Hey there, fellow Go developer! Ready to add some payment magic to your app? Let's dive into integrating Stripe's API using the awesome stripe-go package. Buckle up, because we're about to make your app a money-making machine!
Before we jump in, make sure you've got:
go get github.com/stripe/stripe-go/v72
)First things first, let's create a new Go project:
mkdir stripe-integration cd stripe-integration go mod init stripe-integration
Now, let's import the packages we need:
package main import ( "fmt" "github.com/stripe/stripe-go/v72" "github.com/stripe/stripe-go/v72/customer" // We'll add more as we go along ) func main() { // The fun starts here! }
Time to get that Stripe client up and running:
func main() { stripe.Key = "your_stripe_secret_key" // Pro tip: Use environment variables for your API key in production! }
Let's create a Stripe customer:
params := &stripe.CustomerParams{ Email: stripe.String("[email protected]"), Name: stripe.String("Jenny Rosen"), } newCustomer, err := customer.New(params) if err != nil { // Uh-oh, something went wrong! fmt.Printf("Error creating customer: %v\n", err) return } fmt.Printf("Success! Created customer: %s\n", newCustomer.ID)
Now, let's add a payment method to our customer:
import "github.com/stripe/stripe-go/v72/paymentmethod" // ... in your main function params := &stripe.PaymentMethodParams{ Type: stripe.String("card"), Card: &stripe.PaymentMethodCardParams{ Number: stripe.String("4242424242424242"), ExpMonth: stripe.Int64(12), ExpYear: stripe.Int64(2023), CVC: stripe.String("314"), }, } pm, err := paymentmethod.New(params) if err != nil { fmt.Printf("Error creating payment method: %v\n", err) return } // Attach the payment method to the customer attachParams := &stripe.PaymentMethodAttachParams{ Customer: stripe.String(newCustomer.ID), } pm, err = paymentmethod.Attach(pm.ID, attachParams) if err != nil { fmt.Printf("Error attaching payment method: %v\n", err) return }
Let's charge our customer:
import "github.com/stripe/stripe-go/v72/charge" // ... in your main function chargeParams := &stripe.ChargeParams{ Amount: stripe.Int64(2000), // $20.00 Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String(newCustomer.ID), Description: stripe.String("My First Test Charge (created for API docs)"), } ch, err := charge.New(chargeParams) if err != nil { fmt.Printf("Error creating charge: %v\n", err) return } fmt.Printf("Success! Charged: %v\n", ch.ID)
Always check for errors after each Stripe operation. Logging is your friend:
if err != nil { log.Printf("Error: %v\n", err) // Handle the error appropriately }
Setting up webhooks is crucial for real-time updates. Here's a quick example:
import ( "encoding/json" "net/http" "github.com/stripe/stripe-go/v72/webhook" ) func handleWebhook(w http.ResponseWriter, req *http.Request) { const MaxBodyBytes = int64(65536) req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes) payload, err := ioutil.ReadAll(req.Body) if err != nil { fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err) w.WriteHeader(http.StatusServiceUnavailable) return } event, err := webhook.ConstructEvent(payload, req.Header.Get("Stripe-Signature"), "your_webhook_secret") if err != nil { fmt.Fprintf(os.Stderr, "Error verifying webhook signature: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } // Handle the event switch event.Type { case "payment_intent.succeeded": // Handle successful payment case "payment_intent.payment_failed": // Handle failed payment default: fmt.Fprintf(os.Stderr, "Unhandled event type: %s\n", event.Type) } w.WriteHeader(http.StatusOK) }
Use Stripe's test mode and their test card numbers to verify your integration. Write unit tests for your Stripe functions to ensure they're working as expected.
When deploying, remember:
And there you have it! You've just built a Stripe integration in Go. Pretty cool, right? Remember, this is just scratching the surface. Stripe's API is powerful and flexible, so don't be afraid to explore and experiment.
For more in-depth info, check out Stripe's official docs and the stripe-go GitHub repo.
Now go forth and process those payments like a boss! 💰🚀