Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Go library for the Stripe API.

License

NotificationsYou must be signed in to change notification settings

rizalgowandy/stripe-go

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GoDocBuild StatusCoverage Status

The officialStripe Go client library.

Installation

Make sure your project is using Go Modules (it will have ago.mod file in itsroot if it already is):

go mod init

Then, reference stripe-go in a Go program withimport:

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

Run any of the normalgo commands (build/install/test). The Gotoolchain will resolve and fetch the stripe-go module automatically.

Alternatively, you can also explicitlygo get the package into a project:

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

Documentation

For a comprehensive list of examples, check out theAPIdocumentation.

Seevideo demonstrations covering how to use the library.

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

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)

PaymentIntents

params:=&stripe.PaymentIntentListParams{Customer:stripe.String(customer.ID),}// set this so you can easily retry your request in case of a timeoutparams.Params.IdempotencyKey=stripe.NewIdempotencyKey()i:=paymentintent.List(params)fori.Next() {pi:=i.PaymentIntent()}iferr:=i.Err();err!=nil {// handle}

Events

i:=event.List(nil)fori.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 theevent.Data.Raw property to unmarshal to theappropriate struct.

Authentication with Connect

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

To use theStripe-Account approach, useSetStripeAccount() on aListParamsorParams class. For example:

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

To use a key, pass it toAPI'sInit function:

import ("github.com/stripe/stripe-go/v72""github.com/stripe/stripe-go/v72/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 tocreate a per-request Stripe client since thehttp.DefaultClient is notavailable. Here's a sample handler:

import ("fmt""net/http""google.golang.org/appengine""google.golang.org/appengine/urlfetch""github.com/stripe/stripe-go/v72""github.com/stripe/stripe-go/v72/client")funchandler(w http.ResponseWriter,r*http.Request) {c:=appengine.NewContext(r)httpClient:=urlfetch.Client(c)sc:=stripeClient.New("sk_test_123",stripe.NewBackends(httpClient))params:=&stripe.CustomerParams{Description:stripe.String("Stripe Developer"),Email:stripe.String("gostripe@stripe.com"),        }customer,err:=sc.Customers.New(params)iferr!=nil {fmt.Fprintf(w,"Could not create customer: %v",err)        }fmt.Fprintf(w,"Customer created: %v",customer.ID)}

Usage

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

Without a Client

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

import ("github.com/stripe/stripe-go/v72""github.com/stripe/stripe-go/v72/$resource$")// Setupstripe.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)// DeleteresourceDeleted,err:= $resource$.Del(id, stripe.$Resource$Params)// Listi:= $resource$.List(stripe.$Resource$ListParams)fori.Next() {$resource$:= i.$Resource$()}iferr:=i.Err();err!=nil {// handle}

With a Client

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

import ("github.com/stripe/stripe-go/v72""github.com/stripe/stripe-go/v72/client")// Setupsc:=&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)// DeleteresourceDeleted,err:= sc.$Resource$s.Del(id, stripe.$Resource$Params)// Listi:= sc.$Resource$s.List(stripe.$Resource$ListParams)fori.Next() {resource:= i.$Resource$()}iferr:=i.Err();err!=nil {// handle}

Accessing the Last Response

UseLastResponse on anyAPIResource to look at the API response thatgenerated the current object:

coupon,err:= coupon.New(...)requestID:=coupon.LastResponse.RequestID

Similarly, forList operations, the last response is available on the listobject attached to the iterator:

it:= coupon.List(...)forit.Next() {// Last response *NOT* on the individual iterator objectit.Coupon().LastResponse// wrong// But rather on the list object, also accessible through the iteratorrequestID:=it.CouponList().LastResponse.RequestID}

See the definition ofAPIResponse for available fields.

Note that where API resources are nested in other API resources, onlyLastResponse on the top-level resource is set.

Automatic Retries

The library automatically retries requests on intermittent failures like on aconnection error, timeout, or on certain API responses like a status409 Conflict.Idempotency keys are always added to requests tomake any such subsequent retries safe.

By default, it will perform up to two retries. That number can be configuredwithMaxNetworkRetries:

import ("github.com/stripe/stripe-go/v72""github.com/stripe/stripe-go/v72/client")config:=&stripe.BackendConfig{MaxNetworkRetries:stripe.Int64(0),// Zero retries}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(...)

Configuring Logging

By default, the library logs error messages only (which are sent tostderr).Configure default logging using the globalDefaultLeveledLogger 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 loggersto comply to the following interface:

typeLeveledLoggerInterfaceinterface {Debugf(formatstring,v...interface{})Errorf(formatstring,v...interface{})Infof(formatstring,v...interface{})Warnf(formatstring,v...interface{})}

Some loggers likeLogrus and Zap'sSugaredLoggersupport this interface out-of-the-box so it's possible to setDefaultLeveledLogger to a*logrus.Logger or*zap.SugaredLogger directly.For others it may be necessary to write a thin shim layer to support them.

Expanding Objects

Allexpandable objects in stripe-go take the form of afull resource struct, but unless expansion is requested, only theID field ofthat struct is populated. Expansion is requested by callingAddExpand onparameter structs. For example:

//// *Without* expansion//c,_:=charge.Retrieve("ch_123",nil)c.Customer.ID// Only ID is populatedc.Customer.Name// All other fields are always empty//// With expansion//p:=&CustomerParams{}p.AddExpand("customer")c,_:=charge.Retrieve("ch_123",p)c.Customer.ID// ID is still availablec.Customer.Name// Name is now also available (if it had a value)

Writing a Plugin

If you're writing a plugin that uses the library, we'd appreciate it if youidentified usingstripe.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 StripeAPI. Note that whileName is always required,URL andVersion areoptional.

Request latency telemetry

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

You can disable this behavior if you prefer:

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

Development

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

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

Test

The test suite needs testify'srequire 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 onstripe-mock, so make sure to fetch and run it from abackground terminal (stripe-mock's README also containsinstructions for installing via Homebrew and other methods):

go get -u github.com/stripe/stripe-mockstripe-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, pleaseopen an issue orsubmit apull request.

About

Go library for the Stripe API.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go100.0%

[8]ページ先頭

©2009-2025 Movatter.jp