stripe-go

repository·master·Indexed 25 days ago

https://github.com/stripe/stripe-go

The official Stripe Go client library for interacting with the Stripe API. It provides structured access to Stripe resources such as Customers, PaymentIntents, and Events. The library supports Go 1.22+ and recommends the stripe.Client pattern for accessing V1 APIs. It includes features for automatic retries, logging, nested object expansion, and support for Stripe Connect authentication.

Tokens
46.3K
Snippets
48
Records
230
Agent score
82%

What's inside stripe-go

  1. Migrate to V32 Parameter Structs (Pointer-based fields)

    master

    In version 32, all fields on parameter structs (those ending in *Params) have been converted to pointers. This allows the library to distinguish between a field being unset (nil) and a field being explicitly set to a zero value.

    To set these fields, you must use the provided helper functions instead of passing raw values or taking addresses of literals.

    Available helper functions:

    • stripe.Bool(bool)
    • stripe.Float64(float64)
    • stripe.Int64(int64)
    • stripe.String(string)

    Note on zero values: Previously used fields like CouponEmpty or QuantityZero have been removed. To send an empty value, use the corresponding field with the appropriate helper (e.g., stripe.String("") or stripe.Int64(0)).

    // Example: Initializing a parameter struct with a zero value
    UsageRecord {
        Quantity: stripe.Int64(0),
    }
  2. Configure Stripe for Google AppEngine

    master

    In Google AppEngine, http.DefaultClient is unavailable. You must create a per-request client using urlfetch.Client and stripe.NewBackends.

    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)
    }
  3. Use the recommended `stripe.Client` pattern

    master

    The recommended way to interact with Stripe resources is via the stripe.Client instance. This pattern provides access to V1 APIs and supports modern Go patterns.

    Common operations for a resource (e.g., Customers) include:

    • Create: sc.V1Customers.Create(ctx, params)
    • Retrieve: sc.V1Customers.Retrieve(ctx, id, params)
    • Update: sc.V1Customers.Update(ctx, id, params)
    • Delete: sc.V1Customers.Delete(ctx, id, params)
    • List: sc.V1Customers.List(ctx, params)
    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{})
    
    // Retrieve
    c, err := sc.V1Customers.Retrieve(context.TODO(), id, &stripe.CustomerRetrieveParams{})
    
    // Update
    c, err := sc.V1Customers.Update(context.TODO(), id, &stripe.CustomerUpdateParams{})
    
    // Delete
    c, err := sc.V1Customers.Delete(context.TODO(), id, &stripe.CustomerDeleteParams{})
    
    // List
    for c, err := range sc.V1Customers.List(context.TODO(), &stripe.CustomerListParams{}) {
    	// handle err
    	// do something
    }
  4. Upgrade to the latest major version for support

    master
    New features, bug fixes, and security updates are only released on the latest major version of the Stripe Go client library. While older major versions remain available, they will not receive any updates or security patches. It is recommended to always use the latest major version.
  5. Use Undocumented Parameters and Properties

    master

    To use undocumented or private preview features:

    1. Parameters: Use AddExtra(key, value) on your parameter structs.
    2. Properties: Access undocumented properties by unmarshaling the LastResponse.RawJSON into a map[string]interface{}.
    3. Beta Headers: For features requiring specific beta headers, set them manually in the Params.Headers field.
    // Undocumented Parameters
    params := &stripe.CustomerCreateParams{
    	Email: stripe.String("jenny.rosen@example.com")
    }
    params.AddExtra("secret_feature_enabled", "true")
    
    // Undocumented Properties
    var rawData map[string]interface{}
    _ = json.Unmarshal(customer.LastResponse.RawJSON, &rawData)
    secretFeatureEnabled := rawData["secret_feature_enabled"]
    
    // Beta Headers
    params := &stripe.CustomerCreateParams{
    	...
    	Params: stripe.Params{
    		Headers: http.Header{
    			"Stripe-Version": []string{"2025-10-29.preview; beta_feature_1=v3"},
    		},
    	},
    }
  6. Expand Nested Objects

    master

    By default, expandable objects in stripe-go only populate the ID field. To retrieve the full resource object, use the AddExpand method on the parameter struct before making the API call.

    // With expansion
    p := &stripe.ChargeCreateParams{}
    p.AddExpand("customer")
    c, _ = sc.V1Charges.Retrieve(context.TODO(), "ch_123", p)
    
    // c.Customer.ID is available
    // c.Customer.Name is now also available
  7. Set up stripe-mock for local testing

    master

    The package depends on stripe-mock for local development and testing. You must fetch and run it in a background terminal to simulate the Stripe API locally.

    1. Install stripe-mock: go get -u github.com/stripe/stripe-mock
    2. Run the mock server: stripe-mock
    go get -u github.com/stripe/stripe-mock
    stripe-mock
  8. Mock Stripe Clients for Unit Tests

    master

    To mock the Stripe client using GoMock:

    1. Generate a mock for the Backend type using mockgen.
    2. Initialize a stripe.Backends struct using your mock backend.
    3. Use stripe.NewClient with the mocked backends.
    mockgen -destination=mocks/backend.go -package=mocks github.com/stripe/stripe-go/v86 Backend
  9. Install stripe-go

    master

    To install the Stripe Go client library, ensure your project uses Go Modules. You can initialize a module with go mod init and then either import the package directly in your code or explicitly fetch it using go get.

    Requirements:

    • Go 1.22+ (supports the 4 most recent Go versions at the time of release).
    go mod init
    go get -u github.com/stripe/stripe-go/v86
  10. Install Public and Private Preview SDKs

    master

    Preview features are available in specific SDK versions:

    • Public Preview: Versions with a -beta.X suffix.
    • Private Preview: Versions with an -alpha.X suffix.

    Install them by specifying the version in your go.mod file. For public previews, you can use stripe.AddBetaVersion(name, version) to set required beta headers.

  11. Run tests using just or go test

    master

    You can run tests using the just command runner or standard go test commands.

    To run all tests: just test or go test ./...

    To run tests for a specific package (e.g., invoice): just test ./invoice or go test ./invoice

    To run a single specific test: just test ./invoice -run TestInvoiceGet or go test ./invoice -run TestInvoiceGet

  12. Authenticate with Connect

    master

    When performing actions on behalf of a connected account, you can use one of two methods:

    1. Stripe-Account Header (Recommended): Use SetStripeAccount() on a ListParams or Params object to pass the account ID.
    2. Account Keys: Pass the specific account's access token directly into stripe.NewClient.

    Example using SetStripeAccount:

    listParams := &stripe.CustomerListParams{}
    listParams.SetStripeAccount("acct_123")
    // For a list request
    listParams := &stripe.CustomerListParams{}
    listParams.SetStripeAccount("acct_123")