Skip to content

Commit

Permalink
[fix] #144, #145
Browse files Browse the repository at this point in the history
  • Loading branch information
yoneyan committed Aug 4, 2022
1 parent dca1440 commit a66bcfb
Show file tree
Hide file tree
Showing 11 changed files with 136 additions and 281 deletions.
9 changes: 5 additions & 4 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,6 @@ func UserRestAPI() {
// Payment
//
v1.POST("/payment/membership", payment.MembershipPayment)
v1.POST("/payment/donate", payment.DonatePayment)
v1.PUT("/payment/card", payment.ChangeCardPayment)
v1.GET("/payment/card", payment.ChangeCardPaymentInit)

Expand All @@ -309,16 +308,18 @@ func UserRestAPI() {
v1.POST("/request", ticket.Request)
v1.PUT("/support/:id", ticket.Update)

// User Delete
// User ID Get

// Group Delete
//v1.DELETE("/group", group.Delete)

//v1.POST("/support/:id", chat.Add)
}
}

//
// Stripe
//
router.POST("/stripe", payment.GetStripeWebHook)

ws := router.Group("/ws")
{
v1 := ws.Group("/v1")
Expand Down
18 changes: 6 additions & 12 deletions pkg/api/core/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import (
"time"
)

// Payment Type
const PaymentMembership = 1
const PaymentDonate = 2

type User struct {
gorm.Model
Tokens []*Token `json:"tokens"`
Notice []*Notice `json:"notice" gorm:"many2many:user_notice;"`
Ticket []Ticket `json:"tickets"`
Group *Group `json:"group"`
Payment []Payment `json:"payment_membership"`
GroupID *uint `json:"group_id"`
Name string `json:"name"`
NameEn string `json:"name_en"`
Expand All @@ -25,12 +28,10 @@ type User struct {

type Payment struct {
gorm.Model
User *User `json:"user"`
Group *Group `json:"group"`
UserID uint `json:"user_id"`
GroupID *uint `json:"group_id"`
PaymentIntentID string `json:"payment_intent_id"`
IsMembership *bool `json:"is_membership"`
Type uint `json:"type"`
Paid *bool `json:"paid"`
Refund *bool `json:"refund"`
Fee uint `json:"fee"`
Expand All @@ -40,7 +41,7 @@ type Payment struct {
type Group struct {
gorm.Model
Users []User `json:"users"`
Payment []Payment `json:"payment_membership"`
Payment Payment `json:"payment_membership"`
Services []Service `json:"services"`
Tickets []Ticket `json:"tickets"`
Memos []Memo `json:"memos"`
Expand Down Expand Up @@ -272,13 +273,6 @@ type PaymentCouponTemplate struct {
Comment string `json:"comment"`
}

type PaymentDonateTemplate struct {
gorm.Model
Name string `json:"name"`
Fee uint `json:"fee"`
Comment string `json:"comment"`
}

type ServiceTemplate struct {
gorm.Model
Hidden *bool `json:"hidden"`
Expand Down
59 changes: 1 addition & 58 deletions pkg/api/core/payment/v0/payment.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ import (
"github.com/homenoc/dsbd-backend/pkg/api/core/tool/config"
dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0"
dbPayment "github.com/homenoc/dsbd-backend/pkg/api/store/payment/v0"
dbPaymentDonateTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_donate/v0"
dbPaymentMembershipTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_membership/v0"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/customer"
"github.com/stripe/stripe-go/v72/paymentintent"
"github.com/stripe/stripe-go/v72/paymentmethod"
"github.com/stripe/stripe-go/v72/setupintent"
"github.com/stripe/stripe-go/v72/sub"
Expand Down Expand Up @@ -84,10 +82,9 @@ func MembershipPayment(c *gin.Context) {
}

dbPayment.Create(&core.Payment{
UserID: result.User.ID,
GroupID: result.User.GroupID,
PaymentIntentID: pi.LatestInvoice.PaymentIntent.ID,
IsMembership: &[]bool{true}[0],
Type: core.PaymentMembership,
Paid: &[]bool{false}[0],
Fee: resultTemplate.Fee,
})
Expand All @@ -106,60 +103,6 @@ func MembershipPayment(c *gin.Context) {
})
}

func DonatePayment(c *gin.Context) {
var input payment.Input
userToken := c.Request.Header.Get("USER_TOKEN")
accessToken := c.Request.Header.Get("ACCESS_TOKEN")

err := c.BindJSON(&input)
if err != nil {
log.Println(err)
c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()})
return
}

result := auth.UserAuthorization(core.Token{UserToken: userToken, AccessToken: accessToken})
if result.Err != nil {
c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()})
return
}

resultTemplate, err := dbPaymentDonateTemplate.Get(input.ItemID)
if err != nil {
c.JSON(http.StatusBadRequest, common.Error{Error: "template is not found..."})
return
}

stripe.Key = config.Conf.Stripe.SecretKey

params := &stripe.PaymentIntentParams{
Amount: stripe.Int64(int64(resultTemplate.Fee)),
Currency: stripe.String(string(stripe.CurrencyJPY)),
}

pi, err := paymentintent.New(params)
log.Printf("pi.New: %v\n", pi.ClientSecret)
if err != nil {
log.Printf("pi.New: %v", err)
c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"})
return
}

dbPayment.Create(&core.Payment{
UserID: result.User.ID,
PaymentIntentID: pi.ID,
IsMembership: &[]bool{false}[0],
Paid: &[]bool{false}[0],
Fee: resultTemplate.Fee,
})

go noticeSlackPaymentDonatePayment(result.User.ID, resultTemplate.Fee, pi.ID)

c.JSON(http.StatusOK, payment.ResultByUser{
ClientSecret: pi.ClientSecret,
})
}

func ChangeCardPayment(c *gin.Context) {
var input payment.ChangeCardPaymentInit
userToken := c.Request.Header.Get("USER_TOKEN")
Expand Down
201 changes: 119 additions & 82 deletions pkg/api/core/payment/v0/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@ package v0
import (
"encoding/json"
"fmt"
"github.com/ashwanthkumar/slack-go-webhook"
"github.com/gin-gonic/gin"
"github.com/homenoc/dsbd-backend/pkg/api/core"
"github.com/homenoc/dsbd-backend/pkg/api/core/common"
"github.com/homenoc/dsbd-backend/pkg/api/core/group"
"github.com/homenoc/dsbd-backend/pkg/api/core/payment"
"github.com/homenoc/dsbd-backend/pkg/api/core/tool/config"
dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0"
"github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification"
dbPayment "github.com/homenoc/dsbd-backend/pkg/api/store/payment/v0"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/webhook"
"gorm.io/gorm"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"strconv"
)

func GetStripeWebHook(c *gin.Context) {
Expand Down Expand Up @@ -50,87 +48,126 @@ func GetStripeWebHook(c *gin.Context) {

log.Println(event.Type)

if event.Type == "checkout.session.completed" {
log.Println("user", event.Data.Object["metadata"].(map[string]interface{})["user"].(string))
} else if event.Type == "customer.subscription.updated" {
log.Println("customer.subscription.updated: " + event.Data.Object["id"].(string))
} else if event.Type == "invoice.paid" {
log.Println("invoice.paid: " + event.Data.Object["id"].(string))
} else if event.Type == "invoice.updated" {
log.Println("invoice.updated: " + event.Data.Object["id"].(string))
} else if event.Type == "invoice.payment_succeeded" {
log.Println("invoice.payment_succeeded: " + event.Data.Object["id"].(string))
} else if event.Type == "payment_intent.created" {
log.Println("payment_intent.created: " + event.Data.Object["id"].(string))
} else if event.Type == "payment_intent.succeeded" {
log.Println("payment_intent.successed: " + event.Data.Object["id"].(string))
resultPayment, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["id"].(string)})
if err != nil {
log.Println(err)
}

if resultPayment[0].Group == nil {
log.Println("[paid] error: GroupID is not exists....")
return
}

// Membership
if *resultPayment[0].IsMembership {
resultGroup := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: *resultPayment[0].GroupID}})
if resultGroup.Err != nil {
log.Println(resultGroup.Err)
return
}

// now time
now := time.Now()

if resultGroup.Group[0].MemberExpired != nil {
now = *resultGroup.Group[0].MemberExpired
}
// slack notify(payment log)
attachment := slack.Attachment{}
attachment.Text = &[]string{"Payment Log"}[0]
attachment.AddField(slack.Field{Title: "Type", Value: event.Type}).
AddField(slack.Field{Title: "ID", Value: event.ID}).
AddField(slack.Field{Title: "Created", Value: strconv.FormatInt(event.Created, 10)})
notification.SendSlack(notification.Slack{Attachment: attachment, ID: config.ToPaymentLogSlackNotify, Status: true})

if resultGroup.Group[0].PaymentMembershipTemplate.Yearly {
// membership yearly
now = now.AddDate(1, 0, 0)
} else if resultGroup.Group[0].PaymentMembershipTemplate.Monthly {
// membership monthly
now = now.AddDate(0, 1, 0)
} else {
log.Println("error:")
return
}

dbGroup.Update(group.UpdateMembership, core.Group{
Model: gorm.Model{ID: *resultPayment[0].GroupID},
MemberExpired: &now,
if event.Type == "checkout.session.completed" {
// meta
dataType := event.Data.Object["metadata"].(map[string]interface{})["type"].(string)
name := event.Data.Object["metadata"].(map[string]interface{})["name"].(string)
groupID := event.Data.Object["metadata"].(map[string]interface{})["group_id"].(string)
etc := ""
// stripe standard data
amountTotal := event.Data.Object["amount_total"].(float64)
paymentIntent := event.Data.Object["payment_intent"].(string)
if dataType == "donate" {
dbPayment.Create(&core.Payment{
Type: core.PaymentMembership,
GroupID: nil,
Refund: &[]bool{false}[0],
PaymentIntentID: paymentIntent,
Fee: uint(amountTotal),
})
etc += "UserName: " + name
} else if dataType == "membership" {
etc += "GroupID: " + groupID
}

err = dbPayment.Update(payment.UpdatePaid, &core.Payment{
PaymentIntentID: event.Data.Object["id"].(string),
Paid: &[]bool{true}[0],
})
if err != nil {
log.Println(err)
}

noticeSlackPaymentPaid(event.Data.Object["id"].(string))

} else if event.Type == "charge.succeeded" {
log.Printf("charge.succeeded: " + event.Data.Object["id"].(string))
} else if event.Type == "charge.refunded" {
log.Printf("charge.succeeded: " + event.Data.Object["id"].(string) + "| " + event.Data.Object["payment_intent"].(string))
result, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["payment_intent"].(string)})
if err != nil {
log.Println(err)
}
err = dbPayment.Update(payment.UpdateAll, &core.Payment{
Model: gorm.Model{ID: result[0].ID},
Refund: &[]bool{true}[0],
})
if err != nil {
log.Println(err)
}
// slack notify(payment log)
attachment = slack.Attachment{}
attachment.Text = &[]string{"Payment"}[0]
attachment.AddField(slack.Field{Title: "Type", Value: dataType}).
AddField(slack.Field{Title: "ID", Value: event.ID}).
AddField(slack.Field{Title: "PaymentIntent", Value: paymentIntent}).
AddField(slack.Field{Title: "Etc", Value: etc}).
AddField(slack.Field{Title: "Fee", Value: strconv.Itoa(int(uint(amountTotal))) + "円"})
notification.SendSlack(notification.Slack{Attachment: attachment, ID: config.ToPaymentSlackNotify, Status: true})

//log.Println("user", event.Data.Object["metadata"].(map[string]interface{})["user"].(string))
//} else if event.Type == "customer.subscription.updated" {
// log.Println("customer.subscription.updated: " + event.Data.Object["id"].(string))
//} else if event.Type == "invoice.paid" {
// log.Println("invoice.paid: " + event.Data.Object["id"].(string))
//} else if event.Type == "invoice.updated" {
// log.Println("invoice.updated: " + event.Data.Object["id"].(string))
//} else if event.Type == "invoice.payment_succeeded" {
// log.Println("invoice.payment_succeeded: " + event.Data.Object["id"].(string))
//} else if event.Type == "payment_intent.created" {
// log.Println("payment_intent.created: " + event.Data.Object["id"].(string))
//} else if event.Type == "payment_intent.succeeded" {
// log.Println("payment_intent.successed: " + event.Data.Object["id"].(string))
// resultPayment, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["id"].(string)})
// if err != nil {
// log.Println(err)
// }
//
// // Membership
// if *resultPayment[0].IsMembership {
// if resultPayment[0].Group == nil {
// log.Println("[paid] error: GroupID is not exists....")
// return
// }
//
// resultGroup := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: *resultPayment[0].GroupID}})
// if resultGroup.Err != nil {
// log.Println(resultGroup.Err)
// return
// }
//
// // now time
// now := time.Now()
//
// if resultGroup.Group[0].MemberExpired != nil {
// now = *resultGroup.Group[0].MemberExpired
// }
//
// if resultGroup.Group[0].PaymentMembershipTemplate.Yearly {
// // membership yearly
// now = now.AddDate(1, 0, 0)
// } else if resultGroup.Group[0].PaymentMembershipTemplate.Monthly {
// // membership monthly
// now = now.AddDate(0, 1, 0)
// } else {
// log.Println("error:")
// return
// }
//
// dbGroup.Update(group.UpdateMembership, core.Group{
// Model: gorm.Model{ID: *resultPayment[0].GroupID},
// MemberExpired: &now,
// })
// }
//
// err = dbPayment.Update(payment.UpdatePaid, &core.Payment{
// PaymentIntentID: event.Data.Object["id"].(string),
// Paid: &[]bool{true}[0],
// })
// if err != nil {
// log.Println(err)
// }
//
// noticeSlackPaymentPaid(event.Data.Object["id"].(string))
//
//} else if event.Type == "charge.succeeded" {
// log.Printf("charge.succeeded: " + event.Data.Object["id"].(string))
//} else if event.Type == "charge.refunded" {
// log.Printf("charge.succeeded: " + event.Data.Object["id"].(string) + "| " + event.Data.Object["payment_intent"].(string))
// result, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["payment_intent"].(string)})
// if err != nil {
// log.Println(err)
// }
// err = dbPayment.Update(payment.UpdateAll, &core.Payment{
// Model: gorm.Model{ID: result[0].ID},
// Refund: &[]bool{true}[0],
// })
// if err != nil {
// log.Println(err)
// }

}

Expand Down
Loading

0 comments on commit a66bcfb

Please sign in to comment.