golang Stripe支付API集成客户端插件库stripe的使用

Golang Stripe支付API集成客户端插件库stripe的使用

介绍

这是Stripe官方提供的Go客户端库,用于集成Stripe支付API到你的Go应用中。

要求

  • Go 1.18或更高版本

安装

确保你的项目使用了Go Modules(如果已经使用,根目录会有go.mod文件):

go mod init

然后在Go程序中引用stripe-go:

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

或者显式地获取包:

go get -u github.com/stripe/stripe-go/v82

使用示例

创建客户

sc := stripe.NewClient(apiKey)
params := &stripe.CustomerCreateParams{
	Description:      stripe.String("Stripe Developer"),
	Email:            stripe.String("gostripe@stripe.com"),
	PreferredLocales: stripe.StringSlice([]string{"en", "es"}),
}

c, err := sc.V1Customers.Create(context.TODO(), params)

支付意图

sc := stripe.NewClient(apiKey)
params := &stripe.PaymentIntentListParams{
	Customer: stripe.String(customer.ID),
}

for pi, err := range sc.V1PaymentIntents.List(context.TODO(), params) {
	// 处理错误
	// 执行操作
}

事件处理

sc := stripe.NewClient(apiKey)
for e, err := range sc.V1Events.List(context.TODO(), nil) {
	// 通过e.GetObjectValue("resource_name_based_on_type", "resource_property_name")访问事件数据
	// 或者通过e.Data.Object["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]访问

	// 通过e.GetPreviousValue("resource_name_based_on_type", "resource_property_name")访问先前属性
	// 或者通过e.Data.PreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]访问
}

完整客户操作示例

import "github.com/stripe/stripe-go/v82"

// 设置
sc := stripe.NewClient("sk_key")

// 创建
c, err := sc.V1Customers.Create(context.TODO(), &stripe.CustomerCreateParams{})

// 检索
c, err := sc.V1Customers.Retrieve(context.TODO(), id, &stripe.CustomerRetrieveParams{})

// 更新
c, err := sc.V1Customers.Update(context.TODO(), id, &stripe.CustomerUpdateParams{})

// 删除
c, err := sc.V1Customers.Delete(context.TODO(), id, &stripe.CustomerDeleteParams{})

// 列表
for c, err := range sc.Customers.List(context.TODO(), &stripe.CustomerListParams{}) {
	// 处理错误
	// 执行操作
}

Webhook签名验证

Stripe可以对发送到你的端点的webhook事件进行签名,允许你验证它们不是由第三方发送的。

测试Webhook签名

你可以使用stripe.GenerateTestSignedPayload来模拟来自Stripe的webhook事件:

payload := map[string]interface{}{
	"id":          "evt_test_webhook",
	"object":      "event",
	"api_version": stripe.APIVersion,
}
testSecret := "whsec_test_secret"

payloadBytes, err := json.Marshal(payload)

signedPayload := stripe.GenerateTestSignedPayload(&webhook.UnsignedPayload{Payload: payloadBytes, Secret: testSecret})
event, err := stripe.ConstructEvent(signedPayload.Payload, signedPayload.Header, signedPayload.Secret)

if event.ID == payload["id"] {
	// 对模拟的签名事件执行操作
} else {
	// 处理无效的事件负载
}

高级用法

访问最后响应

使用任何APIResource上的LastResponse来查看生成当前对象的API响应:

coupon, err := sc.V1Coupons.Create(...)
requestID := coupon.LastResponse.RequestID

自动重试

库会自动在间歇性故障(如连接错误、超时或某些API响应如状态409 Conflict)时重试请求。

自定义日志

默认情况下,库只记录错误消息(发送到stderr)。你可以配置默认日志:

stripe.DefaultLeveledLogger = &stripe.LeveledLogger{
    Level: stripe.LevelInfo,
}

扩展对象

所有stripe-go中的可扩展对象都采用完整资源结构的形式,但除非请求扩展,否则只填充该结构的ID字段。

插件开发

如果你正在编写使用该库的插件,我们希望你使用stripe.SetAppInfo来标识:

stripe.SetAppInfo(&stripe.AppInfo{
	Name:    "MyAwesomePlugin",
	URL:     "https://myawesomeplugin.info",
	Version: "1.2.34",
})

测试

我们使用just来方便地运行开发任务。你可以直接使用它们,或者从justfile中复制命令。

这个包依赖于stripe-mock,所以确保从后台终端获取并运行它:

go get -u github.com/stripe/stripe-mock
stripe-mock

运行所有测试:

just test
# 或者: go test ./...

运行一个包的测试:

just test ./invoice
# 或者: go test ./invoice

运行单个测试:

just test ./invoice -run TestInvoiceGet
# 或者: go test ./invoice -run TestInvoiceGet

更多关于golang Stripe支付API集成客户端插件库stripe的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang Stripe支付API集成客户端插件库stripe的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang Stripe支付API集成指南

Stripe是一个流行的支付处理平台,提供了完善的API用于集成支付功能到应用中。下面我将介绍如何在Golang中使用Stripe官方库进行支付集成。

安装Stripe库

首先安装Stripe的Go SDK:

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

基本配置

package main

import (
	"log"
	"github.com/stripe/stripe-go/v72"
	"github.com/stripe/stripe-go/v72/client"
)

func main() {
	// 设置Stripe API密钥
	stripe.Key = "sk_test_your_test_secret_key"
	
	// 或者使用客户端模式
	sc := &client.API{}
	sc.Init("sk_test_your_test_secret_key", nil)
}

核心功能实现

1. 创建支付意向(Payment Intent)

func createPaymentIntent(amount int64, currency string) (*stripe.PaymentIntent, error) {
	params := &stripe.PaymentIntentParams{
		Amount:   stripe.Int64(amount),
		Currency: stripe.String(currency),
		// 可选: 设置支付方式类型
		PaymentMethodTypes: stripe.StringSlice([]string{
			"card",
		}),
	}
	
	return paymentintent.New(params)
}

// 使用示例
intent, err := createPaymentIntent(1000, "usd") // 10美元
if err != nil {
	log.Fatal(err)
}
log.Printf("Payment Intent created: %v", intent.ID)

2. 确认支付

func confirmPaymentIntent(paymentIntentID, paymentMethodID string) (*stripe.PaymentIntent, error) {
	params := &stripe.PaymentIntentConfirmParams{
		PaymentMethod: stripe.String(paymentMethodID),
	}
	return paymentintent.Confirm(paymentIntentID, params)
}

3. 创建客户

func createCustomer(email, name string) (*stripe.Customer, error) {
	params := &stripe.CustomerParams{
		Email: stripe.String(email),
		Name:  stripe.String(name),
	}
	return customer.New(params)
}

4. 创建订阅

func createSubscription(customerID, priceID string) (*stripe.Subscription, error) {
	params := &stripe.SubscriptionParams{
		Customer: stripe.String(customerID),
		Items: []*stripe.SubscriptionItemsParams{
			{
				Price: stripe.String(priceID),
			},
		},
	}
	return sub.New(params)
}

5. 处理Webhook事件

func handleWebhook(payload []byte, signature, secret string) (stripe.Event, error) {
	event, err := webhook.ConstructEvent(payload, signature, secret)
	if err != nil {
		return stripe.Event{}, err
	}

	switch event.Type {
	case "payment_intent.succeeded":
		var paymentIntent stripe.PaymentIntent
		err := json.Unmarshal(event.Data.Raw, &paymentIntent)
		if err != nil {
			return stripe.Event{}, err
		}
		log.Printf("Payment succeeded: %v", paymentIntent.ID)
	case "payment_intent.payment_failed":
		var paymentIntent stripe.PaymentIntent
		err := json.Unmarshal(event.Data.Raw, &paymentIntent)
		if err != nil {
			return stripe.Event{}, err
		}
		log.Printf("Payment failed: %v", paymentIntent.ID)
	}

	return event, nil
}

完整示例:创建并确认支付

package main

import (
	"fmt"
	"log"

	"github.com/stripe/stripe-go/v72"
	"github.com/stripe/stripe-go/v72/customer"
	"github.com/stripe/stripe-go/v72/paymentintent"
	"github.com/stripe/stripe-go/v72/paymentmethod"
)

func main() {
	stripe.Key = "sk_test_your_test_secret_key"

	// 1. 创建客户
	customerParams := &stripe.CustomerParams{
		Email: stripe.String("customer@example.com"),
		Name:  stripe.String("John Doe"),
	}
	c, err := customer.New(customerParams)
	if err != nil {
		log.Fatal(err)
	}

	// 2. 创建支付方式(信用卡)
	pmParams := &stripe.PaymentMethodParams{
		Type: stripe.String("card"),
		Card: &stripe.PaymentMethodCardParams{
			Number:   stripe.String("4242424242424242"),
			ExpMonth: stripe.String("12"),
			ExpYear:  stripe.String("2030"),
			CVC:      stripe.String("123"),
		},
	}
	pm, err := paymentmethod.New(pmParams)
	if err != nil {
		log.Fatal(err)
	}

	// 3. 将支付方式附加到客户
	attachParams := &stripe.PaymentMethodAttachParams{
		Customer: stripe.String(c.ID),
	}
	_, err = paymentmethod.Attach(pm.ID, attachParams)
	if err != nil {
		log.Fatal(err)
	}

	// 4. 创建支付意向
	piParams := &stripe.PaymentIntentParams{
		Amount:        stripe.Int64(1000), // $10.00
		Currency:      stripe.String("usd"),
		Customer:      stripe.String(c.ID),
		PaymentMethod: stripe.String(pm.ID),
		Confirm:       stripe.Bool(true),
		OffSession:    stripe.Bool(true),
	}
	pi, err := paymentintent.New(piParams)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Payment Intent created: %v, Status: %v\n", pi.ID, pi.Status)
}

最佳实践

  1. 密钥管理:不要将密钥硬编码在代码中,使用环境变量或密钥管理服务
  2. 错误处理:正确处理所有可能的API错误
  3. 测试:使用Stripe的测试模式和测试卡号进行充分测试
  4. 日志记录:记录所有重要的支付事件
  5. Webhook验证:始终验证Webhook签名

总结

通过Stripe的Go SDK,我们可以方便地集成支付功能到Golang应用中。本文介绍了支付意向、客户管理、订阅和Webhook处理等核心功能。实际应用中还需要考虑错误处理、重试逻辑和安全措施等更多细节。

Stripe文档非常完善,建议参考官方文档获取最新信息:Stripe官方文档

回到顶部