payment-poc/main.go

457 lines
13 KiB
Go
Raw Normal View History

2023-07-06 11:29:06 +00:00
package main
import (
"embed"
2023-07-27 10:09:38 +00:00
"errors"
2023-07-10 08:10:13 +00:00
"fmt"
2023-07-06 11:29:06 +00:00
"github.com/gin-gonic/gin"
2023-07-10 08:10:13 +00:00
"github.com/google/uuid"
2023-07-06 11:29:06 +00:00
"github.com/joho/godotenv"
2023-07-26 07:51:29 +00:00
"github.com/stripe/stripe-go/v72"
2023-07-10 08:10:13 +00:00
"html/template"
2023-07-06 11:29:06 +00:00
"log"
"net/http"
2023-07-27 20:46:37 +00:00
"os"
"payment-poc/database"
2023-07-10 08:10:13 +00:00
"payment-poc/migration"
2023-07-31 07:21:54 +00:00
"payment-poc/mock"
2023-07-26 07:51:29 +00:00
"payment-poc/state"
stripe2 "payment-poc/stripe"
"payment-poc/viva"
2023-07-10 08:10:13 +00:00
"payment-poc/wspay"
"strconv"
"strings"
2023-07-06 11:29:06 +00:00
"time"
)
//go:embed db/dev/*.sql
var devMigrations embed.FS
2023-07-27 20:46:37 +00:00
type PaymentProvider interface {
2023-07-31 07:21:54 +00:00
CreatePaymentUrl(entry database.PaymentEntry) (updatedEntry database.PaymentEntry, url string, err error)
2023-07-27 20:46:37 +00:00
CompleteTransaction(entry database.PaymentEntry, amount int64) (database.PaymentEntry, error)
CancelTransaction(entry database.PaymentEntry) (database.PaymentEntry, error)
2023-07-31 07:21:54 +00:00
UpdatePayment(entry database.PaymentEntry) (updatedEntry database.PaymentEntry, err error)
2023-07-27 20:46:37 +00:00
}
2023-07-10 08:10:13 +00:00
2023-07-06 11:29:06 +00:00
func init() {
godotenv.Load()
2023-07-10 08:10:13 +00:00
2023-07-06 11:29:06 +00:00
log.SetPrefix("")
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func main() {
client, err := connectToDb()
if err != nil {
log.Fatalf("couldn't connect to db: %v", err)
}
if err := migration.InitializeMigrations(client, devMigrations); err != nil {
log.Fatalf("couldn't execute migrations: %v", err)
}
g := gin.Default()
2023-07-27 20:46:37 +00:00
if !hasProfile("no-auth") {
g.Use(gin.BasicAuth(getAccounts()))
}
2023-07-10 08:10:13 +00:00
g.SetFuncMap(template.FuncMap{
2023-07-31 07:21:54 +00:00
"formatCurrency": formatCurrency,
"formatCurrencyPtr": formatCurrencyPtr,
"decimalCurrency": decimalCurrency,
"formatState": formatState,
"omitempty": omitempty,
2023-07-10 08:10:13 +00:00
})
2023-07-06 11:29:06 +00:00
g.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"message": "no action on given url", "created": time.Now()})
})
g.NoMethod(func(c *gin.Context) {
c.JSON(http.StatusMethodNotAllowed, gin.H{"message": "no action on given method", "created": time.Now()})
})
2023-07-10 08:10:13 +00:00
2023-07-27 20:46:37 +00:00
backendUrl := envMustExist("BACKEND_URL")
paymentGateways := map[state.PaymentGateway]PaymentProvider{}
2023-07-31 07:21:54 +00:00
entryProvider := &database.PaymentEntryProvider{DB: client}
2023-07-27 20:46:37 +00:00
g.LoadHTMLGlob("./templates/*.gohtml")
2023-07-31 07:21:54 +00:00
if hasProfile(string(state.GatewayMock)) {
mockService := mock.Service{
BackendUrl: backendUrl,
}
mockHandlers(g.Group("mock"), entryProvider, &mockService)
paymentGateways[state.GatewayMock] = &mockService
}
2023-07-27 20:46:37 +00:00
if hasProfile(string(state.GatewayWsPay)) {
wspayService := wspay.Service{
ShopId: envMustExist("WSPAY_SHOP_ID"),
ShopSecret: envMustExist("WSPAY_SHOP_SECRET"),
BackendUrl: backendUrl,
}
2023-07-31 07:21:54 +00:00
wsPayHandlers(g.Group("wspay"), entryProvider, &wspayService)
2023-07-27 20:46:37 +00:00
paymentGateways[state.GatewayWsPay] = &wspayService
2023-07-10 08:10:13 +00:00
}
2023-07-27 20:46:37 +00:00
if hasProfile(string(state.GatewayStripe)) {
stripeService := stripe2.Service{
ApiKey: envMustExist("STRIPE_KEY"),
BackendUrl: backendUrl,
}
2023-07-31 07:21:54 +00:00
stripeHandlers(g.Group("stripe"), entryProvider, &stripeService)
2023-07-27 20:46:37 +00:00
paymentGateways[state.GatewayStripe] = &stripeService
stripe.Key = envMustExist("STRIPE_KEY")
2023-07-26 07:51:29 +00:00
}
2023-07-27 20:46:37 +00:00
if hasProfile(string(state.GatewayVivaWallet)) {
vivaService := viva.Service{
ClientId: envMustExist("VIVA_WALLET_CLIENT_ID"),
ClientSecret: envMustExist("VIVA_WALLET_CLIENT_SECRET"),
SourceCode: envMustExist("VIVA_WALLET_SOURCE_CODE"),
MerchantId: envMustExist("VIVA_WALLET_MERCHANT_ID"),
ApiKey: envMustExist("VIVA_WALLET_API_KEY"),
}
2023-07-31 07:21:54 +00:00
vivaHandlers(g.Group("viva"), entryProvider, &vivaService)
2023-07-27 20:46:37 +00:00
paymentGateways[state.GatewayVivaWallet] = &vivaService
}
2023-07-10 08:10:13 +00:00
2023-07-06 11:29:06 +00:00
g.GET("/", func(c *gin.Context) {
2023-07-27 20:46:37 +00:00
entries, _ := entryProvider.FetchAll()
c.HTML(200, "index.gohtml", gin.H{"Entries": entries})
2023-07-26 07:51:29 +00:00
})
g.GET("/methods", func(c *gin.Context) {
amount, err := strconv.ParseFloat(c.Query("amount"), 64)
if err != nil {
amount = 10.00
}
2023-07-31 07:21:54 +00:00
c.HTML(200, "methods.gohtml", gin.H{"Amount": amount, "Gateways": mapGateways(paymentGateways)})
})
2023-07-31 07:21:54 +00:00
g.GET("/methods/:gateway", func(c *gin.Context) {
2023-07-27 20:46:37 +00:00
gateway, err := fetchGateway(c.Param("gateway"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
if paymentGateway, contains := paymentGateways[gateway]; contains {
amount, err := fetchAmount(c.Query("amount"))
if err != nil {
2023-07-27 20:46:37 +00:00
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-31 07:21:54 +00:00
entry, err := entryProvider.CreateEntry(database.PaymentEntry{
Gateway: gateway,
State: state.StatePreinitialized,
TotalAmount: amount,
})
if entry, url, err := paymentGateway.CreatePaymentUrl(entry); err == nil {
entryProvider.UpdateEntry(entry)
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
} else {
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
} else {
c.AbortWithError(http.StatusBadRequest, errors.New("unsupported payment gateway: "+string(gateway)))
2023-07-26 07:51:29 +00:00
return
}
})
2023-07-30 10:14:05 +00:00
g.GET("/entries/:id", func(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
entry, err := entryProvider.FetchById(id)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
c.HTML(200, "info.gohtml", gin.H{"Entry": entry})
})
2023-07-27 20:46:37 +00:00
g.POST("/entries/:id/complete", func(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
2023-07-27 20:46:37 +00:00
entry, err := entryProvider.FetchById(id)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
if paymentGateway, ok := paymentGateways[entry.Gateway]; ok {
amount, err := fetchAmount(c.PostForm("amount"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
entry, err = paymentGateway.CompleteTransaction(entry, amount)
2023-07-30 10:14:05 +00:00
if err == nil {
2023-07-27 20:46:37 +00:00
entryProvider.UpdateEntry(entry)
c.Redirect(http.StatusSeeOther, "/entries/"+id.String())
} else {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
} else {
if err != nil {
c.AbortWithError(http.StatusInternalServerError, errors.New("payment gateway not supported: "+string(entry.Gateway)))
return
}
}
})
2023-07-27 20:46:37 +00:00
g.POST("/entries/:id/cancel", func(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
2023-07-27 20:46:37 +00:00
entry, err := entryProvider.FetchById(id)
if err != nil {
2023-07-27 20:46:37 +00:00
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
if paymentGateway, ok := paymentGateways[entry.Gateway]; ok {
entry, err = paymentGateway.CancelTransaction(entry)
2023-07-30 10:14:05 +00:00
if err == nil {
2023-07-27 20:46:37 +00:00
entryProvider.UpdateEntry(entry)
c.Redirect(http.StatusSeeOther, "/entries/"+id.String())
} else {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
} else {
if err != nil {
c.AbortWithError(http.StatusInternalServerError, errors.New("payment gateway not supported: "+string(entry.Gateway)))
return
}
}
})
2023-07-31 07:21:54 +00:00
g.POST("/entries/:id/refresh", func(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
entry, err := entryProvider.FetchById(id)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
if paymentGateway, ok := paymentGateways[entry.Gateway]; ok {
entry, err = paymentGateway.UpdatePayment(entry)
if err == nil {
entryProvider.UpdateEntry(entry)
}
c.Redirect(http.StatusSeeOther, "/entries/"+id.String())
} else {
if err != nil {
c.AbortWithError(http.StatusInternalServerError, errors.New("payment gateway not supported: "+string(entry.Gateway)))
return
}
}
})
2023-07-27 20:46:37 +00:00
log.Fatal(http.ListenAndServe(":5281", g))
}
2023-07-26 07:51:29 +00:00
2023-07-31 07:21:54 +00:00
func mockHandlers(g *gin.RouterGroup, provider *database.PaymentEntryProvider, mockService *mock.Service) {
g.GET("/gateway/:id", func(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
entry, err := provider.FetchById(id)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
c.HTML(http.StatusOK, "mock_gateway.gohtml", gin.H{"Entry": entry})
})
g.GET("success", func(c *gin.Context) {
url, err := mockService.HandleResponse(c, provider, state.StateAccepted)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Redirect(http.StatusSeeOther, url)
})
g.GET("error", func(c *gin.Context) {
url, err := mockService.HandleResponse(c, provider, state.StateError)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Redirect(http.StatusSeeOther, url)
})
}
func mapGateways(gateways map[state.PaymentGateway]PaymentProvider) map[string]string {
providerMap := map[string]string{}
for key := range gateways {
providerMap[string(key)] = mapGatewayName(key)
}
return providerMap
}
func mapGatewayName(key state.PaymentGateway) string {
switch key {
case state.GatewayStripe:
return "Stripe"
case state.GatewayVivaWallet:
return "Viva wallet"
case state.GatewayWsPay:
return "WsPay"
case state.GatewayMock:
return "mock"
}
return ""
}
2023-07-27 20:46:37 +00:00
func fetchGateway(gateway string) (state.PaymentGateway, error) {
switch gateway {
case string(state.GatewayWsPay):
return state.GatewayWsPay, nil
case string(state.GatewayStripe):
return state.GatewayStripe, nil
case string(state.GatewayVivaWallet):
return state.GatewayVivaWallet, nil
2023-07-31 07:21:54 +00:00
case string(state.GatewayMock):
return state.GatewayMock, nil
2023-07-27 20:46:37 +00:00
}
return "", errors.New("unknown gateway: " + gateway)
}
2023-07-26 07:51:29 +00:00
2023-07-27 20:46:37 +00:00
func getAccounts() gin.Accounts {
auth := strings.Split(envMustExist("AUTH"), ":")
return gin.Accounts{auth[0]: auth[1]}
}
2023-07-26 07:51:29 +00:00
2023-07-27 20:46:37 +00:00
func fetchAmount(amount string) (int64, error) {
if amount, err := strconv.ParseFloat(amount, 64); err == nil {
return int64(amount * 100), nil
} else {
return 0, err
}
}
2023-07-31 07:21:54 +00:00
func vivaHandlers(g *gin.RouterGroup, provider *database.PaymentEntryProvider, vivaService *viva.Service) {
2023-07-27 20:46:37 +00:00
g.GET("success", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := vivaService.HandleResponse(c, provider, state.StateAccepted)
2023-07-27 20:46:37 +00:00
if err != nil {
2023-07-26 07:51:29 +00:00
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
2023-07-26 07:51:29 +00:00
})
g.GET("error", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := vivaService.HandleResponse(c, provider, state.StateError)
2023-07-26 07:51:29 +00:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
})
}
2023-07-26 07:51:29 +00:00
2023-07-31 07:21:54 +00:00
func stripeHandlers(g *gin.RouterGroup, provider *database.PaymentEntryProvider, stripeService *stripe2.Service) {
2023-07-26 07:51:29 +00:00
2023-07-27 20:46:37 +00:00
g.GET("success", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := stripeService.HandleResponse(c, provider, state.StateAccepted)
2023-07-27 20:46:37 +00:00
if err != nil {
2023-07-26 07:51:29 +00:00
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
2023-07-26 07:51:29 +00:00
})
2023-07-27 20:46:37 +00:00
g.GET("error", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := stripeService.HandleResponse(c, provider, state.StateError)
2023-07-26 07:51:29 +00:00
if err != nil {
2023-07-27 20:46:37 +00:00
c.AbortWithError(http.StatusInternalServerError, err)
2023-07-26 07:51:29 +00:00
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
2023-07-10 08:10:13 +00:00
})
2023-07-26 07:51:29 +00:00
}
2023-07-31 07:21:54 +00:00
func wsPayHandlers(g *gin.RouterGroup, provider *database.PaymentEntryProvider, wspayService *wspay.Service) {
2023-07-27 20:46:37 +00:00
g.GET("/initialize/:id", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
entry, err := provider.FetchById(uuid.MustParse(c.Param("id")))
2023-07-10 08:10:13 +00:00
if err != nil {
2023-07-27 20:46:37 +00:00
c.AbortWithError(http.StatusNotFound, err)
2023-07-10 08:10:13 +00:00
return
}
2023-07-31 07:21:54 +00:00
if entry.State != state.StatePreinitialized {
2023-07-10 08:10:13 +00:00
c.AbortWithError(http.StatusBadRequest, err)
return
}
2023-07-27 20:46:37 +00:00
form := wspayService.InitializePayment(entry)
2023-07-10 08:10:13 +00:00
2023-07-26 07:51:29 +00:00
c.HTML(200, "wspay.gohtml", gin.H{"Action": wspay.AuthorisationForm, "Form": form})
2023-07-10 08:10:13 +00:00
})
2023-07-27 10:09:38 +00:00
2023-07-26 07:51:29 +00:00
g.GET("success", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := wspayService.HandleSuccessResponse(c, provider)
2023-07-10 08:10:13 +00:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
2023-07-10 08:10:13 +00:00
})
2023-07-26 07:51:29 +00:00
g.GET("error", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := wspayService.HandleErrorResponse(c, provider, state.StateError)
2023-07-10 08:10:13 +00:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
2023-07-10 08:10:13 +00:00
})
2023-07-26 07:51:29 +00:00
g.GET("cancel", func(c *gin.Context) {
2023-07-31 07:21:54 +00:00
url, err := wspayService.HandleErrorResponse(c, provider, state.StateCanceled)
2023-07-10 08:10:13 +00:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2023-07-27 20:46:37 +00:00
c.Redirect(http.StatusSeeOther, url)
})
}
2023-07-10 08:10:13 +00:00
2023-07-27 20:46:37 +00:00
func hasProfile(profile string) bool {
profiles := strings.Split(os.Getenv("PROFILE"), ",")
for _, p := range profiles {
if profile == strings.TrimSpace(p) {
return true
2023-07-10 08:10:13 +00:00
}
2023-07-27 20:46:37 +00:00
}
return false
}
2023-07-10 08:10:13 +00:00
2023-07-27 20:46:37 +00:00
func formatState(stt state.PaymentState) string {
switch stt {
case state.StateCanceled:
2023-07-30 10:14:05 +00:00
return "Otkazana"
2023-07-27 20:46:37 +00:00
case state.StateVoided:
2023-07-31 07:21:54 +00:00
return "Poništena"
2023-07-27 20:46:37 +00:00
case state.StateAccepted:
2023-07-30 10:14:05 +00:00
return "Predautorizirana"
2023-07-27 20:46:37 +00:00
case state.StateError:
return "Greška"
2023-07-30 10:14:05 +00:00
case state.StatePreinitialized:
return "Predinicijalizirana"
2023-07-27 20:46:37 +00:00
case state.StateInitialized:
2023-07-30 10:14:05 +00:00
return "Inicijalizirana"
2023-07-27 20:46:37 +00:00
case state.StateCanceledInitialization:
2023-07-30 10:14:05 +00:00
return "Otkazana tijekom izrade"
2023-07-27 20:46:37 +00:00
case state.StateCompleted:
2023-07-30 10:14:05 +00:00
return "Autorizirana"
2023-07-27 20:46:37 +00:00
}
return "nepoznato stanje '" + string(stt) + "'"
}
func formatCurrency(current int64) string {
return fmt.Sprintf("%d,%02d", current/100, current%100)
}
2023-07-31 07:21:54 +00:00
func formatCurrencyPtr(current *int64) string {
if current != nil {
return fmt.Sprintf("%d,%02d", (*current)/100, (*current)%100)
} else {
return "-"
}
}
2023-07-27 20:46:37 +00:00
func decimalCurrency(current int64) string {
return fmt.Sprintf("%d,%02d", current/100, current%100)
}
func omitempty(value string) string {
if value == "" {
return "-"
}
return value
2023-07-10 08:10:13 +00:00
}