Create methods to create a Stripe customer and subscribe to a plan
This commit is contained in:
		@ -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 := ""
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user