Implementing payment APIs for a go backend may be a struggle not only for gin framework developers that are just starting out but also the ones that have been using the framework for a while.
This article will show how to simply integrate a stripe checkout REST API that will produce links to a stripe checkout screen for your users to perform payments in your apps.
First install stripe package using this command
go get -u github.com/stripe/stripe-go/v74
Now add this controller
func CreateCheckoutUrl(c *gin.Context) {
var body struct {
Amount int64 `form:"amount"`
ReceiptEmail string `form:"email"`
Metadata string `form:"metadata"`
}
if err := c.Bind(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to read body",
})
return
}
apiKey := os.Getenv("STRIPE_SECRET_KEY")
stripe.Key = apiKey
domain := "https://your.domain.com/"
params := &stripe.CheckoutSessionParams{
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("usd"),
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
Name: stripe. String("Product Name Here"),
},
TaxBehavior: stripe.String("exclusive"),
UnitAmount: stripe.Int64(body.Amount * 100),
},
Quantity: stripe.Int64(1),
},
},
CustomerEmail: &body.ReceiptEmail,
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
SuccessURL: stripe.String(domain + "/"),
CancelURL: stripe.String(domain + "/"),
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{Enabled: stripe.Bool(true)},
}
params.AddMetadata("id", body.Metadata)
fmt.Println("params - ", params)
s, err := session.New(params)
if err != nil {
log.Printf("Error creating session: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"checkout_url": s.URL,
})
}
In your routes add the following endpoint
// stripe api
r.POST("/create-checkout-url/", controllers.CreateCheckoutUrl)
Done, You can now deploy your gin backend and test the API by making a post request to the endpoint we just created.
Top comments (0)