Categorygithub.com/agilebits/stripe-go
modulepackage
15.6.0+incompatible
Repository: https://github.com/agilebits/stripe-go.git
Documentation: pkg.go.dev

# README

Go Stripe GoDoc Build Status

Summary

The official Stripe Go client library.

Versioning

Each revision of the binding is tagged and the version is updated accordingly.

Given Go's lack of built-in versioning, it is highly recommended you use a package management tool in order to ensure a newer version of the binding does not affect backwards compatibility.

To see the list of past versions, run git tag. To manually get an older version of the client, clone this repo, checkout the specific tag and build the library:

git clone https://github.com/stripe/stripe-go.git
cd stripe-go
git checkout api_version_tag
make build

For more details on changes between versions, see the binding changelog and API changelog.

Installation

go get github.com/stripe/stripe-go

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{
	Balance: -123,
	Desc:  "Stripe Developer",
	Email: "[email protected]",
}
params.SetSource(&stripe.CardParams{
	Name:   "Go Stripe",
	Number: "378282246310005",
	Month:  "06",
	Year:   "15",
})

customer, err := customer.New(params)

Charges

params := &stripe.ChargeListParams{Customer: 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.GetObjValue("resource_name_based_on_type", "resource_property_name")
	// alternatively you can access values via e.Data.Obj["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]

	// access previous attributes via e.GetPrevValue("resource_name_based_on_type", "resource_property_name")
	// alternatively you can access values via e.Data.Prev["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]
}

Alternatively, you can use the even.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, pass the StripeAccount field to a ListParams or Params class. For example:

// For a list request
listParams := &stripe.ChargeListParams{StripeAccount: merchantID}
// For any other kind of request
params := &stripe.CustomerParams{StripeAccount: merchantID}

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 := client.New("sk_live_key", stripe.NewBackends(httpClient))

	fmt.Fprintf(w, "Ready to make calls to the Stripe API")
}

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
err := $resource$.Del(id)

// 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
err := sc.$Resource$s.Del(id)

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

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

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

For running additional tests, follow the steps below:

Set the STRIPE_KEY environment variable to match your test private key, then run make test:

STRIPE_KEY=YOUR_API_KEY make test

Or to run tests for a particular subpackage:

STRIPE_KEY=YOUR_API_KEY go test ./invoice

Or to run a particular test (it's worth noting however that Go will report a success even if the referenced test doesn't exist):

STRIPE_KEY=YOUR_API_KEY go test -run "TestAllInvoicesScenarios" ./invoice

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

# Packages

Package account provides the /account APIs.
Package balance provides the /balance APIs.
Package bankaccount provides the /bank_accounts APIs.
Package bitcoinreceiver provides the /bitcoin/receivers APIs.
Package bitcointransaction provides the /bitcoin/transactions APIs.
Package card provides the /cards APIs.
Package charge provides the /charges APIs.
Package client provides a Stripe client for invoking APIs across all resources.
Package countryspec provides the /country_specs APIs.
Package coupon provides the /coupons APIs.
Package currency provides the list of currency codes.
Package customer provides the /customers APIs.
Package discount provides the discount-related APIs.
Package dispute provides the dispute-related APIs.
Package event provides the /events APIs.
Package fee provides the /application_fees APIs.
Package feerefund provides the /application_fees/refunds APIs.
Package fileupload provides the file upload related APIs.
Package invoice provides the /invoices APIs.
Package invoiceitem provides the /invoiceitems APIs.
No description provided by the author
No description provided by the author
No description provided by the author
Package paymentsource provides the /sources APIs.
Package plan provides the /plans APIs.
No description provided by the author
Package recipient provides the /recipients APIs.
Package refund provides the /refunds APIs.
Package reversal provides the /transfers/reversals APIs.
No description provided by the author
Package sub provides the /subscriptions APIs.
No description provided by the author
Package token provides the /tokens APIs.
Package transfer provides the /transfers APIs.
Package utils provides internal utilities.

# Functions

GetBackend returns the currently used backend in the binding.
GetIter returns a new Iter for a given query and its options.
NewBackends creates a new set of backends with the given HTTP client.
NewIdempotencyKey generates a new idempotency key that can be used on a request.
SetBackend sets the backend used in the binding.
SetHTTPClient overrides the default HTTP client.
SourceParamsFor creates SourceParams objects around supported payment sources, returning errors if not.

# Constants

AccountTypeBankAccount is a constant value representing an external account which is a bank account.
AccountTypeCard is a constant value representing an external account which is a card.
APIBackend is a constant representing the API service backend.
No description provided by the author
APIURL is the URL of the API service backend.
No description provided by the author
No description provided by the author
Company is a constant value representing a company legal entity type.
Day is a constant value representing a daily payout interval.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
IdentityVerificationPending is a constant value indicating that identity verification status is pending.
IdentityVerificationUnverified is a constant value indicating that identity verification status is unverified.
IdentityVerificationVerified is a constant value indicating that identity verification status is verified.
No description provided by the author
No description provided by the author
No description provided by the author
Individual is a constant value representing an individual legal entity type.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Manual is a constant value representing a manual payout interval.
No description provided by the author
Month is a constant value representing a monthly payout interval.
PaymentSourceBankAccount is a constant representing a payment source which is a bank account.
PaymentSourceBitcoinReceiver is a constant representing a payment source which is a Bitcoin receiver.
PaymentSourceCard is a constant representing a payment source which is a card.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
TotalBackends is the total number of Stripe API endpoints supported by the binding.
UploadsBackend is a constant representing the uploads service backend.
UploadsURL is the URL of the uploads service backend.
Week is a constant value representing a weekly payout interval.

# Variables

Key is the Stripe API key used globally in the binding.
Logger controls how stripe performs logging at a package level.
LogLevel is the logging level for this library.

# Structs

Account is the resource representing your Stripe account.
AccountExternalAccountParams are the parameters allowed to reference an external account when creating an account.
AccountList is a list of accounts as returned from a list endpoint.
AccountListParams are the parameters allowed during account listing.
AccountParams are the parameters allowed during account creation/updates.
AccountRejectParams is the structure for the Reject function.
Address is the structure for an account address.
No description provided by the author
Amount is a structure wrapping an amount value and its currency.
APIConnectionError is a failure to connect to the Stripe API.
APIError is a catch all for any errors not covered by other types (and should be extremely uncommon).
AuthenticationError is a failure to properly authenticate during a request.
BackendConfiguration is the internal implementation for making HTTP calls to Stripe.
Backends are the currently supported endpoints.
Balance is the resource representing your Stripe balance.
BalanceParams is the set of parameters that can be used when retrieving a balance.
BankAccount represents a Stripe bank account.
BankAccountList is a list object for bank accounts.
BankAccountListParams is the set of parameters that can be used when listing bank accounts.
BankAccountParams is the set of parameters that can be used when creating or updating a bank account.
BitcoinReceiver is the resource representing a Stripe bitcoin receiver.
BitcoinReceiverList is a list of bitcoin receivers as retrieved from a list endpoint.
BitcoinReceiverListParams is the set of parameters that can be used when listing BitcoinReceivers.
BitcoinReceiverParams is the set of parameters that can be used when creating a BitcoinReceiver.
BitcoinReceiverUpdateParams is the set of parameters that can be used when updating a BitcoinReceiver.
BitcoinTransaction is the resource representing a Stripe bitcoin transaction.
BitcoinTransactionList is a list object for BitcoinTransactions.
BitcoinTransactionListParams is the set of parameters that can be used when listing BitcoinTransactions.
CaptureParams is the set of parameters that can be used when capturing a charge.
Card is the resource representing a Stripe credit/debit card.
CardError are the most common type of error you should expect to handle.
CardList is a list object for cards.
CardListParams is the set of parameters that can be used when listing cards.
CardParams is the set of parameters that can be used when creating or updating a card.
Charge is the resource representing a Stripe charge.
ChargeList is a list of charges as retrieved from a list endpoint.
ChargeListParams is the set of parameters that can be used when listing charges.
Outcome is the charge's outcome that details whether a payment was accepted and why.
ChargeParams is the set of parameters that can be used when creating or updating a charge.
CountrySpec is the resource representing the rules required for a Stripe account.
CountrySpecList is a list of country specs as retrieved from a list endpoint.
CountrySpecListParams are the parameters allowed during CountrySpec listing.
Coupon is the resource representing a Stripe coupon.
CouponList is a list of coupons as retrieved from a list endpoint.
CouponListParams is the set of parameters that can be used when listing coupons.
CouponParams is the set of parameters that can be used when creating a coupon.
Customer is the resource representing a Stripe customer.
CustomerList is a list of customers as retrieved from a list endpoint.
CustomerListParams is the set of parameters that can be used when listing customers.
CustomerParams is the set of parameters that can be used when creating or updating a customer.
CustomerShippingDetails is the structure containing shipping information.
CustomerSourceParams are used to manipulate a given Stripe Customer object's payment sources.
No description provided by the author
Discount is the resource representing a Stripe discount.
Dispute is the resource representing a Stripe dispute.
DisputeEvidence is the structure that contains various details about the evidence submitted for the dispute.
DisputeEvidenceParams is the set of parameters that can be used when submitting evidence for disputes.
DisputeList is a list of disputes as retrieved from a list endpoint.
DisputeListParams is the set of parameters that can be used when listing disputes.
DisputeParams is the set of parameters that can be used when updating a dispute.
DOB is a structure for an account owner's date of birth.
Error is the response returned when a call is unsuccessful.
Event is the resource representing a Stripe event.
EventData is the unmarshalled object as a map.
EventList is a list of events as retrieved from a list endpoint.
EventListParams is the set of parameters that can be used when listing events.
EvidenceDetails is the structure representing more details about the dispute.
ExternalAccount is an external account (a bank account or card) that's attached to an account.
ExternalAccountList is a list of external accounts that may be either bank accounts or cards.
Fee is the resource representing a Stripe application fee.
FeeList is a list of fees as retrieved from a list endpoint.
FeeListParams is the set of parameters that can be used when listing application fees.
FeeParams is the set of parameters that can be used when refunding an application fee.
FeeRefund is the resource representing a Stripe fee refund.
FeeRefundList is a list object for fee refunds.
FeeRefundListParams is the set of parameters that can be used when listing fee refunds.
FeeRefundParams is the set of parameters that can be used when refunding a fee.
File represents a link to downloadable content.
FileUpload is the resource representing a Stripe file upload.
FileUploadList is a list of file uploads as retrieved from a list endpoint.
FileUploadListParams is the set of parameters that can be used when listing file uploads.
FileUploadParams is the set of parameters that can be used when creating a file upload.
Filters is a structure that contains a collection of filters for list-related APIs.
FraudDetails is the structure detailing fraud status.
IdentityDocument is the structure for an identity document.
IdentityVerification is the structure for an account's verification.
InvalidRequestError is an error that occurs when a request contains invalid parameters.
No description provided by the author
Invoice is the resource representing a Stripe invoice.
InvoiceItem is the resource represneting a Stripe invoice item.
InvoiceItemList is a list of invoice items as retrieved from a list endpoint.
InvoiceItemListParams is the set of parameters that can be used when listing invoice items.
InvoiceItemParams is the set of parameters that can be used when creating or updating an invoice item.
InvoiceLine is the resource representing a Stripe invoice line item.
InvoiceLineList is a list object for invoice line items.
InvoiceLineListParams is the set of parameters that can be used when listing invoice line items.
InvoiceList is a list of invoices as retrieved from a list endpoint.
InvoiceListParams is the set of parameters that can be used when listing invoices.
InvoiceParams is the set of parameters that can be used when creating or updating an invoice.
Iter provides a convenient interface for iterating over the elements returned from paginated list API calls.
LegalEntity is the structure for properties related to an account's legal state.
ListMeta is the structure that contains the common properties of List iterators.
ListParams is the structure that contains the common properties of any *ListParams structure.
No description provided by the author
No description provided by the author
No description provided by the author
OrderList is a list of orders as retrieved from a list endpoint.
OrderListParams is the set of parameters that can be used when listing orders.
No description provided by the author
OrderPayParams is the set of parameters that can be used when paying orders.
No description provided by the author
OrderReturnList is a list of returns as retrieved from a list endpoint.
OrderReturnListParams is the set of parameters that can be used when listing returns.
OrderReturnParams is the set of parameters that can be used when returning orders.
No description provided by the author
Owner is the structure for an account owner.
PackageDimensions represents the dimension of a product or a sku from the perspective of shipping.
Params is the structure that contains the common properties of any *Params structure.
PaymentSource describes the payment source used to make a Charge.
Period is a structure representing a start and end dates.
PIIParams are parameters for personal identifiable information (PII).
Plan is the resource representing a Stripe plan.
PlanList is a list of plans as returned from a list endpoint.
PlanListParams is the set of parameters that can be used when listing plans.
PlanParams is the set of parameters that can be used when creating or updating a plan.
Product is the resource representing a Stripe product.
ProductList is a list of products as retrieved from a list endpoint.
ProductListParams is the set of parameters that can be used when listing products.
ProductParams is the set of parameters that can be used when creating or updating a product.
RateLimitError occurs when the Stripe API is hit to with too many requests too quickly and indicates that the current request has been rate limited.
Recipient is the resource representing a Stripe recipient.
RecipientList is a list of recipients as retrieved from a list endpoint.
RecipientListParams is the set of parameters that can be used when listing recipients.
RecipientParams is the set of parameters that can be used when creating or updating recipients.
Refund is the resource representing a Stripe refund.
RefundList is a list object for refunds.
RefundListParams is the set of parameters that can be used when listing refunds.
RefundParams is the set of parameters that can be used when refunding a charge.
RequestValues is a collection of values that can be submitted along with a request that specifically allows for duplicate keys and encodes its entries in the same order that they were added.
Reversal represents a transfer reversal.
ReversalList is a list of object for reversals.
ReversalListParams is the set of parameters that can be used when listing reversals.
ReversalParams is the set of parameters that can be used when reversing a transfer.
No description provided by the author
ShippingDetails is the structure containing shipping information.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SourceList is a list object for cards.
SourceListParams are used to enumerate the payment sources that are attached to a Customer.
SourceParams is a union struct used to describe an arbitrary payment source.
SourceVerifyParams are used to verify a customer source For more details see https://stripe.com/docs/guides/ach-beta.
Sub is the resource representing a Stripe subscription.
SubList is a list object for subscriptions.
SubListParams is the set of parameters that can be used when listing active subscriptions.
SubParams is the set of parameters that can be used when creating or updating a subscription.
Token is the resource representing a Stripe token.
TokenParams is the set of parameters that can be used when creating a token.
TOSAcceptanceParams is the structure for TOS acceptance.
Transaction is the resource representing the balance transaction.
TransactionList is a list of transactions as returned from a list endpoint.
Transfer is the resource representing a Stripe transfer.
TransferList is a list of transfers as retrieved from a list endpoint.
TransferListParams is the set of parameters that can be used when listing transfers.
TransferParams is the set of parameters that can be used when creating or updating a transfer.
TransferSchedule is the structure for an account's transfer schedule.
TransferScheduleParams are the parameters allowed for transfer schedules.
TxFee is a structure that breaks down the fees in a transaction.
TxListParams is the set of parameters that can be used when listing balance transactions.
TxParams is the set of parameters that can be used when retrieving a transaction.
VerificationFieldsList lists the fields needed for an account verification.

# Interfaces

Backend is an interface for making calls against a Stripe service.
Displayer provides a human readable representation of a struct.

# Type aliases

AccountType is the type of an external account.
BankAccountStatus is the list of allowed values for the bank account's status.
CardBrand is the list of allowed values for the card's brand.
CardFunding is the list of allowed values for the card's funding.
Country is the list of supported countries.
CouponDuration is the list of allowed values for the coupon's duration.
Currency is the list of supported currencies.
DisputeReason is the list of allowed values for a discount's reason.
DisputeStatus is the list of allowed values for a discount's status.
ErrorCode is the list of allowed values for the error's code.
ErrorType is the list of allowed values for the error's type.
No description provided by the author
FileUploadPurpose is the purpose of a particular file upload.
FraudReport is the list of allowed values for reporting fraud.
IdentityVerificationStatus describes the different statuses for identity verification.
Interval describes the payout interval.
InvoiceLineType is the list of allowed values for the invoice line's type.
LegalEntityType describes the types for a legal entity.
OrderStatus represents the statuses of an order object.
PaymentSourceType consts represent valid payment sources.
PlanInterval is the list of allowed values for a plan's interval.
Query is the function used to get a page listing.
RecipientType is the list of allowed values for the recipient's type.
RefundReason is, if set, the reason the refund is being made--allowed values are "fraudulent", "duplicate", and "requested_by_customer".
SubStatus is the list of allowed values for the subscription's status.
SupportedBackend is an enumeration of supported Stripe endpoints.
TokenizationMethod is the list of allowed values for the card's tokenization method.
TokenType is the list of allowed values for a token's type.
TransactionStatus is the list of allowed values for the transaction's status.
TransactionType is the list of allowed values for the transaction's type.
TransferFailCode is the list of allowed values for the transfer's failure code.
TransferSourceType is the list of allowed values for the transfer's source_type field.
TransferStatus is the list of allowed values for the transfer's status.
TransferType is the list of allowed values for the transfer's type.
Verification is the list of allowed verification responses.