DEV Community

Cover image for Set up a Stripe Checkout REST API (+ metadata) using Go and Gin Framework.
Benard Mseti
Benard Mseti

Posted on

8

Set up a Stripe Checkout REST API (+ metadata) using Go and Gin Framework.

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
Enter fullscreen mode Exit fullscreen mode

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,
    })
}
Enter fullscreen mode Exit fullscreen mode

In your routes add the following endpoint

// stripe api
    r.POST("/create-checkout-url/", controllers.CreateCheckoutUrl)
Enter fullscreen mode Exit fullscreen mode

Done, You can now deploy your gin backend and test the API by making a post request to the endpoint we just created.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay