Skip to content
Go library for the Stripe API.
Go Other
  1. Go 99.9%
  2. Other 0.1%
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Added a template for GitHub issues Nov 3, 2016
account Changes to Account and Person to represent identity verification state Sep 6, 2019
accountlink Revert Go module support Jan 16, 2019
applepaydomain Revert Go module support Jan 16, 2019
balance Remove TODOs and deprecated parts Oct 10, 2019
balancetransaction Add balancetransaction package and move to /v1/balance_transactions Jul 31, 2019
bankaccount Revert Go module support Jan 16, 2019
bitcoinreceiver Revert Go module support Jan 16, 2019
bitcointransaction Revert Go module support Jan 16, 2019
capability Add support for the Capability resource and APIs May 9, 2019
card Revert Go module support Jan 16, 2019
charge update test to use params Mar 27, 2019
checkout/session Fix `Items` to be a slice May 6, 2019
client Add support for `Mandate` Nov 6, 2019
countryspec Revert Go module support Jan 16, 2019
coupon Revert Go module support Jan 16, 2019
creditnote Add support for `CreditNoteLineItem` Jan 14, 2020
customer Revert Go module support Jan 16, 2019
customerbalancetransaction Add balancetransaction package and move to /v1/balance_transactions Jul 31, 2019
discount Revert Go module support Jan 16, 2019
dispute Revert Go module support Jan 16, 2019
ephemeralkey Add support for API version 2019-03-14 Mar 19, 2019
event Revert Go module support Jan 16, 2019
exchangerate Revert Go module support Jan 16, 2019
fee Revert Go module support Jan 16, 2019
feerefund Revert Go module support Jan 16, 2019
file Add support for file_link_data in file creation requests Apr 30, 2019
filelink Revert Go module support Jan 16, 2019
form Add OAuth support Jul 29, 2019
invoice Add Billing changes Jun 24, 2019
invoiceitem Revert Go module support Jan 16, 2019
issuing Add and to IssuingCardholder Nov 8, 2019
loginlink Revert Go module support Jan 16, 2019
mandate Add support for `Mandate` Nov 6, 2019
oauth Add OAuth support Jul 29, 2019
order Don't add a .New method Oct 8, 2019
orderreturn Don't add a .New method Oct 8, 2019
paymentintent Move to API version 2019-08-14 and other changes Aug 15, 2019
paymentmethod Add support for PaymentMethod Mar 19, 2019
paymentsource update tests Apr 17, 2019
payout Revert Go module support Jan 16, 2019
person Add support for API version 2019-02-19 Feb 18, 2019
plan Add support for decimal amounts on Billing resources Aug 22, 2019
product update tests Apr 17, 2019
radar Properly use /v1/radar/early_fraud_warnings as the API Aug 15, 2019
recipient Revert Go module support Jan 16, 2019
recipienttransfer Use custom types for resources and string on params Jun 6, 2018
refund Add to Charge and to Refund and Dispute Nov 7, 2019
reporting Revert Go module support Jan 16, 2019
reversal Revert Go module support Jan 16, 2019
review Revert Go module support Jan 16, 2019
scripts Add test script to check that all clients are included in `client.API` May 8, 2019
setupintent Add support for the `SetupIntent` resource and APIs Jun 28, 2019
sigma/scheduledqueryrun Revert Go module support Jan 16, 2019
sku Revert Go module support Jan 16, 2019
source Code Review: Add SourcMandate parameter back Sep 20, 2019
sourcetransaction Revert Go module support Jan 16, 2019
sub Add Billing changes Jun 24, 2019
subitem Revert Go module support Jan 16, 2019
subschedule Support for the `now` on `StartDate` on Subscription Schedule creation Nov 22, 2019
taxid Add support for TaxID resource and APIs Apr 23, 2019
taxrate Add support for TaxRate resource and APIs Apr 24, 2019
terminal Add support for Terminal Location and Reader deletion Mar 19, 2019
testing Add support for `CreditNoteLineItem` Jan 14, 2020
threedsecure Revert Go module support Jan 16, 2019
token Add a long list of missing params and properties Mar 27, 2019
topup Revert Go module support Jan 16, 2019
transfer Revert Go module support Jan 16, 2019
usagerecord Revert Go module support Jan 16, 2019
usagerecordsummary userrecordsummary: replace stripe.Charge.* with stripe.UserRecordSumm… Apr 3, 2019
webhook Fix comment typos Nov 24, 2019
webhookendpoint update tests Apr 17, 2019
.gitignore Add `.DS_Store` to `.gitignore` May 16, 2019
.travis.yml Add support for `CreditNoteLineItem` Jan 14, 2020
CHANGELOG Reformat CHANGELOG to CHANGELOG.md Oct 20, 2017
CHANGELOG.md Bump version to 68.13.0 Jan 24, 2020
CODE_OF_CONDUCT.md Contributor Convenant Oct 24, 2019
LICENSE update license to Stripe Aug 30, 2014
Makefile Add test script to check that all clients are included in `client.API` May 8, 2019
README.md Bump version to 68.13.0 Jan 24, 2020
VERSION Bump version to 68.13.0 Jan 24, 2020
account.go Add to Account Dec 20, 2019
account_test.go Rename `AccountOpener` to `Representative` and update to latest API v… Oct 10, 2019
accountlink.go Add support for the Account Link resource Jan 9, 2019
address.go Fix linter on almost all packages Jul 30, 2018
applepaydomain.go Rework most of the library naming and structure Jun 6, 2018
application.go Fix linter on almost all packages Jul 30, 2018
application_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
balance.go Add balancetransaction package and move to /v1/balance_transactions Jul 31, 2019
balance_transaction_test.go Add balancetransaction package and move to /v1/balance_transactions Jul 31, 2019
balancetransaction.go Add ReportingCategory to BalanceTransaction Jan 7, 2020
bankaccount.go Change Account field to expanded version. Oct 3, 2019
bankaccount_test.go Revert Go module support Jan 16, 2019
bitcoinreceiver.go Remove editable bitcoin receiver actions Aug 17, 2018
bitcoinreceiver_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
bitcointransaction.go Fix comment typos Nov 24, 2019
bitcointransaction_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
capability.go Add `PendingVerification` on `Account`, `Person` and `Capability` Aug 26, 2019
card.go Add `unavailable` as possible value on `CardVerification` Jul 1, 2019
card_test.go Revert Go module support Jan 16, 2019
charge.go Add support for `Network` on `Charge` Dec 4, 2019
charge_test.go Revert Go module support Jan 16, 2019
checkout_session.go Add `Metadata` support on Checkout `Session` Jan 17, 2020
countryspec.go Add support for API version 2019-02-19 Feb 18, 2019
coupon.go Add comments for all const blocks Jul 30, 2018
coupon_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
creditnote.go Add support for `CreditNoteLineItem` Jan 14, 2020
currency.go Add comments for all const blocks Jul 30, 2018
customer.go Remove TODOs and deprecated parts Oct 10, 2019
customer_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
customerbalancetransaction.go Add support for Customer Balance Transaction resource and APIs Jun 16, 2019
discount.go Rename all properties in the library to match the API reference Jun 6, 2018
dispute.go Add payment_intent filter for listing disputes Nov 21, 2019
dispute_test.go Move File to FileUpload to make its location more intuitive Jun 11, 2018
ephemeralkey.go Improve docs for ephemeral keys Oct 29, 2019
ephemeralkey_test.go Power test suite with stripe-mock + rework parameters with form Sep 15, 2017
error.go Add missing error code Sep 24, 2019
error_test.go Introduce `GetBackendWithConfig` and make logging configurable per ba… Jul 3, 2018
event.go Prevents `Object` from being serialized on the `Event` resource Mar 4, 2019
event_test.go Rename all properties in the library to match the API reference Jun 6, 2018
example_test.go Revert Go module support Jan 16, 2019
exchangerate.go Add extra params to Get for exchangerate and countryspec Jun 14, 2018
exchangerate_test.go Add support for /v1/exchange_rates API requests Oct 31, 2017
fee.go Convert the rest of expansion functions to safer style Jun 11, 2018
fee_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
feerefund.go Use Fee struct for FeeRefund.Fee Jul 16, 2018
feerefund_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
file.go Add support for file_link_data in file creation requests Apr 30, 2019
file_test.go Add support for file_link_data in file creation requests Apr 30, 2019
filelink.go Update for API version 2018-09-24 Sep 26, 2018
filelink_test.go Add the File Link resource Aug 3, 2018
invoice.go Adds PendingUpdate to Subscription Jan 10, 2020
invoice_test.go Add support for custom values in SubscriptionBillingCycleAnchor on In… Aug 26, 2019
invoiceitem.go Add support for decimal amounts on Billing resources Aug 22, 2019
invoiceitem_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
issuing_authorization.go Add support for ViolatedAuthorizationControls on Issuing Authorization Nov 18, 2019
issuing_card.go Add support for shipment speed for issuing cards Jan 24, 2020
issuing_cardholder.go Add and to IssuingCardholder Nov 8, 2019
issuing_dispute.go Add a long list of missing params and properties Mar 27, 2019
issuing_transaction.go Add support for to Issuing Transaction Jun 14, 2019
iter.go Revert Go module support Jan 16, 2019
iter_test.go Revert Go module support Jan 16, 2019
log.go Add log prefixes + test suite Mar 22, 2019
log_test.go Add log prefixes + test suite Mar 22, 2019
loginlink.go Add a long list of missing params and properties Mar 27, 2019
mandate.go Add AU BECS Debit to PaymentMethod Dec 9, 2019
oauth.go Add OAuth support Jul 29, 2019
order.go JSON spelling error Oct 11, 2019
order_test.go Revert Go module support Jan 16, 2019
orderreturn.go OrderReturnParams pkg, order -> orderreturn Oct 8, 2019
orderreturn_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
params.go Revert Go module support Jan 16, 2019
params_test.go Revert Go module support Jan 16, 2019
paymentintent.go Pin to API version 2019-12-03 and remove deprecated fields Dec 3, 2019
paymentintent_test.go Move to API version 2019-08-14 and other changes Aug 15, 2019
paymentmethod.go Add AU BECS Debit to PaymentMethod Dec 9, 2019
paymentsource.go Revert Go module support Jan 16, 2019
paymentsource_test.go Revert Go module support Jan 16, 2019
payout.go Remove lossy "MarshalJSON" implementations Oct 10, 2019
payout_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
person.go Rename `AccountOpener` to `Representative` and update to latest API v… Oct 10, 2019
person_test.go Add support for the Person resource and fix broken tests Oct 31, 2018
plan.go Add support for decimal amounts on Billing resources Aug 22, 2019
plan_test.go Add support for decimal amounts on Billing resources Aug 22, 2019
product.go Add a long list of missing params and properties Mar 27, 2019
product_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
radar_earlyfraudwarning.go Add support for radar.early_fraud_warning resource May 23, 2019
radar_valuelist.go Fix failing tests and remove deprecated properties on Invoice Nov 27, 2018
radar_valuelistitem.go Fix failing tests and remove deprecated properties on Invoice Nov 27, 2018
recipient.go Revert Go module support Jan 16, 2019
recipient_test.go Revert Go module support Jan 16, 2019
recipienttransfer.go Remove lossy "MarshalJSON" implementations Oct 10, 2019
recipienttransfer_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
refund.go Add new refund reason `RefundReasonExpiredUncapturedCharge` Nov 26, 2019
refund_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
reporting_reportrun.go Add support for columns on Reporting resources Mar 14, 2019
reporting_reporttype.go Add support for columns on Reporting resources Mar 14, 2019
reversal.go Add a long list of missing params and properties Mar 27, 2019
reversal_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
review.go Add support for the Review resource Nov 28, 2018
review_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
setupintent.go Pin to API version 2019-12-03 and remove deprecated fields Dec 3, 2019
setupintent_test.go Separate NextAction as its own for SetupIntent Jul 1, 2019
sigma_scheduledqueryrun.go Update for API version 2018-09-24 Sep 26, 2018
sku.go Address brandur's comments Jul 30, 2018
sku_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
source.go Merge pull request #952 from shengwei-stripe/aubecsdebit Oct 1, 2019
source_test.go Revert Go module support Jan 16, 2019
sourcetransaction.go Move old Live properties to Livemode Aug 20, 2018
sourcetransaction_test.go Convert the rest of expansion functions to safer style Jun 11, 2018
stripe.go Bump version to 68.13.0 Jan 24, 2020
stripe_test.go Support `Stripe-Should-Retry` header Sep 20, 2019
sub.go Add values for SubscriptionProrationBehavior Jan 13, 2020
sub_test.go Revert Go module support Jan 16, 2019
subitem.go Adds PendingUpdate to Subscription Jan 10, 2020
subschedule.go Pin to API version 2019-12-03 and remove deprecated fields Dec 3, 2019
subschedule_test.go Support for the `now` on `StartDate` on Subscription Schedule creation Nov 22, 2019
taxid.go Add new values for TaxIDType and fix TaxIDTypeCHVAT Jan 23, 2020
taxrate.go Add TaxRate support on other resources Apr 25, 2019
terminal_connectiontoken.go Remove TODOs and deprecated parts Oct 10, 2019
terminal_location.go Add and to Terminal Reader and Location Dec 19, 2019
terminal_reader.go Add and to Terminal Reader and Location Dec 19, 2019
threedsecure.go Fix linter on almost all packages Jul 30, 2018
token.go Add a long list of missing params and properties Mar 27, 2019
topup.go Add a long list of missing params and properties Mar 27, 2019
transfer.go Remove lossy "MarshalJSON" implementations Oct 10, 2019
transfer_test.go Remove lossy "MarshalJSON" implementations Oct 10, 2019
usagerecord.go Rename usage record file Aug 20, 2018
usagerecord_test.go Revert Go module support Jan 16, 2019
usagerecordsummary.go Fix two issues with List tests Aug 28, 2018
v32_migration_guide.md Fix typo in v32 migration guide Jun 6, 2018
webhookendpoint.go Add support for `api_version` on `WebhookEndpoint` Feb 28, 2019

README.md

Go Stripe

GoDoc Build Status Coverage Status

The official Stripe Go client library.

Installation

Install stripe-go with:

go get -u github.com/stripe/stripe-go

Then, import it using:

import (
    "github.com/stripe/stripe-go"
    "github.com/stripe/stripe-go/customer"
)

Go Module Support

The library currently does not ship with first-class support for Go modules. We put in support for it before, but ran into compatibility problems for existing installations using Dep (see discussion in closer to the bottom of this thread), and reverted support. Our current plan is to wait for better module compatibility in Dep (see a preliminary patch here), give the release a little grace time to become more widely distributed, then bring support back.

For now, require stripe-go in go.mod with a version but without a version suffix in the path like so:

module github.com/my/package

require (
    github.com/stripe/stripe-go v68.13.0
)

And use the same style of import paths as above:

import (
    "github.com/stripe/stripe-go"
    "github.com/stripe/stripe-go/customer"
)

Documentation

For a comprehensive list of examples, check out the API documentation.

For details on all the functionality in this library, see the GoDoc documentation.

Below are a few simple examples:

Customers

params := &stripe.CustomerParams{
	Description:        stripe.String("Stripe Developer"),
	Email:              stripe.String("gostripe@stripe.com"),
}

customer, err := customer.New(params)

Charges

params := &stripe.ChargeListParams{Customer: stripe.String(customer.ID)}
params.Filters.AddFilter("include[]", "", "total_count")

// set this so you can easily retry your request in case of a timeout
params.Params.IdempotencyKey = stripe.NewIdempotencyKey()

i := charge.List(params)
for i.Next() {
	charge := i.Charge()
}

if err := i.Err(); err != nil {
	// handle
}

Events

i := event.List(nil)
for i.Next() {
	e := i.Event()

	// 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.PrevPreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]
}

Alternatively, you can use the event.Data.Raw property to unmarshal to the appropriate struct.

Authentication with Connect

There are two ways of authenticating requests when performing actions on behalf of a connected account, one that uses the Stripe-Account header containing an account's ID, and one that uses the account's keys. Usually the former is the recommended approach. See the documentation for more information.

To use the Stripe-Account approach, use SetStripeAccount() on a ListParams or Params class. For example:

// For a list request
listParams := &stripe.ChargeListParams{}
listParams.SetStripeAccount("acct_123")
// For any other kind of request
params := &stripe.CustomerParams{}
params.SetStripeAccount("acct_123")

To use a key, pass it to API's Init function:

import (
	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/client"
)

stripe := &client.API{}
stripe.Init("access_token", nil)

Google AppEngine

If you're running the client in a Google AppEngine environment, you'll need to create a per-request Stripe client since the http.DefaultClient is not available. Here's a sample handler:

import (
	"fmt"
	"net/http"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"

	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/client"
)

func handler(w http.ResponseWriter, r *http.Request) {
        c := appengine.NewContext(r)
        httpClient := urlfetch.Client(c)

        sc := stripeClient.New("sk_live_key", stripe.NewBackends(httpClient))

        chargeParams := &stripe.ChargeParams{
            Amount:      stripe.Int64(2000),
            Currency:    stripe.String(string(stripe.CurrencyUSD)),
            Description: stripe.String("Charge from Google App Engine"),
        }
        chargeParams.SetSource("tok_amex") // obtained with Stripe.js
        charge, err := sc.Charges.New(chargeParams)
        if err != nil {
            fmt.Fprintf(w, "Could not process payment: %v", err)
        }
        fmt.Fprintf(w, "Completed payment: %v", charge.ID)
}

Usage

While some resources may contain more/less APIs, the following pattern is applied throughout the library for a given $resource$:

Without a Client

If you're only dealing with a single key, you can simply import the packages required for the resources you're interacting with without the need to create a client.

import (
	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/$resource$"
)

// Setup
stripe.Key = "sk_key"

stripe.SetBackend("api", backend) // optional, useful for mocking

// Create
$resource$, err := $resource$.New(stripe.$Resource$Params)

// Get
$resource$, err := $resource$.Get(id, stripe.$Resource$Params)

// Update
$resource$, err := $resource$.Update(stripe.$Resource$Params)

// Delete
resourceDeleted, err := $resource$.Del(id, stripe.$Resource$Params)

// List
i := $resource$.List(stripe.$Resource$ListParams)
for i.Next() {
	$resource$ := i.$Resource$()
}

if err := i.Err(); err != nil {
	// handle
}

With a Client

If you're dealing with multiple keys, it is recommended you use client.API. This allows you to create as many clients as needed, each with their own individual key.

import (
	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/client"
)

// Setup
sc := &client.API{}
sc.Init("sk_key", nil) // the second parameter overrides the backends used if needed for mocking

// Create
$resource$, err := sc.$Resource$s.New(stripe.$Resource$Params)

// Get
$resource$, err := sc.$Resource$s.Get(id, stripe.$Resource$Params)

// Update
$resource$, err := sc.$Resource$s.Update(stripe.$Resource$Params)

// Delete
resourceDeleted, err := sc.$Resource$s.Del(id, stripe.$Resource$Params)

// List
i := sc.$Resource$s.List(stripe.$Resource$ListParams)
for i.Next() {
	resource := i.$Resource$()
}

if err := i.Err(); err != nil {
	// handle
}

Configuring Automatic Retries

You can enable automatic retries on requests that fail due to a transient problem by configuring the maximum number of retries:

import (
	"github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/client"
)

config := &stripe.BackendConfig{
    MaxNetworkRetries: 2,
}

sc := &client.API{}
sc.Init("sk_key", &stripe.Backends{
    API:     stripe.GetBackendWithConfig(stripe.APIBackend, config),
    Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config),
})

coupon, err := sc.Coupons.New(...)

Various errors can trigger a retry, like a connection error or a timeout, and also certain API responses like HTTP status 409 Conflict.

Idempotency keys are added to requests to guarantee that retries are safe.

Configuring Logging

Configure logging using the global DefaultLeveledLogger variable:

stripe.DefaultLeveledLogger = &stripe.LeveledLogger{
    Level: stripe.LevelInfo,
}

Or on a per-backend basis:

config := &stripe.BackendConfig{
    LeveledLogger: &stripe.LeveledLogger{
        Level: stripe.LevelInfo,
    },
}

It's possible to use non-Stripe leveled loggers as well. Stripe expects loggers to comply to the following interface:

type LeveledLoggerInterface interface {
	Debugf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Warnf(format string, v ...interface{})
}

Some loggers like Logrus and Zap's [SugaredLogger][sugaredlogger] support this interface out-of-the-box so it's possible to set DefaultLeveledLogger to a *logrus.Logger or *zap.SugaredLogger directly. For others it may be necessary to write a thin shim layer to support them.

Writing a Plugin

If you're writing a plugin that uses the library, we'd appreciate it if you identified using stripe.SetAppInfo:

stripe.SetAppInfo(&stripe.AppInfo{
    Name:    "MyAwesomePlugin",
    URL:     "https://myawesomeplugin.info",
    Version: "1.2.34",
})

This information is passed along when the library makes calls to the Stripe API. Note that while Name is always required, URL and Version are optional.

Request latency telemetry

By default, the library sends request latency telemetry to Stripe. These numbers help Stripe improve the overall latency of its API for all users.

You can disable this behavior if you prefer:

config := &stripe.BackendConfig{
	EnableTelemetry: false,
}

Development

Pull requests from the community are welcome. If you submit one, please keep the following guidelines in mind:

  1. Code must be go fmt compliant.
  2. All types, structs and funcs should be documented.
  3. Ensure that make test succeeds.

Test

The test suite needs testify's require package to run:

github.com/stretchr/testify/require

Before running the tests, make sure to grab all of the package's dependencies:

go get -t -v

It also depends on stripe-mock, so make sure to fetch and run it from a background terminal (stripe-mock's README also contains instructions for installing via Homebrew and other methods):

go get -u github.com/stripe/stripe-mock
stripe-mock

Run all tests:

make test

Run tests for one package:

go test ./invoice

Run a single test:

go test ./invoice -run TestInvoiceGet

For any requests, bug or comments, please open an issue or submit a pull request.

You can’t perform that action at this time.