Hey there, fellow Go developer! Ready to add some payment magic to your app? Let's dive into integrating Razorpay's API using the awesome razorpay-go package. Razorpay is a popular payment gateway in India, and with this guide, you'll be processing payments like a pro in no time.
Before we jump in, make sure you've got:
Got all that? Great! Let's get our hands dirty.
First things first, let's create a new Go project and grab the razorpay-go package:
mkdir razorpay-integration cd razorpay-integration go mod init razorpay-integration go get github.com/razorpay/razorpay-go
Now, let's create a client instance with your API keys:
package main import ( "github.com/razorpay/razorpay-go" ) func main() { client := razorpay.NewClient("YOUR_KEY_ID", "YOUR_KEY_SECRET") }
Easy peasy, right? You're now ready to start making API calls!
Let's create an order for your customer:
data := map[string]interface{}{ "amount": 50000, // amount in paise "currency": "INR", "receipt": "some_receipt_id", } order, err := client.Order.Create(data, nil)
After the payment, you'll want to verify the signature:
attributes := map[string]string{ "razorpay_order_id": "order_ID", "razorpay_payment_id": "payment_ID", "razorpay_signature": "signature", } err := client.Utility.VerifyPaymentSignature(attributes)
Got an authorized payment? Let's capture it:
captureResponse, err := client.Payment.Capture("payment_ID", 50000, nil)
Oops, need to refund? No worries:
refundData := map[string]interface{}{ "amount": 50000, } refund, err := client.Payment.Refund("payment_ID", refundData, nil)
Webhooks are your friends. Set up an endpoint and verify those signatures:
func webhookHandler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Can't read body", http.StatusBadRequest) return } signature := r.Header.Get("X-Razorpay-Signature") secret := "YOUR_WEBHOOK_SECRET" if client.Utility.VerifyWebhookSignature(string(body), signature, secret) { // Process the webhook payload } else { http.Error(w, "Invalid signature", http.StatusBadRequest) } }
Always check for errors and log them properly. Your future self will thank you:
if err != nil { log.Printf("Error: %v", err) // Handle the error appropriately }
Use Razorpay's test mode to simulate transactions. Create different scenarios to ensure your integration handles various cases smoothly.
Ready for the big leagues? Switch to your production API keys and run through this checklist:
And there you have it! You've just built a solid Razorpay integration in Go. Remember, this is just the tip of the iceberg. Razorpay offers a ton of features, so don't be afraid to explore their docs for more advanced stuff.
Keep coding, stay curious, and may your payments always be successful! 🚀💰