You need to enable JavaScript to run this app. Go+Gin接入Stripe Checkout报undefined: session编译错误排查
优惠活动
大模型
产品
解决方案
定价
更多

Go+Gin接入Stripe Checkout报undefined: session编译错误排查

编译报错原因排查与修复

undefined: session 错误的直接触发原因

  • 你当前仅导入了Stripe Go SDK的根包github.com/stripe/stripe-go/v71,但SDK中用于操作Checkout支付会话的session类型与方法,实际定义在独立的子包github.com/stripe/stripe-go/v71/checkout/session路径下。既没有导入该子包,也没有通过全路径前缀引用对应符号,Go编译器自然无法识别未定义的session标识符,直接抛出undefined: session编译错误。

代码中连带存在的其他编译问题

就算修复了未导入包的问题,现有代码还有多处会阻断编译的问题:

  • 缺少标准库log包的导入:代码中直接调用log.Println(err),未导入对应包会触发第二个未定义错误
  • 代码块括号嵌套错误:r.Run(":8080")被错误嵌套在了GET路由的回调函数内部,回调函数的闭合括号缺失,会触发语法解析错误
  • 货币参数值写法错误:Currency: stripe.String("stripe.String(stripe.CurrencyEUR)") 把整段Go代码当成长字符串传入参数,实际应该将EUR常量转成字符串后传入
  • 字段访问权限错误:返回响应时取的s.id是小写开头的私有字段,SDK返回的会话对象中,可外部访问的会话ID字段为大写开头的s.ID
  • 错误处理逻辑缺失:创建会话失败时没有中断路由响应流程,会继续执行后续逻辑

修复后可正常编译的参考实现

package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	stripe "github.com/stripe/stripe-go/v71"
	"github.com/stripe/stripe-go/v71/checkout/session"
)

func main() {
	r := gin.Default()
	// 全局设置Stripe密钥,无需在每次路由请求中重复赋值
	stripe.Key = "sk_test_MyKey............"

	r.GET("/buy/:id", func(c *gin.Context) {
		params := &stripe.CheckoutSessionParams{
			PaymentMethodTypes: stripe.StringSlice([]string{
				"card",
				"ideal",
			}),
			LineItems: []*stripe.CheckoutSessionLineItemParams{
				{
					PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
						Currency: stripe.String(string(stripe.CurrencyEUR)),
						ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
							Name: stripe.String("T-shirt"),
						},
						UnitAmount: stripe.Int64(2000),
					},
					Quantity: stripe.Int64(1),
				},
			},
			Mode:       stripe.String("payment"),
			SuccessURL: stripe.String("https://example.com/success?session_id={CHECKOUT_SESSION_ID}"),
			CancelURL:  stripe.String("https://example.com/cancel"),
		}
		s, err := session.New(params)
		if err != nil {
			log.Println(err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"SessionID": s.ID,
		})
	})
	r.Run(":8080")
}

内容的提问来源于stack exchange,提问作者Ueda Takeyuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 10:15:10