在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:stripe/stripe-go开源软件地址:https://github.com/stripe/stripe-go开源编程语言:Go 100.0%开源软件介绍:Go StripeThe official Stripe Go client library. InstallationMake sure your project is using Go Modules (it will have a go mod init Then, reference stripe-go in a Go program with import (
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/customer"
) Run any of the normal Alternatively, you can also explicitly go get -u github.com/stripe/stripe-go/v72 DocumentationFor a comprehensive list of examples, check out the API documentation. See video demonstrations covering how to use the library. For details on all the functionality in this library, see the Go documentation. Below are a few simple examples: Customersparams := &stripe.CustomerParams{
Description: stripe.String("Stripe Developer"),
Email: stripe.String("[email protected]"),
PreferredLocales: stripe.StringSlice([]string{"en", "es"}),
}
c, err := customer.New(params) PaymentIntentsparams := &stripe.PaymentIntentListParams{
Customer: stripe.String(customer.ID),
}
// set this so you can easily retry your request in case of a timeout
params.Params.IdempotencyKey = stripe.NewIdempotencyKey()
i := paymentintent.List(params)
for i.Next() {
pi := i.PaymentIntent()
}
if err := i.Err(); err != nil {
// handle
} Eventsi := 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 Authentication with ConnectThere are two ways of authenticating requests when performing actions on behalf
of a connected account, one that uses the To use the // For a list request
listParams := &stripe.CustomerListParams{}
listParams.SetStripeAccount("acct_123") // For any other kind of request
params := &stripe.CustomerParams{}
params.SetStripeAccount("acct_123") To use a key, pass it to import (
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/client"
)
stripe := &client.API{}
stripe.Init("access_token", nil) Google AppEngineIf you're running the client in a Google AppEngine environment, you'll need to
create a per-request Stripe client since the 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"
)
func handler(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("[email protected]"),
}
customer, err := sc.Customers.New(params)
if err != nil {
fmt.Fprintf(w, "Could not create customer: %v", err)
}
fmt.Fprintf(w, "Customer created: %v", customer.ID)
} UsageWhile some resources may contain more/less APIs, the following pattern is
applied throughout the library for a given Without a ClientIf 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/v72"
"github.com/stripe/stripe-go/v72/$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 ClientIf you're dealing with multiple keys, it is recommended you use import (
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/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
} Accessing the Last ResponseUse c, err := coupon.New(...)
requestID := coupon.LastResponse.RequestID Similarly, for it := coupon.List(...)
for it.Next() {
// Last response *NOT* on the individual iterator object
it.Coupon().LastResponse // wrong
// But rather on the list object, also accessible through the iterator
requestID := it.CouponList().LastResponse.RequestID
} See the definition of Note that where API resources are nested in other API resources, only
Automatic RetriesThe library automatically retries requests on intermittent failures like on a
connection error, timeout, or on certain API responses like a status By default, it will perform up to two retries. That number can be configured
with 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 LoggingBy default, the library logs error messages only (which are sent to 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
support this interface out-of-the-box so it's possible to set
Expanding ObjectsAll expandable objects in stripe-go take the form of a
full resource struct, but unless expansion is requested, only the //
// *Without* expansion
//
c, _ := charge.Retrieve("ch_123", nil)
c.Customer.ID // Only ID is populated
c.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 available
c.Customer.Name // Name is now also available (if it had a value) Writing a PluginIf you're writing a plugin that uses the library, we'd appreciate it if you
identified using 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 Request latency telemetryBy 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: stripe.Bool(false),
} DevelopmentPull requests from the community are welcome. If you submit one, please keep the following guidelines in mind:
TestThe test suite needs testify's
Before running the tests, make sure to grab all of the package's dependencies:
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):
Run all tests:
Run tests for one package:
Run a single test:
For any requests, bug or comments, please open an issue or submit a pull request. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论