How to use Stripe in Go

Stripe is one of the most widely used payment platforms in the world. In this article, we will see how to use Stripe's APIs with the Go programming language.

Installing the Stripe Library

To interact with Stripe in Go, we need to install the official Stripe SDK package for Go.

go get github.com/stripe/stripe-go/v78

Configuring the API Key

Before performing any operations, we need to configure the API key provided by Stripe.


package main

import (
    "github.com/stripe/stripe-go/v78"
    "github.com/stripe/stripe-go/v78/customer"
)

func main() {
    stripe.Key = "sk_test_XXXXXXXXXXXXXXXXXXXXXXX"
}

Creating a Customer

We can create a customer in Stripe using the customer package.


params := &stripe.CustomerParams{
    Email: stripe.String("customer@example.com"),
    Name:  stripe.String("Mario Rossi"),
}
c, err := customer.New(params)
if err != nil {
    log.Fatalf("Error creating customer: %v", err)
}
fmt.Printf("Customer created: %s", c.ID)

Creating a Payment

To process a card payment, we can use the paymentintent endpoint.


import "github.com/stripe/stripe-go/v78/paymentintent"

params := &stripe.PaymentIntentParams{
    Amount:   stripe.Int64(1000),
    Currency: stripe.String("eur"),
    PaymentMethodTypes: stripe.StringSlice([]string{"card"}),
}
pi, err := paymentintent.New(params)
if err != nil {
    log.Fatalf("Error creating payment: %v", err)
}
fmt.Printf("Payment created: %s", pi.ID)

Handling Webhooks

Webhooks allow you to receive notifications about payment events. Here is an example of handling a webhook in Go.


import (
    "net/http"
    "io"
    "github.com/stripe/stripe-go/v78/webhook"
)

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    payload, _ := io.ReadAll(r.Body)
    event, err := webhook.ConstructEvent(payload, r.Header.Get("Stripe-Signature"), "webhook_secret")
    if err != nil {
        http.Error(w, "Error parsing webhook", http.StatusBadRequest)
        return
    }
    fmt.Printf("Event received: %s", event.Type)
}

Conclusion

In this article, we explored how to integrate Stripe's APIs into a Go application. We saw how to configure the API key, create a customer, process a payment, and handle webhooks.

Back to top