Create methods to create a Stripe customer and subscribe to a plan

This commit is contained in:
vinchent 2024-08-12 14:06:39 +02:00
parent 0b35136d3f
commit fd1d1808f0
2 changed files with 49 additions and 4 deletions

6
go.mod
View File

@ -3,13 +3,11 @@ module myapp
go 1.22.5
require (
github.com/alexedwards/scs/v2 v2.8.0
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/cors v1.2.1
github.com/go-sql-driver/mysql v1.8.1
github.com/stripe/stripe-go/v79 v79.6.0
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/alexedwards/scs/v2 v2.8.0 // indirect
)
require filippo.io/edwards25519 v1.1.0 // indirect

View File

@ -2,8 +2,10 @@ package cards
import (
"github.com/stripe/stripe-go/v79"
"github.com/stripe/stripe-go/v79/customer"
"github.com/stripe/stripe-go/v79/paymentintent"
"github.com/stripe/stripe-go/v79/paymentmethod"
"github.com/stripe/stripe-go/v79/subscription"
)
type Card struct {
@ -71,6 +73,51 @@ func (c *Card) RetrievePaymentIntent(id string) (*stripe.PaymentIntent, error) {
return pi, nil
}
func (c *Card) SubscribeToPlan(
cust *stripe.Customer,
plan, email, last4, cardType string,
) (string, error) {
stripeCustomerID := cust.ID
items := []*stripe.SubscriptionItemsParams{
{Plan: stripe.String(plan)},
}
params := &stripe.SubscriptionParams{
Customer: stripe.String(stripeCustomerID),
Items: items,
}
params.AddMetadata("last_four", last4)
params.AddMetadata("card_type", cardType)
params.AddExpand("latest_invoice.payment_intent")
subscription, err := subscription.New(params)
if err != nil {
return "", err
}
return subscription.ID, nil
}
func (c *Card) CreateCustomer(pm, email string) (*stripe.Customer, string, error) {
stripe.Key = c.Secret
customerParams := &stripe.CustomerParams{
PaymentMethod: stripe.String(pm),
Email: stripe.String(email),
InvoiceSettings: &stripe.CustomerInvoiceSettingsParams{
DefaultPaymentMethod: stripe.String(pm),
},
}
cust, err := customer.New(customerParams)
if err != nil {
msg := ""
if stripeErr, ok := err.(*stripe.Error); ok {
msg = cardErrorMessage(stripeErr.Code)
}
return nil, msg, err
}
return cust, "", nil
}
func cardErrorMessage(code stripe.ErrorCode) string {
msg := ""