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.

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay