Stripe API + Go:将多个产品从模型发送到结账会话

pvcm50d1  于 2023-05-04  发布在  Go
关注(0)|答案(1)|浏览(161)

我想从我的sqlite数据库发送更多的产品,以条纹结帐会议,但我不知道我怎么能做。我更喜欢使用“for”循环,但我如何在这段代码中实现它。

我的单品编码:

var cart []models.Cart

Db.Where("user_id = ?", user_id).Find(&cart)

params := &stripe.CheckoutSessionParams{
    Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
    LineItems: []*stripe.CheckoutSessionLineItemParams{
        &stripe.CheckoutSessionLineItemParams{
            PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
                Currency: stripe.String("usd"),
                ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
                    Name: stripe.String(cart[0].Product_title),
                },
                UnitAmount: stripe.Int64(cart[0].Product_price * 100),
            },
            Quantity: stripe.Int64(1),
        },
    },
    SuccessURL: stripe.String("http://localhost:3000/member/order/success"),
    CancelURL:  stripe.String("http://localhost:3000/member/order/cancel"),
}
h43kikqp

h43kikqp1#

stripeBody是你从body中解析出来的body,然后循环抛出你的lineItems,然后把它放在一个像stripeItems这样的变量中,然后把它添加到params中

var stripeItems []*stripe.CheckoutSessionLineItemParams
for _, cart := range stripeBody.Cart {
    stripeItems = append(stripeItems, &stripe.CheckoutSessionLineItemParams{
        PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
            Currency: stripe.String("usd"),
            ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
                Name:   stripe.String(cart.Name),
                Images: stripe.StringSlice([]string{cart.Image}),
            },
            UnitAmount: stripe.Int64(int64(cart.Price) * 100),
        },
        Quantity: stripe.Int64(cart.Quantity),
    })
}


params := &stripe.CheckoutSessionParams{
    Mode:          stripe.String(string(stripe.CheckoutSessionModePayment)),
    LineItems:     stripeItems,
    CustomerEmail: &stripeBody.Address.Email,
    SuccessURL:    stripe.String(domain + "/success"),
    CancelURL:     stripe.String(domain + "/cancel"),
}
s, err := session.New(params)

相关问题