### Install and Run Stripe Mock Source: https://github.com/stripe/stripe-go/blob/master/README.md Install the stripe-mock tool and run it in the background. This is required for testing the Stripe Go client library. ```bash go get -u github.com/stripe/stripe-mock stripe-mock ``` -------------------------------- ### Global Configuration Example Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Demonstrates setting a global API key and making a customer creation call using package-level functions. ```go stripe.APIKey = "sk_test_123" cust, err := customer.New(params) // uses the global stripe.APIKey ``` -------------------------------- ### Install Public Preview Stripe Go SDK Source: https://github.com/stripe/stripe-go/blob/master/README.md Specify a public preview version of the Stripe Go SDK in your go.mod file. These versions may have breaking changes without major version bumps. ```go require ( ... github.com/stripe/stripe-go/v86 ... ) ``` -------------------------------- ### Get Customer using Legacy Pattern Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the legacy resource pattern to get a customer by ID. Requires importing `github.com/stripe/stripe-go/v86/customer`. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) // Setup stripe.Key = "sk_key" // Set backend (optional, useful for mocking) // stripe.SetBackend("api", backend) // Get c, err := customer.Get(id, &stripe.CustomerParams{}) ``` -------------------------------- ### Use Mocked Stripe Client in Go Unit Tests Source: https://github.com/stripe/stripe-go/blob/master/README.md Initialize and use a mocked Stripe client in Go unit tests with GoMock. This example demonstrates setting up expectations and asserting client method calls. ```go import ( "example/hello/mocks" t"testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stripe/stripe-go/v86" ) func UseMockedStripeClient(t *testing.T) { // Create a mock controller mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() // Create a mock stripe backend mockBackend := mocks.NewMockBackend(mockCtrl) backends := &stripe.Backends{API: mockBackend} client := stripe.NewClient("sk_test", stripe.WithBackends(backends)) // Set up a mock call mockBackend.EXPECT().Call("GET", "/v1/accounts/acc_123", gomock.Any(), gomock.Any(), gomock.Any()). // Return nil error Return(nil). Do(func(method string, path string, key string, params stripe.ParamsContainer, v *stripe.Account) { // Set the return value for the method *v = stripe.Account{ ID: "acc_123", } }).Times(1) // Call the client method acc, _ := client.V1Accounts.GetByID(context.TODO(), "acc_123", nil) // Asset the result assert.Equal(t, "acc_123", acc.ID) } ``` -------------------------------- ### Get Stripe Go Package Source: https://github.com/stripe/stripe-go/blob/master/README.md Explicitly get the Stripe Go package using the go get command. ```bash go get -u github.com/stripe/stripe-go/v86 ``` -------------------------------- ### V2 Amount Type Declaration (Before) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Example of declaring a variable with the specific V2 Amount type before consolidation. ```go // Before var amt *stripe.V2CoreAccountIdentityBusinessDetailsAnnualRevenueAmount ``` -------------------------------- ### Migrate Customer retrieval from Get to Retrieve Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Customer retrieval method changed from `Get` to `Retrieve`. Parameter types also changed from `CustomerParams` to `CustomerRetrieveParams`. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() sc.Customers.Get(params) ``` ```go params := &stripe.CustomerRetrieveParams{...} sc.V1Customers.Retrieve(context.TODO(), params) ``` -------------------------------- ### V2 Amount Type Declaration (After) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Example of declaring a variable with the consolidated `stripe.Amount` type after consolidation. ```go // After var amt *stripe.Amount ``` -------------------------------- ### Run Tests for a Specific Package Source: https://github.com/stripe/stripe-go/blob/master/README.md Run tests for a particular package within the Stripe Go client library. For example, to test the 'invoice' package. ```bash just test ./invoice # or: go test ./invoice ``` -------------------------------- ### Initialize Go Project with Modules Source: https://github.com/stripe/stripe-go/blob/master/README.md Initialize a new Go project to use Go Modules for dependency management. ```bash go mod init ``` -------------------------------- ### Stripe Client Initialization and Customer Creation Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Shows how to initialize a stripe.Client with an API key and create a customer using the client's V1Customers API. ```go sc := stripe.NewClient("sk_test_123") cust, err := sc.V1Customers.Create(context.TODO(), params) ``` -------------------------------- ### Create Customer with stripe.Client Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.Client` to create a new customer. Requires importing the stripe package. ```go import "github.com/stripe/stripe-go/v86" // Setup sc := stripe.NewClient("sk_key") // To set backends, e.g. for testing, or to customize use this instead: // sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) // Create c, err := sc.V1Customers.Create(context.TODO(), &stripe.CustomerCreateParams{}) ``` -------------------------------- ### List Customers with stripe.Client Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.Client` to list customers. Iterates through results. Requires importing the stripe package. ```go import "github.com/stripe/stripe-go/v86" // Setup sc := stripe.NewClient("sk_key") // To set backends, e.g. for testing, or to customize use this instead: // sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) // List for c, err := range sc.Customers.List(context.TODO(), &stripe.CustomerListParams{}) { // handle err // do something } ``` -------------------------------- ### Add Metadata and Expand using helper methods Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v75 Shows the usage of AddMetadata and AddExpand methods which remain supported. ```go params.AddMetadata("order_id", "6735") params.AddExpand("business_profile") ``` -------------------------------- ### Create Customer using Legacy Pattern Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the legacy resource pattern to create a customer. Requires importing `github.com/stripe/stripe-go/v86/customer`. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) // Setup stripe.Key = "sk_key" // Set backend (optional, useful for mocking) // stripe.SetBackend("api", backend) // Create c, err := customer.New(&stripe.CustomerParams{}) ``` -------------------------------- ### Create stripe.Client with custom backends Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client When passing custom `stripe.Backends`, use `stripe.NewClient(stripeKey, stripe.WithBackends(backends))`. ```go sc := stripe.NewClient(stripeKey, stripe.WithBackends(backends)) ``` -------------------------------- ### Migrating Customer Creation (Old vs. New) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Compares the old global method for creating a customer with the new method using stripe.Client. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() customer.New(params) ``` ```go params := &stripe.CustomerCreateParams{...} sc.V1Customers.Create(context.TODO(), params) ``` -------------------------------- ### Configure AccountParams with Metadata and Expand Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v75 Demonstrates the transition from using an embedded Params struct to direct field assignment for AccountParams. ```go params := &stripe.AccountParams{ Params: stripe.Params{ Expand: []*string{stripe.String("business_profile")}, Metadata: map[string]string{ "order_id": "6735", }, }, } ``` ```go params := &stripe.AccountParams{ Expand: []*string{stripe.String("business_profile")}, Metadata: map[string]string{ "order_id": "6735", }, } ``` -------------------------------- ### Set V2 Decimal Params (Before) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Illustrates setting a V2 decimal parameter using a string before the update. ```go pct := "75.25" params := &stripe.V2CoreAccountCreateParams{ Identity: &stripe.V2CoreAccountCreateIdentityParams{ Individual: &stripe.V2CoreAccountCreateIdentityIndividualParams{ Relationship: &stripe.V2CoreAccountCreateIdentityIndividualRelationshipParams{ PercentOwnership: &pct, // was *string }, }, }, } ``` -------------------------------- ### Configure BackendConfig with Pointers Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v71 Use stripe helper functions to set pointer-based configuration values in BackendConfig. ```go config := &stripe.BackendConfig{ MaxNetworkRetries: stripe.Int64(2), } ``` -------------------------------- ### Configure Per-Backend Logging Source: https://github.com/stripe/stripe-go/blob/master/README.md Configure logging for a specific backend instance. This allows for different logging levels for different configurations. ```go config := &stripe.BackendConfig{ LeveledLogger: &stripe.LeveledLogger{ Level: stripe.LevelInfo, }, } ``` -------------------------------- ### Read V2 Decimal Responses (Before) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Demonstrates reading a V2 decimal response as a string and parsing it to float64. ```go pctStr := *account.Identity.Individual.Relationship.PercentOwnership // string pct, _ := strconv.ParseFloat(pctStr, 64) ``` -------------------------------- ### Run All Tests Source: https://github.com/stripe/stripe-go/blob/master/README.md Execute all tests for the Stripe Go client library using the 'just' command or 'go test'. ```bash just test # or: go test ./... ``` -------------------------------- ### List Customers using Legacy Pattern Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the legacy resource pattern to list customers. Iterates through results. Requires importing `github.com/stripe/stripe-go/v86/customer`. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) // Setup stripe.Key = "sk_key" // Set backend (optional, useful for mocking) // stripe.SetBackend("api", backend) // List i := customer.List(&stripe.CustomerListParams{}) for i.Next() { c := i.Customer() // do something } if err := i.Err(); err != nil { // handle } ``` -------------------------------- ### Migrating Customer List (Old vs. New) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Compares the old global method for listing customers with the new method using stripe.Client. ```go i := customer.List(&stripe.CustomerListParams{}) for i.Next() { cust := i.Customer() // handle cust } if err := i.Err(); err != nil { // handle err } ``` ```go params := &stripe.CustomerListParams{} ctx := context.TODO() for cust, err := range sc.V1Customers.List(ctx, params).All(ctx) { // handle err // handle cust } ``` -------------------------------- ### Replace client.New with stripe.NewClient Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Use `stripe.NewClient(apiKey)` to create a new client. This replaces the older `client.New(apiKey, nil)` pattern. ```regex /client.New\((.*), nil\)/stripe.NewClient($1)/ ``` -------------------------------- ### Retrieve Customer with stripe.Client Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.Client` to retrieve an existing customer by ID. Requires importing the stripe package. ```go import "github.com/stripe/stripe-go/v86" // Setup sc := stripe.NewClient("sk_key") // To set backends, e.g. for testing, or to customize use this instead: // sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) // Retrieve c, err := sc.V1Customers.Retrieve(context.TODO(), id, &stripe.CustomerRetrieveParams{}) ``` -------------------------------- ### Migrate Customer creation from New to Create Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Customer creation method changed from `New` to `Create`. Parameter types also changed from `CustomerParams` to `CustomerCreateParams`. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() sc.Customers.New(params) ``` ```go params := &stripe.CustomerCreateParams{...} sc.V1Customers.Create(context.TODO(), params) ``` -------------------------------- ### Migrate Customer list iteration Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client List methods now return `iter.Seq2` and can be ranged over directly. The `Next`, `Current`, and `Err` calls are no longer needed. ```go i := sc.Customers.List(&stripe.CustomerListParams{}) for i.Next() { cust := i.Customer() // handle cust } if err := i.Err(); err != nil { // handle err } ``` ```go params := &stripe.CustomerListParams{} ctx := context.TODO() for cust, err := range sc.V1Customers.List(ctx, params).All(ctx) { // handle err // handle cust } ``` -------------------------------- ### Iterate Over Customer Search Results with .All() Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Similar to list methods, append `.All(ctx)` to the Search method to iterate over search results. This applies to search methods returning `*V1SearchList[*T]`. ```go // Before for customer, err := range client.V1Customers.Search(ctx, params) { ... } // After for customer, err := range client.V1Customers.Search(ctx, params).All(ctx) { ... } ``` -------------------------------- ### V2 Amount Type Consolidation (Before) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Illustrates referencing a V2 monetary amount before type consolidation, using a specific Amount type. ```go // Before // amount was *stripe.V2CoreAccountIdentityBusinessDetailsAnnualRevenue Amount amount := account.Identity.BusinessDetails.AnnualRevenue.Amount fmt.Println(amount.Value) // int64 fmt.Println(amount.Currency) // stripe.Currency ``` -------------------------------- ### Iterate Over Customer List with .All() Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 To iterate over a customer list, append `.All(ctx)` to the List method call. This change applies to both V1 and V2 list methods. ```go // Before for customer, err := range client.V1Customers.List(ctx, params) { if err != nil { return err } fmt.Println(customer.ID) } // After for customer, err := range client.V1Customers.List(ctx, params).All(ctx) { if err != nil { return err } fmt.Println(customer.ID) } ``` -------------------------------- ### Create Stripe Client for Google AppEngine Source: https://github.com/stripe/stripe-go/blob/master/README.md Create a per-request Stripe client using a custom HTTP client for Google AppEngine environments. This is necessary because http.DefaultClient is not available. ```go import ( "fmt" "net/http" "google.golang.org/appengine" "google.golang.org/appengine/urlfetch" "github.com/stripe/stripe-go/v86" ) func handler(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) httpClient := urlfetch.Client(ctx) backends := stripe.NewBackends(httpClient) sc := stripe.NewClient("sk_test_123", stripe.WithBackends(backends)) params := &stripe.CustomerCreateParams{ Description: stripe.String("Stripe Developer"), Email: stripe.String("gostripe@stripe.com"), } customer, err := sc.V1Customers.Create(ctx, params) if err != nil { fmt.Fprintf(w, "Could not create customer: %v", err) return } fmt.Fprintf(w, "Customer created: %v", customer.ID) } ``` -------------------------------- ### Set V2 Decimal Params (After) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Shows how to set a V2 decimal parameter using float64 after the update. Requires Go 1.26+ for direct literal or use `stripe.Float64()`. ```go pct := 75.25 params := &stripe.V2CoreAccountCreateParams{ Identity: &stripe.V2CoreAccountCreateIdentityParams{ Individual: &stripe.V2CoreAccountCreateIdentityIndividualParams{ Relationship: &stripe.V2CoreAccountCreateIdentityIndividualRelationshipParams{ PercentOwnership: &pct, // now *float64 }, }, }, } ``` -------------------------------- ### Import Stripe Go Package Source: https://github.com/stripe/stripe-go/blob/master/README.md Import the Stripe Go package and its submodules into your Go program. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) ``` -------------------------------- ### Update Customer with stripe.Client Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.Client` to update an existing customer by ID. Requires importing the stripe package. ```go import "github.com/stripe/stripe-go/v86" // Setup sc := stripe.NewClient("sk_key") // To set backends, e.g. for testing, or to customize use this instead: // sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) // Update c, err := sc.V1Customers.Update(context.TODO(), id, &stripe.CustomerUpdateParams{}) ``` -------------------------------- ### Migrating Customer Retrieval (Old vs. New) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Compares the old global method for retrieving a customer with the new method using stripe.Client. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() customer.Get(params) ``` ```go params := &stripe.CustomerRetrieveParams{...} sc.V1Customers.Retrieve(context.TODO(), params) ``` -------------------------------- ### Discount Customer Expandable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Notes that `Discount.Customer` maps to `string` but is an expandable `*Customer`. ```APIDOC ## Discount Customer Expandable ### Description `Discount.Customer` maps to `string` but is an expandable `*Customer`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Migrating Customer Update (Old vs. New) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Compares the old global method for updating a customer with the new method using stripe.Client. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() customer.Update(params) ``` ```go params := &stripe.CustomerUpdateParams{...} sc.V1Customers.Update(context.TODO(), params) ``` -------------------------------- ### Generate Stripe Go Mock Backend Source: https://github.com/stripe/stripe-go/blob/master/README.md Use mockgen to generate a mock implementation of the Backend interface for unit testing. ```bash mockgen -destination=mocks/backend.go -package=mocks github.com/stripe/stripe-go/v86 Backend ``` -------------------------------- ### Billing Portal Configuration Application Expandable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Indicates that `BillingPortalConfiguration.Application` is expandable. ```APIDOC ## Billing Portal Configuration Application Expandable ### Description `BillingPortalConfiguration.Application` is expandable. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Callback-Style Iteration with .All() Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 For callback-style iteration, append `.All(ctx)` to the List method before providing the callback function. This ensures compatibility with the new return types. ```go // Before client.V1Customers.List(ctx, params)(func(customer *stripe.Customer, err error) bool { // handle customer return true }) // After client.V1Customers.List(ctx, params).All(ctx)(func(customer *stripe.Customer, err error) bool { // handle customer return true }) ``` -------------------------------- ### Set Beta Headers for Private Preview Features Source: https://github.com/stripe/stripe-go/blob/master/README.md To access private preview features with a release version of the SDK, set a beta header directly in the request parameters. Use the `Stripe-Version` header with the appropriate preview version and feature flags. ```go params := &stripe.CustomerCreateParams{ ... Params: stripe.Params{ Headers: http.Header{ "Stripe-Version": []string{"2025-10-29.preview; beta_feature_1=v3; beta_feature_2=v1"}, }, }, } ``` -------------------------------- ### Configure Stripe-go to Log Informational Messages Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v71 Set the DefaultLeveledLogger to LevelInfo to revert to the previous behavior of logging informational messages and errors. ```go stripe.DefaultLeveledLogger = &stripe.LeveledLogger{ Level: stripe.LevelInfo, } ``` -------------------------------- ### Configure LeveledLogger Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v71 Set the logging level globally or within a specific BackendConfig instance. ```go stripe.DefaultLeveledLogger = &stripe.LeveledLogger{ Level: stripe.LevelDebug, } ``` ```go config := &stripe.BackendConfig{ LeveledLogger: &stripe.LeveledLogger{ Level: stripe.LevelDebug, }, } ``` -------------------------------- ### Application Fee Application Expandable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Notes that `ApplicationFee.Application` is expandable. ```APIDOC ## Application Fee Application Expandable ### Description `ApplicationFee.Application` is expandable. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Identify Plugin Using Stripe-go Source: https://github.com/stripe/stripe-go/blob/master/README.md Set application information using `stripe.SetAppInfo` to identify your plugin when it makes calls to the Stripe API. This helps Stripe understand the ecosystem using their services. ```go stripe.SetAppInfo(&stripe.AppInfo{ Name: "MyAwesomePlugin", URL: "https://myawesomeplugin.info", Version: "1.2.34", }) ``` -------------------------------- ### Expand Objects With Expansion Source: https://github.com/stripe/stripe-go/blob/master/README.md Retrieve a resource and request expansion of specific related objects. This populates additional fields beyond just the ID for the expanded objects. ```go // // With expansion // p := &stripe.ChargeCreateParams{} p.AddExpand("customer") c, _ = sc.V1Charges.Retrieve(context.TODO(), "ch_123", p) c.Customer.ID // ID is still available c.Customer.Name // Name is now also available (if it had a value) ``` -------------------------------- ### List Stripe PaymentIntents for a Customer Source: https://github.com/stripe/stripe-go/blob/master/README.md List all PaymentIntents associated with a specific customer. The customer ID must be provided in the parameters. ```go sc := stripe.NewClient(apiKey) params := &stripe.PaymentIntentListParams{ Customer: stripe.String(customer.ID), } for pi, err := range sc.V1PaymentIntents.List(context.TODO(), params) { // handle err // do something } ``` -------------------------------- ### Accessing Per-Page Data from List Structs Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 The `V1List/V2List` structs now expose per-page data. Use `.Data()`, `.Meta()`, `.Err()`, and `.LastResponse()` to access current page data, list metadata, fetch errors, and the last API response respectively. ```go list := client.V1Customers.List(ctx, params) data := list.Data() // []*stripe.Customer for the current page meta := list.Meta() // stripe.ListMeta — includes HasMore err := list.Err() // error from fetching the current page resp := list.LastResponse() // *stripe.APIResponse with RawJSON ``` -------------------------------- ### Update Customer using Legacy Pattern Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the legacy resource pattern to update a customer by ID. Requires importing `github.com/stripe/stripe-go/v86/customer`. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) // Setup stripe.Key = "sk_key" // Set backend (optional, useful for mocking) // stripe.SetBackend("api", backend) // Update c, err := customer.Update(id, &stripe.CustomerParams{}) ``` -------------------------------- ### Migrating Customer Deletion (Old vs. New) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Compares the old global method for deleting a customer with the new method using stripe.Client. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() customer.Del(params) ``` ```go params := &stripe.CustomerDeleteParams{...} sc.V1Customers.Delete(context.TODO(), params) ``` -------------------------------- ### Create a Stripe Customer Source: https://github.com/stripe/stripe-go/blob/master/README.md Create a new customer in Stripe using the V1Customers.Create method. Ensure the API key is set before calling this method. ```go 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) ``` -------------------------------- ### Delete Customer with stripe.Client Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.Client` to delete a customer by ID. Requires importing the stripe package. ```go import "github.com/stripe/stripe-go/v86" // Setup sc := stripe.NewClient("sk_key") // To set backends, e.g. for testing, or to customize use this instead: // sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) // Delete c, err := sc.V1Customers.Delete(context.TODO(), id, &stripe.CustomerDeleteParams{}) ``` -------------------------------- ### Run a Single Specific Test Source: https://github.com/stripe/stripe-go/blob/master/README.md Execute a single test case within a specific package. This is useful for targeted debugging. ```bash just test ./invoice -run TestInvoiceGet # or: go test ./invoice -run TestInvoiceGet ``` -------------------------------- ### Migrate Customer update from Update to Update Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Customer update method remains `Update`, but parameter types changed from `CustomerParams` to `CustomerUpdateParams`. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() sc.Customers.Update(params) ``` ```go params := &stripe.CustomerUpdateParams{...} sc.V1Customers.Update(context.TODO(), params) ``` -------------------------------- ### Delete Customer using Legacy Pattern Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the legacy resource pattern to delete a customer by ID. Requires importing `github.com/stripe/stripe-go/v86/customer`. ```go import ( "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/customer" ) // Setup stripe.Key = "sk_key" // Set backend (optional, useful for mocking) // stripe.SetBackend("api", backend) // Delete c, err := customer.Del(id, &stripe.CustomerParams{}) ``` -------------------------------- ### Update PlanParams: ProductID to Product.ID Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Replaces the direct `ProductID` field with a nested `Product.ID` structure in `PlanParams` for specifying the associated product. ```go // Before params := &stripe.PlanParams{ ProductID: stripe.String("prod_12345abc"), } // After params := &stripe.PlanParams{ Product: &stripe.PlanProductParams{ ``` -------------------------------- ### Customer Source Parameter Type Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Clarifies that `CustomerParams.Source` maps to `*SourceParams` but should be the ID of a source, represented as `*string`. ```APIDOC ## Customer Source Parameter Type ### Description `CustomerParams.Source` maps to `*SourceParams` but should be the ID of a source, represented as `*string`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Set Stripe-Account Header for Connect Source: https://github.com/stripe/stripe-go/blob/master/README.md Set the Stripe-Account header on list parameters to perform actions on behalf of a connected account. ```go // For a list request listParams := &stripe.CustomerListParams{} listParams.SetStripeAccount("acct_123") ``` -------------------------------- ### Method-specific Params for AppsSecret creation Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Parameter objects are now method-specific. `AppsSecretParams` is replaced by `AppsSecretCreateParams` and nested scope parameters are also updated. ```go params := &stripe.CustomerParams{Name: stripe.String("Jenny Rosen")} params.Context = context.TODO() sc.Customers.Del("cus_123", params) // ❌ -- runtime error from Stripe: Name param not allowed ``` ```go params := &stripe.AppsSecretParams{ Name: stripe.String("sec_123"), Payload: stripe.String("very secret string"), Scope: &stripe.AppsSecretScopeParams{ Type: stripe.String(stripe.AppsSecretScopeTypeAccount), }, } ``` ```go params := &stripe.AppsSecretCreateParams{ Name: stripe.String("sec_123"), Payload: stripe.String("very secret string"), Scope: &stripe.AppsSecretCreateScopeParams{ Type: stripe.String(stripe.AppsSecretScopeTypeAccount), }, } ``` -------------------------------- ### Discount Checkout Session Not Expandable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 States that `Discount.CheckoutSession` maps to `*CheckoutSession` but is not expandable. ```APIDOC ## Discount Checkout Session Not Expandable ### Description `Discount.CheckoutSession` maps to `*CheckoutSession` but is not expandable. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Global Logging Level Source: https://github.com/stripe/stripe-go/blob/master/README.md Set the global logging level for the stripe-go library. By default, only error messages are logged. Use LevelInfo to log more detailed information. ```go stripe.DefaultLeveledLogger = &stripe.LeveledLogger{ Level: stripe.LevelInfo, } ``` -------------------------------- ### Read V2 Decimal Responses (After) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Shows reading a V2 decimal response directly as a float64. ```go pct := account.Identity.Individual.Relationship.PercentOwnership // float64 fmt.Println(pct) // 75.25 ``` -------------------------------- ### Add Parameter Struct for CreditNote ListPreviewLines in Stripe Go Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Introduces a separate parameter struct, CreditNotePreviewParams, for the CreditNote ListPreviewLines method (renamed to PreviewLines). This organizes nested parameters like Lines and CreditNoteLineParams. ```go type CreditNotePreviewParams struct { Lines *CreditNoteLineItemListPreviewParams } type CreditNoteLineItemListPreviewParams struct { Lines []*CreditNotePreviewLineParams } ``` -------------------------------- ### Migrate Customer deletion from Del to Delete Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client Customer deletion method changed from `Del` to `Delete`. Parameter types also changed from `CustomerParams` to `CustomerDeleteParams`. ```go params := &stripe.CustomerParams{...} params.Context = context.TODO() sc.Customers.Del(params) ``` ```go params := &stripe.CustomerDeleteParams{...} sc.V1Customers.Delete(context.TODO(), params) ``` -------------------------------- ### Add Beta Version Header for Preview Features Source: https://github.com/stripe/stripe-go/blob/master/README.md Use stripe.AddBetaVersion to set the Stripe-Version header for specific preview features. This function is only available in public preview SDKs. ```go stripe.AddBetaVersion("feature_beta", "v3") ``` -------------------------------- ### Update AccountParams: RequestedCapabilities to Capabilities Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Replaces the deprecated `RequestedCapabilities` field with the `Capabilities` struct in `AccountParams`. Use `stripe.Bool(true)` to request a capability. ```go // Before params := &stripe.AccountParams{ RequestedCapabilities: ["card_payments"], } // After params := &stripe.AccountParams{ Capabilities: &stripe.AccountCapabilitiesParams{ CardPayments: &stripe.AccountCapabilitiesCardPaymentsParams{ Requested: stripe.Bool(true), }, }, } ``` -------------------------------- ### Account Capabilities Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Ensures consistency in using `AccountCapabilityStatus` for all `AccountCapabilities` fields. ```APIDOC ## Account Capabilities ### Description Be consistent about using `AccountCapabilityStatus` for all `AccountCapabilities` (all the same enum values). ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### ConstructEventWithOptions for Webhook Verification Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Use ConstructEventWithOptions to control API version mismatch behavior. Set IgnoreAPIVersionMismatch to false to enforce API version checks, consistent with other Stripe libraries. This option is available to replicate previous behavior of ConstructEventIgnoringTolerance and ConstructEventWithTolerance. ```go ConstructEventWithOptions(payload, header, secret, ConstructEventOptions{IgnoreTolerance: true, IgnoreAPIVersionMismatch: false}) ``` ```go ConstructEventWithOptions(payload, header, secret, ConstructEventOptions{Tolerance: tolerance, IgnoreAPIVersionMismatch: false}) ``` -------------------------------- ### Account Company Parameters Address Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Clarifies the difference between `AccountCompanyParams.Address` and `*AccountAddressParams`, noting that `*AccountAddressParams` has a `Town` field not applicable to `AccountCompanyParams.Address`. ```APIDOC ## Account Company Parameters Address ### Description `*AccountAddressParams` had `Town` field that is not applicable to `AccountCompanyParams.Address`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Authenticate with Connect Account Key Source: https://github.com/stripe/stripe-go/blob/master/README.md Authenticate requests using an account's specific keys by passing the access token to stripe.NewClient. ```go import ( "github.com/stripe/stripe-go/v86" ) sc := stripe.NewClient("access_token") ``` -------------------------------- ### Customer Address Nullable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Notes that `Customer.Address` maps to `Address` and is nullable. ```APIDOC ## Customer Address Nullable ### Description `Customer.Address` maps to `Address` and is nullable. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Add PaymentMethodCardNetworks Structs in Stripe Go Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Introduces PaymentMethodCardNetworksAvailable and PaymentMethodCardNetworksPreferred structs to manage available and preferred card networks for payment methods. ```go type PaymentMethodCardNetworksAvailable struct { Acs *bool Visa *bool } type PaymentMethodCardNetworksPreferred struct { Acs *bool Visa *bool } ``` -------------------------------- ### Iterate and Access Raw JSON for List Operations Source: https://github.com/stripe/stripe-go/blob/master/README.md When using `List` operations, access the `RawJSON` of each resource as you iterate through the results. This allows for dynamic inspection of individual resources. ```go for cust, err := range sc.V1Customers.List(context.TODO(), &stripe.CustomerListParams{}) { if err != nil { return err } customerJSON := cust.LastResponse.RawJSON log.Printf("Customer JSON: %s", customerJSON) // {"id":"cus_123",...} } ``` -------------------------------- ### Account Company Parameters Address Kana/Kanji Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Explains that `AccountAddressParams` has been split into separate `AccountCompanyAddressKanaParams` and `AccountCompanyAddressKanjiParams` for `AccountCompanyParams.AddressKana` and `AccountCompanyParams.AddressKanji` respectively. ```APIDOC ## Account Company Parameters Address Kana/Kanji ### Description `AccountAddressParams` has been split into separate `AccountCompanyAddressKanaParams` and `AccountCompanyAddressKanjiParams`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Expand Objects Without Expansion Source: https://github.com/stripe/stripe-go/blob/master/README.md Retrieve a resource without requesting expansion of related objects. Only the ID field of expandable objects will be populated. ```go // // *Without* expansion // c, _ := sc.V1Charges.Retrieve(context.TODO(), "ch_123", nil) c.Customer.ID // Only ID is populated c.Customer.Name // All other fields are always empty ``` -------------------------------- ### V2 Amount Type Consolidation (After) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Shows referencing a V2 monetary amount after type consolidation, using the shared `stripe.Amount` type. ```go // After // amount is now *stripe.Amount amount := account.Identity.BusinessDetails.AnnualRevenue.Amount fmt.Println(amount.Value) // int64 fmt.Println(amount.Currency) // stripe.Currency ``` -------------------------------- ### Account Settings Card Issuing Parameters TOS Acceptance Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Highlights that `AccountTOSAcceptanceParams` has a `ServiceAgreement` field not applicable to `AccountSettingsCardIssuingParams.TOSAcceptance`. ```APIDOC ## Account Settings Card Issuing Parameters TOS Acceptance ### Description `AccountTOSAcceptanceParams` has `ServiceAgreement` field that is not applicable to `AccountSettingsCardIssuingParams.TOSAcceptance`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Setting Nullable Map Values to Clear Entries Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Nullable map values now use pointer types, allowing `nil` to clear an entry. This is useful for clearing specific currency minimum balances in payment settings. ```go params := &stripe.BalanceSettingsUpdateParams{ Payments: &stripe.BalanceSettingsUpdatePaymentsParams{ Payouts: &stripe.BalanceSettingsUpdatePaymentsPayoutsParams{ MinimumBalanceByCurrency: map[string]*int64{ "usd": stripe.Int64(5000), // To clear a currency's minimum balance: "eur": nil }, }, }, } ``` -------------------------------- ### Charge Billing Details Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Notes that `Charge.BillingDetails` maps to `*BillingDetails` and is unshared with `PaymentMethod`. ```APIDOC ## Charge Billing Details ### Description `Charge.BillingDetails` maps to `*BillingDetails` and is unshared with `PaymentMethod`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Update Go Module Imports Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v71 Update import paths to include the major version suffix required for Go Modules support. ```go import ( "github.com/stripe/stripe-go" "github.com/stripe/stripe-go/customer" ) ``` ```go import ( "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/customer" ) ``` -------------------------------- ### Custom Logger Interface Source: https://github.com/stripe/stripe-go/blob/master/README.md Define a custom logger that complies with the Stripe LeveledLoggerInterface. This allows integration with various logging libraries. ```go type LeveledLoggerInterface interface { Debugf(format string, v ...interface{}) Errorf(format string, v ...interface{}) Infof(format string, v ...interface{}) Warnf(format string, v ...interface{}) } ``` -------------------------------- ### Validate BankAccount/Card Parameters in Stripe Go Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Ensures that exactly one of 'params.Account' or 'params.Customer' is set for BankAccount and Card client methods. This prevents ambiguity where previously only one parameter would be used if both were provided. ```go if params.Account == nil && params.Customer == nil { return nil, errors.New("one of account or customer must be set") } if params.Account != nil && params.Customer != nil { return nil, errors.New("one of account or customer must be set") } ``` -------------------------------- ### Add BillingDetails Structs in Stripe Go Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Introduces separate structs, PaymentMethodBillingDetails and PaymentMethodBillingDetailsParams, for handling billing details associated with payment methods. ```go type PaymentMethodBillingDetails struct { Address *Address Email *string Name *string Phone *string } type PaymentMethodBillingDetailsParams struct { Address *AddressParams Email *string Name *string Phone *string } ``` -------------------------------- ### Clearing Fields Using AddExtra (Before v85) Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v85 Before v85, fields were cleared using `AddExtra` with an empty string value. This method is now deprecated in favor of `UnsetFields`. ```go params := &stripe.SubscriptionUpdateParams{} params.AddExtra("pause_collection", "") ``` -------------------------------- ### Configure Automatic Retries Source: https://github.com/stripe/stripe-go/blob/master/README.md Configure the number of automatic retries for network requests. By default, the library retries up to two times. Set MaxNetworkRetries to 0 to disable retries. ```go import ( "github.com/stripe/stripe-go/v86" ) config := &stripe.BackendConfig{ MaxNetworkRetries: stripe.Int64(0), // Zero retries } backends := &stripe.NewBackendWithConfig(config) sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) coupon, err := sc.V1Coupons.Create(...) ``` -------------------------------- ### Mock and Verify Webhook Events with Test Signatures Source: https://github.com/stripe/stripe-go/blob/master/README.md Use `stripe.GenerateTestSignedPayload` to create mock signed webhook events for testing. This allows you to test your webhook handler logic without sending actual events from Stripe. ```go 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"] { // Do something with the mocked signed event } else { // Handle invalid event payload } ``` -------------------------------- ### Make Custom Raw Requests with Stripe Go SDK Source: https://github.com/stripe/stripe-go/blob/master/README.md Send custom requests to undocumented or API endpoints using the rawrequest package. This allows bypassing standard method definitions and specifying request details directly. Supports both JSON and form encoding for v2 and v1 requests respectively. ```go import ( "encoding/json" "fmt" "github.com/stripe/stripe-go/v86" "github.com/stripe/stripe-go/v86/form" "github.com/stripe/stripe-go/v86/rawrequest" ) func make_raw_request() error { stripe.Key = "sk_test_123" b, err := stripe.GetRawRequestBackend(stripe.APIBackend) if err != nil { return err } client := rawrequest.Client{B: b, Key: apiKey} payload := map[string]interface{} { "event_name": "hotdogs_eaten", "payload": map[string]string{ "value": "123", "stripe_customer_id": "cus_Quq8itmW58RMet", } } // for a v2 request, json encode the payload body, err := json.Marshal(payload) if err != nil { return err } v2_resp, err := client.RawRequest(http.MethodPost, "/v2/billing/meter_events", string(body), nil) if err != nil { return err } var v2_response map[string]interface{} err = json.Unmarshal(v2_resp.RawJSON, &v2_response) if err != nil { return err } fmt.Printf("%#v\n", v2_response) // for a v1 request, form encode the payload formValues := &form.Values{} form.AppendTo(formValues, payload) content := formValues.Encode() v1_resp, err := client.RawRequest(http.MethodPost, "/v1/billing/meter_events", content, nil) if err != nil { return err } var v1_response map[string]interface{} err = json.Unmarshal(v1_resp.RawJSON, &v1_response) if err != nil { return err } fmt.Printf("%#v\n", v1_response) return nil } ``` -------------------------------- ### Pass Undocumented Parameters to Stripe API Source: https://github.com/stripe/stripe-go/blob/master/README.md Use the `AddExtra()` method to pass parameters not yet supported by the typed library. Ensure the parameter names and structure match Stripe's API expectations. ```go params := &stripe.CustomerCreateParams{ Email: stripe.String("jenny.rosen@example.com") } params.AddExtra("secret_feature_enabled", "true") params.AddExtra("secret_parameter[primary]","primary value") params.AddExtra("secret_parameter[secondary]","secondary value") customer, err := sc.V1Customer.Create(context.TODO(), params) ``` -------------------------------- ### APIResponse Struct Definition Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v71 The structure containing metadata for API responses, including headers, idempotency keys, and request IDs. ```go // APIResponse encapsulates some common features of a response from the // Stripe API. type APIResponse struct { // Header contain a map of all HTTP header keys to values. Its behavior and // caveats are identical to that of http.Header. Header http.Header // IdempotencyKey contains the idempotency key used with this request. // Idempotency keys are a Stripe-specific concept that helps guarantee that // requests that fail and need to be retried are not duplicated. IdempotencyKey string // RawJSON contains the response body as raw bytes. RawJSON []byte // RequestID contains a string that uniquely identifies the Stripe request. // Used for debugging or support purposes. RequestID string // Status is a status code and message. e.g. "200 OK" Status string // StatusCode is a status code as integer. e.g. 200 StatusCode int } ``` -------------------------------- ### Update FeeRefundParams in Stripe Go Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Replaces FeeRefundParams.ApplicationFee with FeeRefundParams.Fee and FeeRefundParams.ID for clarity and correctness. ```go type FeeRefundParams struct { Fee *string ID *string } ``` -------------------------------- ### Invoice Customer Phone Not Nullable Source: https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73 Clarifies that `Invoice.CustomerPhone` maps to `*string` but is a non-nullable `string`. ```APIDOC ## Invoice Customer Phone Not Nullable ### Description `Invoice.CustomerPhone` maps to `*string` but is a non-nullable `string`. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### List Stripe Events Source: https://github.com/stripe/stripe-go/blob/master/README.md List Stripe events. You can access event data and previous attributes using helper methods or by unmarshalling the raw data. ```go sc := stripe.NewClient(apiKey) for e, err := range sc.V1Events.List(context.TODO(), nil) { // access event data via e.GetObjectValue("resource_name_based_on_type", "resource_property_name") // alternatively you can access values via e.Data.Object["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"] // access previous attributes via e.GetPreviousValue("resource_name_based_on_type", "resource_property_name") // alternatively you can access values via e.Data.PreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"] } ```