diff --git a/OPENAPI_VERSION b/OPENAPI_VERSION index 5f5b311191..8f166ae2e0 100644 --- a/OPENAPI_VERSION +++ b/OPENAPI_VERSION @@ -1 +1 @@ -v1267 \ No newline at end of file +v1268 \ No newline at end of file diff --git a/README.md b/README.md index 8562023b30..4bc55caf50 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Go Stripe + [![Go Reference](https://pkg.go.dev/badge/github.com/stripe/stripe-go)](https://pkg.go.dev/github.com/stripe/stripe-go/v79) [![Build Status](https://github.com/stripe/stripe-go/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/stripe/stripe-go/actions/workflows/ci.yml?query=branch%3Amaster) [![Coverage Status](https://coveralls.io/repos/github/stripe/stripe-go/badge.svg?branch=master)](https://coveralls.io/github/stripe/stripe-go?branch=master) @@ -14,13 +15,13 @@ The official [Stripe][stripe] Go client library. Make sure your project is using Go Modules (it will have a `go.mod` file in its root if it already is): -``` sh +```sh go mod init ``` Then, reference stripe-go in a Go program with `import`: -``` go +```go import ( "github.com/stripe/stripe-go/v79" "github.com/stripe/stripe-go/v79/customer" @@ -256,7 +257,7 @@ if err := i.Err(); err != nil { Use `LastResponse` on any `APIResource` to look at the API response that generated the current object: -``` go +```go c, err := coupon.New(...) requestID := coupon.LastResponse.RequestID ``` @@ -264,7 +265,7 @@ requestID := coupon.LastResponse.RequestID Similarly, for `List` operations, the last response is available on the list object attached to the iterator: -``` go +```go it := coupon.List(...) for it.Next() { // Last response *NOT* on the individual iterator object @@ -354,7 +355,7 @@ full resource struct, but unless expansion is requested, only the `ID` field of that struct is populated. Expansion is requested by calling `AddExpand` on parameter structs. For example: -``` go +```go // // *Without* expansion // @@ -373,11 +374,12 @@ c, _ = charge.Get("ch_123", p) c.Customer.ID // ID is still available c.Customer.Name // Name is now also available (if it had a value) ``` + ### How to use undocumented parameters and properties stripe-go is a typed library and it supports all public properties or parameters. -Stripe sometimes launches private beta features which introduce new properties or parameters that are not immediately public. These will not have typed accessors in the stripe-go library but can still be used. +Stripe sometimes launches private beta features which introduce new properties or parameters that are not immediately public. These will not have typed accessors in the stripe-go library but can still be used. #### Parameters @@ -412,13 +414,15 @@ secret_parameter, ok := rawData["secret_parameter"].(map[string]interface{}) if ok { primary := secret_parameter["primary"].(string) secondary := secret_parameter["secondary"].(string) -} +} ``` ### Webhook signing + Stripe can optionally sign the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it [here](https://stripe.com/docs/webhooks/signatures). #### Testing Webhook signing + You can use `stripe.webhook.GenerateTestSignedPayload` to mock webhook events that come from Stripe: ```go @@ -477,10 +481,13 @@ config := &stripe.BackendConfig{ To mock a Stripe client for a unit tests using [GoMock](https://github.com/golang/mock): 1. Generate a `Backend` type mock. + ``` mockgen -destination=mocks/backend.go -package=mocks github.com/stripe/stripe-go/v79 Backend ``` + 2. Use the `Backend` mock to initialize and call methods on the client. + ```go import ( @@ -531,19 +538,89 @@ go get -u github.com/stripe/stripe-go/v79@v77.1.0-beta.1 ``` > **Note** -> There can be breaking changes between beta versions. +> There can be breaking changes between beta versions. We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version. If your beta feature requires a `Stripe-Version` header to be sent, set the `stripe.APIVersion` field using the `stripe.AddBetaVersion` function to set it: > **Note** -> The `APIVersion` can only be set in beta versions of the library. +> The `APIVersion` can only be set in beta versions of the library. ```go stripe.AddBetaVersion("feature_beta", "v3") ``` +### Custom Request + +If you would like to send a request to an API that is: + +- not yet supported in stripe-go (like any `/v2/...` endpoints), or +- undocumented (like a private beta), or +- public, but you prefer to bypass the method definitions in the library and specify your request details directly + +You can use the `rawrequest` package: + +```go +import ( + "encoding/json" + "fmt" + + "github.com/stripe/stripe-go/v79" + "github.com/stripe/stripe-go/v79/form" + "github.com/stripe/stripe-go/v79/rawrequest" +) + +func make_raw_request() error { + stripe.Key = "sk_test_123" + + payload := map[string]interface{}{ + "event_name": "hotdogs_eaten", + "payload": map[string]string{ + "value": "123", + "stripe_customer_id": "cus_Quq8itmW58RMet", + }, + } + + // for a v2 request, json encode the payload + body, err := json.Marshal(payload) + if err != nil { + return err + } + + v2_resp, err := rawrequest.Post("/v2/billing/meter_events", string(body), nil) + if err != nil { + return err + } + + var v2_response map[string]interface{} + err = json.Unmarshal(v2_resp.RawJSON, &v2_response) + if err != nil { + return err + } + fmt.Printf("%#v\n", v2_response) + + // for a v1 request, form encode the payload + formValues := &form.Values{} + form.AppendTo(formValues, payload) + content := formValues.Encode() + + v1_resp, err := rawrequest.Post("/v1/billing/meter_events", content, nil) + if err != nil { + return err + } + + var v1_response map[string]interface{} + err = json.Unmarshal(v1_resp.RawJSON, &v1_response) + if err != nil { + return err + } + fmt.Printf("%#v\n", v1_response) + + return nil +} +``` + ## Support New features and bug fixes are released on the latest major version of the Stripe Go client library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates. diff --git a/api_version.go b/api_version.go index ed98ae37bd..667ebc2877 100644 --- a/api_version.go +++ b/api_version.go @@ -7,5 +7,5 @@ package stripe const ( - apiVersion string = "2024-06-20" + apiVersion string = "2024-09-30.acacia" ) diff --git a/billing/creditbalancesummary/client.go b/billing/creditbalancesummary/client.go new file mode 100644 index 0000000000..2e3c19b7d3 --- /dev/null +++ b/billing/creditbalancesummary/client.go @@ -0,0 +1,42 @@ +// +// +// File generated from our OpenAPI spec +// +// + +// Package creditbalancesummary provides the /billing/credit_balance_summary APIs +package creditbalancesummary + +import ( + "net/http" + + stripe "github.com/stripe/stripe-go/v79" +) + +// Client is used to invoke /billing/credit_balance_summary APIs. +type Client struct { + B stripe.Backend + Key string +} + +// Retrieves the credit balance summary for a customer +func Get(params *stripe.BillingCreditBalanceSummaryParams) (*stripe.BillingCreditBalanceSummary, error) { + return getC().Get(params) +} + +// Retrieves the credit balance summary for a customer +func (c Client) Get(params *stripe.BillingCreditBalanceSummaryParams) (*stripe.BillingCreditBalanceSummary, error) { + creditbalancesummary := &stripe.BillingCreditBalanceSummary{} + err := c.B.Call( + http.MethodGet, + "/v1/billing/credit_balance_summary", + c.Key, + params, + creditbalancesummary, + ) + return creditbalancesummary, err +} + +func getC() Client { + return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key} +} diff --git a/billing/creditbalancetransaction/client.go b/billing/creditbalancetransaction/client.go new file mode 100644 index 0000000000..f778d8d455 --- /dev/null +++ b/billing/creditbalancetransaction/client.go @@ -0,0 +1,77 @@ +// +// +// File generated from our OpenAPI spec +// +// + +// Package creditbalancetransaction provides the /billing/credit_balance_transactions APIs +package creditbalancetransaction + +import ( + "net/http" + + stripe "github.com/stripe/stripe-go/v79" + "github.com/stripe/stripe-go/v79/form" +) + +// Client is used to invoke /billing/credit_balance_transactions APIs. +type Client struct { + B stripe.Backend + Key string +} + +// Retrieves a credit balance transaction +func Get(id string, params *stripe.BillingCreditBalanceTransactionParams) (*stripe.BillingCreditBalanceTransaction, error) { + return getC().Get(id, params) +} + +// Retrieves a credit balance transaction +func (c Client) Get(id string, params *stripe.BillingCreditBalanceTransactionParams) (*stripe.BillingCreditBalanceTransaction, error) { + path := stripe.FormatURLPath("/v1/billing/credit_balance_transactions/%s", id) + creditbalancetransaction := &stripe.BillingCreditBalanceTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditbalancetransaction) + return creditbalancetransaction, err +} + +// Retrieve a list of credit balance transactions +func List(params *stripe.BillingCreditBalanceTransactionListParams) *Iter { + return getC().List(params) +} + +// Retrieve a list of credit balance transactions +func (c Client) List(listParams *stripe.BillingCreditBalanceTransactionListParams) *Iter { + return &Iter{ + Iter: stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) { + list := &stripe.BillingCreditBalanceTransactionList{} + err := c.B.CallRaw(http.MethodGet, "/v1/billing/credit_balance_transactions", c.Key, b, p, list) + + ret := make([]interface{}, len(list.Data)) + for i, v := range list.Data { + ret[i] = v + } + + return ret, list, err + }), + } +} + +// Iter is an iterator for billing credit balance transactions. +type Iter struct { + *stripe.Iter +} + +// BillingCreditBalanceTransaction returns the billing credit balance transaction which the iterator is currently pointing to. +func (i *Iter) BillingCreditBalanceTransaction() *stripe.BillingCreditBalanceTransaction { + return i.Current().(*stripe.BillingCreditBalanceTransaction) +} + +// BillingCreditBalanceTransactionList returns the current list object which the iterator is +// currently using. List objects will change as new API calls are made to +// continue pagination. +func (i *Iter) BillingCreditBalanceTransactionList() *stripe.BillingCreditBalanceTransactionList { + return i.List().(*stripe.BillingCreditBalanceTransactionList) +} + +func getC() Client { + return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key} +} diff --git a/billing/creditgrant/client.go b/billing/creditgrant/client.go new file mode 100644 index 0000000000..93ae7603af --- /dev/null +++ b/billing/creditgrant/client.go @@ -0,0 +1,134 @@ +// +// +// File generated from our OpenAPI spec +// +// + +// Package creditgrant provides the /billing/credit_grants APIs +package creditgrant + +import ( + "net/http" + + stripe "github.com/stripe/stripe-go/v79" + "github.com/stripe/stripe-go/v79/form" +) + +// Client is used to invoke /billing/credit_grants APIs. +type Client struct { + B stripe.Backend + Key string +} + +// Creates a credit grant +func New(params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + return getC().New(params) +} + +// Creates a credit grant +func (c Client) New(params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + creditgrant := &stripe.BillingCreditGrant{} + err := c.B.Call( + http.MethodPost, + "/v1/billing/credit_grants", + c.Key, + params, + creditgrant, + ) + return creditgrant, err +} + +// Retrieves a credit grant +func Get(id string, params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + return getC().Get(id, params) +} + +// Retrieves a credit grant +func (c Client) Get(id string, params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + path := stripe.FormatURLPath("/v1/billing/credit_grants/%s", id) + creditgrant := &stripe.BillingCreditGrant{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Updates a credit grant +func Update(id string, params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + return getC().Update(id, params) +} + +// Updates a credit grant +func (c Client) Update(id string, params *stripe.BillingCreditGrantParams) (*stripe.BillingCreditGrant, error) { + path := stripe.FormatURLPath("/v1/billing/credit_grants/%s", id) + creditgrant := &stripe.BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Expires a credit grant +func Expire(id string, params *stripe.BillingCreditGrantExpireParams) (*stripe.BillingCreditGrant, error) { + return getC().Expire(id, params) +} + +// Expires a credit grant +func (c Client) Expire(id string, params *stripe.BillingCreditGrantExpireParams) (*stripe.BillingCreditGrant, error) { + path := stripe.FormatURLPath("/v1/billing/credit_grants/%s/expire", id) + creditgrant := &stripe.BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Voids a credit grant +func VoidGrant(id string, params *stripe.BillingCreditGrantVoidGrantParams) (*stripe.BillingCreditGrant, error) { + return getC().VoidGrant(id, params) +} + +// Voids a credit grant +func (c Client) VoidGrant(id string, params *stripe.BillingCreditGrantVoidGrantParams) (*stripe.BillingCreditGrant, error) { + path := stripe.FormatURLPath("/v1/billing/credit_grants/%s/void", id) + creditgrant := &stripe.BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Retrieve a list of credit grants +func List(params *stripe.BillingCreditGrantListParams) *Iter { + return getC().List(params) +} + +// Retrieve a list of credit grants +func (c Client) List(listParams *stripe.BillingCreditGrantListParams) *Iter { + return &Iter{ + Iter: stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) { + list := &stripe.BillingCreditGrantList{} + err := c.B.CallRaw(http.MethodGet, "/v1/billing/credit_grants", c.Key, b, p, list) + + ret := make([]interface{}, len(list.Data)) + for i, v := range list.Data { + ret[i] = v + } + + return ret, list, err + }), + } +} + +// Iter is an iterator for billing credit grants. +type Iter struct { + *stripe.Iter +} + +// BillingCreditGrant returns the billing credit grant which the iterator is currently pointing to. +func (i *Iter) BillingCreditGrant() *stripe.BillingCreditGrant { + return i.Current().(*stripe.BillingCreditGrant) +} + +// BillingCreditGrantList returns the current list object which the iterator is +// currently using. List objects will change as new API calls are made to +// continue pagination. +func (i *Iter) BillingCreditGrantList() *stripe.BillingCreditGrantList { + return i.List().(*stripe.BillingCreditGrantList) +} + +func getC() Client { + return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key} +} diff --git a/billing_alert.go b/billing_alert.go index f612d5aa99..8993f803ed 100644 --- a/billing_alert.go +++ b/billing_alert.go @@ -24,12 +24,19 @@ const ( BillingAlertStatusInactive BillingAlertStatus = "inactive" ) +type BillingAlertUsageThresholdFilterType string + +// List of values that BillingAlertUsageThresholdFilterType can take +const ( + BillingAlertUsageThresholdFilterTypeCustomer BillingAlertUsageThresholdFilterType = "customer" +) + // Defines how the alert will behave. -type BillingAlertUsageThresholdConfigRecurrence string +type BillingAlertUsageThresholdRecurrence string -// List of values that BillingAlertUsageThresholdConfigRecurrence can take +// List of values that BillingAlertUsageThresholdRecurrence can take const ( - BillingAlertUsageThresholdConfigRecurrenceOneTime BillingAlertUsageThresholdConfigRecurrence = "one_time" + BillingAlertUsageThresholdRecurrenceOneTime BillingAlertUsageThresholdRecurrence = "one_time" ) // Lists billing active and inactive alerts @@ -48,18 +55,18 @@ func (p *BillingAlertListParams) AddExpand(f string) { p.Expand = append(p.Expand, &f) } -// Filters to limit the scope of an alert. -type BillingAlertFilterParams struct { - // Limit the scope to this alert only to this customer. +// The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. +type BillingAlertUsageThresholdFilterParams struct { + // Limit the scope to this usage alert only to this customer. Customer *string `form:"customer"` - // Limit the scope of this rated usage alert to this subscription. - Subscription *string `form:"subscription"` - // Limit the scope of this rated usage alert to this subscription item. - SubscriptionItem *string `form:"subscription_item"` + // What type of filter is being applied to this usage alert. + Type *string `form:"type"` } // The configuration of the usage threshold. -type BillingAlertUsageThresholdConfigParams struct { +type BillingAlertUsageThresholdParams struct { + // The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. + Filters []*BillingAlertUsageThresholdFilterParams `form:"filters"` // Defines at which value the alert will fire. GTE *int64 `form:"gte"` // The [Billing Meter](https://stripe.com/api/billing/meter) ID whose usage is monitored. @@ -75,12 +82,10 @@ type BillingAlertParams struct { AlertType *string `form:"alert_type"` // Specifies which fields in the response should be expanded. Expand []*string `form:"expand"` - // Filters to limit the scope of an alert. - Filter *BillingAlertFilterParams `form:"filter"` // The title of the alert. Title *string `form:"title"` // The configuration of the usage threshold. - UsageThresholdConfig *BillingAlertUsageThresholdConfigParams `form:"usage_threshold_config"` + UsageThreshold *BillingAlertUsageThresholdParams `form:"usage_threshold"` } // AddExpand appends a new field to expand. @@ -124,20 +129,23 @@ func (p *BillingAlertDeactivateParams) AddExpand(f string) { p.Expand = append(p.Expand, &f) } -// Limits the scope of the alert to a specific [customer](https://stripe.com/docs/api/customers). -type BillingAlertFilter struct { +// The filters allow limiting the scope of this usage alert. You can only specify up to one filter at this time. +type BillingAlertUsageThresholdFilter struct { // Limit the scope of the alert to this customer ID - Customer *Customer `json:"customer"` + Customer *Customer `json:"customer"` + Type BillingAlertUsageThresholdFilterType `json:"type"` } // Encapsulates configuration of the alert to monitor usage on a specific [Billing Meter](https://stripe.com/docs/api/billing/meter). -type BillingAlertUsageThresholdConfig struct { +type BillingAlertUsageThreshold struct { + // The filters allow limiting the scope of this usage alert. You can only specify up to one filter at this time. + Filters []*BillingAlertUsageThresholdFilter `json:"filters"` // The value at which this alert will trigger. GTE int64 `json:"gte"` // The [Billing Meter](https://stripe.com/api/billing/meter) ID whose usage is monitored. Meter *BillingMeter `json:"meter"` // Defines how the alert will behave. - Recurrence BillingAlertUsageThresholdConfigRecurrence `json:"recurrence"` + Recurrence BillingAlertUsageThresholdRecurrence `json:"recurrence"` } // A billing alert is a resource that notifies you when a certain usage threshold on a meter is crossed. For example, you might create a billing alert to notify you when a certain user made 100 API requests. @@ -145,8 +153,6 @@ type BillingAlert struct { APIResource // Defines the type of the alert. AlertType BillingAlertAlertType `json:"alert_type"` - // Limits the scope of the alert to a specific [customer](https://stripe.com/docs/api/customers). - Filter *BillingAlertFilter `json:"filter"` // Unique identifier for the object. ID string `json:"id"` // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. @@ -158,7 +164,7 @@ type BillingAlert struct { // Title of the alert. Title string `json:"title"` // Encapsulates configuration of the alert to monitor usage on a specific [Billing Meter](https://stripe.com/docs/api/billing/meter). - UsageThresholdConfig *BillingAlertUsageThresholdConfig `json:"usage_threshold_config"` + UsageThreshold *BillingAlertUsageThreshold `json:"usage_threshold"` } // BillingAlertList is a list of Alerts as retrieved from a list endpoint. diff --git a/billing_creditbalancesummary.go b/billing_creditbalancesummary.go new file mode 100644 index 0000000000..556cdc060a --- /dev/null +++ b/billing_creditbalancesummary.go @@ -0,0 +1,102 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of this amount. We currently only support `monetary` credits. +type BillingCreditBalanceSummaryBalanceAvailableBalanceType string + +// List of values that BillingCreditBalanceSummaryBalanceAvailableBalanceType can take +const ( + BillingCreditBalanceSummaryBalanceAvailableBalanceTypeMonetary BillingCreditBalanceSummaryBalanceAvailableBalanceType = "monetary" +) + +// The type of this amount. We currently only support `monetary` credits. +type BillingCreditBalanceSummaryBalanceLedgerBalanceType string + +// List of values that BillingCreditBalanceSummaryBalanceLedgerBalanceType can take +const ( + BillingCreditBalanceSummaryBalanceLedgerBalanceTypeMonetary BillingCreditBalanceSummaryBalanceLedgerBalanceType = "monetary" +) + +// The credit applicability scope for which to fetch balance summary. +type BillingCreditBalanceSummaryFilterApplicabilityScopeParams struct { + // The price type to which credit grants can apply to. We currently only support `metered` price type. + PriceType *string `form:"price_type"` +} + +// The filter criteria for the credit balance summary. +type BillingCreditBalanceSummaryFilterParams struct { + // The credit applicability scope for which to fetch balance summary. + ApplicabilityScope *BillingCreditBalanceSummaryFilterApplicabilityScopeParams `form:"applicability_scope"` + // The credit grant for which to fetch balance summary. + CreditGrant *string `form:"credit_grant"` + // Specify the type of this filter. + Type *string `form:"type"` +} + +// Retrieves the credit balance summary for a customer +type BillingCreditBalanceSummaryParams struct { + Params `form:"*"` + // The customer for which to fetch credit balance summary. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The filter criteria for the credit balance summary. + Filter *BillingCreditBalanceSummaryFilterParams `form:"filter"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceSummaryParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditBalanceSummaryBalanceAvailableBalanceMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceSummaryBalanceAvailableBalance struct { + // The monetary amount. + Monetary *BillingCreditBalanceSummaryBalanceAvailableBalanceMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` credits. + Type BillingCreditBalanceSummaryBalanceAvailableBalanceType `json:"type"` +} + +// The monetary amount. +type BillingCreditBalanceSummaryBalanceLedgerBalanceMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceSummaryBalanceLedgerBalance struct { + // The monetary amount. + Monetary *BillingCreditBalanceSummaryBalanceLedgerBalanceMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` credits. + Type BillingCreditBalanceSummaryBalanceLedgerBalanceType `json:"type"` +} + +// The credit balances. One entry per credit grant currency. If a customer only has credit grants in a single currency, then this will have a single balance entry. +type BillingCreditBalanceSummaryBalance struct { + AvailableBalance *BillingCreditBalanceSummaryBalanceAvailableBalance `json:"available_balance"` + LedgerBalance *BillingCreditBalanceSummaryBalanceLedgerBalance `json:"ledger_balance"` +} + +// Indicates the credit balance for credits granted to a customer. +type BillingCreditBalanceSummary struct { + APIResource + // The credit balances. One entry per credit grant currency. If a customer only has credit grants in a single currency, then this will have a single balance entry. + Balances []*BillingCreditBalanceSummaryBalance `json:"balances"` + // The customer the balance is for. + Customer *Customer `json:"customer"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/billing_creditbalancetransaction.go b/billing_creditbalancetransaction.go new file mode 100644 index 0000000000..3087f0b928 --- /dev/null +++ b/billing_creditbalancetransaction.go @@ -0,0 +1,183 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of this amount. We currently only support `monetary` credits. +type BillingCreditBalanceTransactionCreditAmountType string + +// List of values that BillingCreditBalanceTransactionCreditAmountType can take +const ( + BillingCreditBalanceTransactionCreditAmountTypeMonetary BillingCreditBalanceTransactionCreditAmountType = "monetary" +) + +// The type of credit transaction. +type BillingCreditBalanceTransactionCreditType string + +// List of values that BillingCreditBalanceTransactionCreditType can take +const ( + BillingCreditBalanceTransactionCreditTypeCreditsGranted BillingCreditBalanceTransactionCreditType = "credits_granted" +) + +// The type of this amount. We currently only support `monetary` credits. +type BillingCreditBalanceTransactionDebitAmountType string + +// List of values that BillingCreditBalanceTransactionDebitAmountType can take +const ( + BillingCreditBalanceTransactionDebitAmountTypeMonetary BillingCreditBalanceTransactionDebitAmountType = "monetary" +) + +// The type of debit transaction. +type BillingCreditBalanceTransactionDebitType string + +// List of values that BillingCreditBalanceTransactionDebitType can take +const ( + BillingCreditBalanceTransactionDebitTypeCreditsApplied BillingCreditBalanceTransactionDebitType = "credits_applied" + BillingCreditBalanceTransactionDebitTypeCreditsExpired BillingCreditBalanceTransactionDebitType = "credits_expired" + BillingCreditBalanceTransactionDebitTypeCreditsVoided BillingCreditBalanceTransactionDebitType = "credits_voided" +) + +// The type of balance transaction (credit or debit). +type BillingCreditBalanceTransactionType string + +// List of values that BillingCreditBalanceTransactionType can take +const ( + BillingCreditBalanceTransactionTypeCredit BillingCreditBalanceTransactionType = "credit" + BillingCreditBalanceTransactionTypeDebit BillingCreditBalanceTransactionType = "debit" +) + +// Retrieve a list of credit balance transactions +type BillingCreditBalanceTransactionListParams struct { + ListParams `form:"*"` + // The credit grant for which to fetch credit balance transactions. + CreditGrant *string `form:"credit_grant"` + // The customer for which to fetch credit balance transactions. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a credit balance transaction +type BillingCreditBalanceTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditBalanceTransactionCreditAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceTransactionCreditAmount struct { + // The monetary amount. + Monetary *BillingCreditBalanceTransactionCreditAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` credits. + Type BillingCreditBalanceTransactionCreditAmountType `json:"type"` +} + +// Credit details for this balance transaction. Only present if type is `credit`. +type BillingCreditBalanceTransactionCredit struct { + Amount *BillingCreditBalanceTransactionCreditAmount `json:"amount"` + // The type of credit transaction. + Type BillingCreditBalanceTransactionCreditType `json:"type"` +} + +// The monetary amount. +type BillingCreditBalanceTransactionDebitAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceTransactionDebitAmount struct { + // The monetary amount. + Monetary *BillingCreditBalanceTransactionDebitAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` credits. + Type BillingCreditBalanceTransactionDebitAmountType `json:"type"` +} + +// Details of how the credits were applied to an invoice. Only present if `type` is `credits_applied`. +type BillingCreditBalanceTransactionDebitCreditsApplied struct { + // The invoice to which the credits were applied. + Invoice *Invoice `json:"invoice"` + // The invoice line item to which the credits were applied. + InvoiceLineItem string `json:"invoice_line_item"` +} + +// Debit details for this balance transaction. Only present if type is `debit`. +type BillingCreditBalanceTransactionDebit struct { + Amount *BillingCreditBalanceTransactionDebitAmount `json:"amount"` + // Details of how the credits were applied to an invoice. Only present if `type` is `credits_applied`. + CreditsApplied *BillingCreditBalanceTransactionDebitCreditsApplied `json:"credits_applied"` + // The type of debit transaction. + Type BillingCreditBalanceTransactionDebitType `json:"type"` +} + +// A credit balance transaction is a resource representing a transaction (either a credit or a debit) against an existing credit grant. +type BillingCreditBalanceTransaction struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Credit details for this balance transaction. Only present if type is `credit`. + Credit *BillingCreditBalanceTransactionCredit `json:"credit"` + // The credit grant associated with this balance transaction. + CreditGrant *BillingCreditGrant `json:"credit_grant"` + // Debit details for this balance transaction. Only present if type is `debit`. + Debit *BillingCreditBalanceTransactionDebit `json:"debit"` + // The effective time of this balance transaction. + EffectiveAt int64 `json:"effective_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the test clock this credit balance transaction belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + // The type of balance transaction (credit or debit). + Type BillingCreditBalanceTransactionType `json:"type"` +} + +// BillingCreditBalanceTransactionList is a list of CreditBalanceTransactions as retrieved from a list endpoint. +type BillingCreditBalanceTransactionList struct { + APIResource + ListMeta + Data []*BillingCreditBalanceTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingCreditBalanceTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingCreditBalanceTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingCreditBalanceTransaction BillingCreditBalanceTransaction + var v billingCreditBalanceTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingCreditBalanceTransaction(v) + return nil +} diff --git a/billing_creditgrant.go b/billing_creditgrant.go new file mode 100644 index 0000000000..193bb027c8 --- /dev/null +++ b/billing_creditgrant.go @@ -0,0 +1,217 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of this amount. We currently only support `monetary` credits. +type BillingCreditGrantAmountType string + +// List of values that BillingCreditGrantAmountType can take +const ( + BillingCreditGrantAmountTypeMonetary BillingCreditGrantAmountType = "monetary" +) + +// The price type to which credit grants can apply to. We currently only support `metered` price type. +type BillingCreditGrantApplicabilityConfigScopePriceType string + +// List of values that BillingCreditGrantApplicabilityConfigScopePriceType can take +const ( + BillingCreditGrantApplicabilityConfigScopePriceTypeMetered BillingCreditGrantApplicabilityConfigScopePriceType = "metered" +) + +// The category of this credit grant. +type BillingCreditGrantCategory string + +// List of values that BillingCreditGrantCategory can take +const ( + BillingCreditGrantCategoryPaid BillingCreditGrantCategory = "paid" + BillingCreditGrantCategoryPromotional BillingCreditGrantCategory = "promotional" +) + +// Retrieve a list of credit grants +type BillingCreditGrantListParams struct { + ListParams `form:"*"` + // Only return credit grants for this customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditGrantAmountMonetaryParams struct { + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `value` parameter. + Currency *string `form:"currency"` + // A positive integer representing the amount of the credit grant. + Value *int64 `form:"value"` +} + +// Amount of this credit grant. +type BillingCreditGrantAmountParams struct { + // The monetary amount. + Monetary *BillingCreditGrantAmountMonetaryParams `form:"monetary"` + // Specify the type of this amount. We currently only support `monetary` credits. + Type *string `form:"type"` +} + +// Specify the scope of this applicability config. +type BillingCreditGrantApplicabilityConfigScopeParams struct { + // The price type to which credit grants can apply to. We currently only support `metered` price type. + PriceType *string `form:"price_type"` +} + +// Configuration specifying what this credit grant applies to. +type BillingCreditGrantApplicabilityConfigParams struct { + // Specify the scope of this applicability config. + Scope *BillingCreditGrantApplicabilityConfigScopeParams `form:"scope"` +} + +// Creates a credit grant +type BillingCreditGrantParams struct { + Params `form:"*"` + // Amount of this credit grant. + Amount *BillingCreditGrantAmountParams `form:"amount"` + // Configuration specifying what this credit grant applies to. + ApplicabilityConfig *BillingCreditGrantApplicabilityConfigParams `form:"applicability_config"` + // The category of this credit grant. + Category *string `form:"category"` + // Id of the customer to whom the credit should be granted. + Customer *string `form:"customer"` + // The time when the credit becomes effective i.e when it is eligible to be used. Defaults to the current timestamp if not specified. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The time when the credit created by this credit grant will expire. If set to empty, the credit will never expire. + ExpiresAt *int64 `form:"expires_at"` + // Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object (ex: cost basis) in a structured format. + Metadata map[string]string `form:"metadata"` + // A descriptive name shown in dashboard and on invoices. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingCreditGrantParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Expires a credit grant +type BillingCreditGrantExpireParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantExpireParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Voids a credit grant +type BillingCreditGrantVoidGrantParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantVoidGrantParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditGrantAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditGrantAmount struct { + // The monetary amount. + Monetary *BillingCreditGrantAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` credits. + Type BillingCreditGrantAmountType `json:"type"` +} +type BillingCreditGrantApplicabilityConfigScope struct { + // The price type to which credit grants can apply to. We currently only support `metered` price type. + PriceType BillingCreditGrantApplicabilityConfigScopePriceType `json:"price_type"` +} +type BillingCreditGrantApplicabilityConfig struct { + Scope *BillingCreditGrantApplicabilityConfigScope `json:"scope"` +} + +// A credit grant is a resource that records a grant of some credit to a customer. +type BillingCreditGrant struct { + APIResource + Amount *BillingCreditGrantAmount `json:"amount"` + ApplicabilityConfig *BillingCreditGrantApplicabilityConfig `json:"applicability_config"` + // The category of this credit grant. + Category BillingCreditGrantCategory `json:"category"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Id of the customer to whom the credit was granted. + Customer *Customer `json:"customer"` + // The time when the credit becomes effective i.e when it is eligible to be used. + EffectiveAt int64 `json:"effective_at"` + // The time when the credit will expire. If not present, the credit will never expire. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A descriptive name shown in dashboard and on invoices. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the test clock this credit grant belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` + // The time when this credit grant was voided. If not present, the credit grant hasn't been voided. + VoidedAt int64 `json:"voided_at"` +} + +// BillingCreditGrantList is a list of CreditGrants as retrieved from a list endpoint. +type BillingCreditGrantList struct { + APIResource + ListMeta + Data []*BillingCreditGrant `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingCreditGrant. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingCreditGrant) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingCreditGrant BillingCreditGrant + var v billingCreditGrant + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingCreditGrant(v) + return nil +} diff --git a/capability.go b/capability.go index cab2bea632..690c501f31 100644 --- a/capability.go +++ b/capability.go @@ -40,7 +40,7 @@ const ( CapabilityDisabledReasonRequirementsFieldsNeeded CapabilityDisabledReason = "requirements.fields_needed" ) -// The status of the capability. Can be `active`, `inactive`, `pending`, or `unrequested`. +// The status of the capability. type CapabilityStatus string // List of values that CapabilityStatus can take @@ -161,7 +161,7 @@ type Capability struct { // Time at which the capability was requested. Measured in seconds since the Unix epoch. RequestedAt int64 `json:"requested_at"` Requirements *CapabilityRequirements `json:"requirements"` - // The status of the capability. Can be `active`, `inactive`, `pending`, or `unrequested`. + // The status of the capability. Status CapabilityStatus `json:"status"` } diff --git a/checkout_session.go b/checkout_session.go index bc5a769a5c..1896de01f1 100644 --- a/checkout_session.go +++ b/checkout_session.go @@ -1196,7 +1196,7 @@ type CheckoutSessionInvoiceCreationParams struct { // When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. type CheckoutSessionLineItemAdjustableQuantityParams struct { - // Set to true if the quantity can be adjusted to any non-negative integer. By default customers will be able to remove the line item by setting the quantity to 0. + // Set to true if the quantity can be adjusted to any non-negative integer. Enabled *bool `form:"enabled"` // The maximum quantity the customer can purchase for the Checkout Session. By default this value is 99. You can specify a value up to 999999. Maximum *int64 `form:"maximum"` diff --git a/client/api.go b/client/api.go index 5cb9cfa08b..8f88fa8c06 100644 --- a/client/api.go +++ b/client/api.go @@ -19,6 +19,9 @@ import ( "github.com/stripe/stripe-go/v79/balancetransaction" "github.com/stripe/stripe-go/v79/bankaccount" billingalert "github.com/stripe/stripe-go/v79/billing/alert" + billingcreditbalancesummary "github.com/stripe/stripe-go/v79/billing/creditbalancesummary" + billingcreditbalancetransaction "github.com/stripe/stripe-go/v79/billing/creditbalancetransaction" + billingcreditgrant "github.com/stripe/stripe-go/v79/billing/creditgrant" billingmeter "github.com/stripe/stripe-go/v79/billing/meter" billingmeterevent "github.com/stripe/stripe-go/v79/billing/meterevent" billingmetereventadjustment "github.com/stripe/stripe-go/v79/billing/metereventadjustment" @@ -166,6 +169,12 @@ type API struct { BankAccounts *bankaccount.Client // BillingAlerts is the client used to invoke /billing/alerts APIs. BillingAlerts *billingalert.Client + // BillingCreditBalanceSummary is the client used to invoke /billing/credit_balance_summary APIs. + BillingCreditBalanceSummary *billingcreditbalancesummary.Client + // BillingCreditBalanceTransactions is the client used to invoke /billing/credit_balance_transactions APIs. + BillingCreditBalanceTransactions *billingcreditbalancetransaction.Client + // BillingCreditGrants is the client used to invoke /billing/credit_grants APIs. + BillingCreditGrants *billingcreditgrant.Client // BillingMeterEventAdjustments is the client used to invoke /billing/meter_event_adjustments APIs. BillingMeterEventAdjustments *billingmetereventadjustment.Client // BillingMeterEvents is the client used to invoke /billing/meter_events APIs. @@ -434,6 +443,9 @@ func (a *API) Init(key string, backends *stripe.Backends) { a.BalanceTransactions = &balancetransaction.Client{B: backends.API, Key: key} a.BankAccounts = &bankaccount.Client{B: backends.API, Key: key} a.BillingAlerts = &billingalert.Client{B: backends.API, Key: key} + a.BillingCreditBalanceSummary = &billingcreditbalancesummary.Client{B: backends.API, Key: key} + a.BillingCreditBalanceTransactions = &billingcreditbalancetransaction.Client{B: backends.API, Key: key} + a.BillingCreditGrants = &billingcreditgrant.Client{B: backends.API, Key: key} a.BillingMeterEventAdjustments = &billingmetereventadjustment.Client{B: backends.API, Key: key} a.BillingMeterEvents = &billingmeterevent.Client{B: backends.API, Key: key} a.BillingMeterEventSummaries = &billingmetereventsummary.Client{B: backends.API, Key: key} diff --git a/creditnote.go b/creditnote.go index 51596fc106..5d7b1f1720 100644 --- a/creditnote.go +++ b/creditnote.go @@ -8,6 +8,15 @@ package stripe import "encoding/json" +// Type of the pretax credit amount referenced. +type CreditNotePretaxCreditAmountType string + +// List of values that CreditNotePretaxCreditAmountType can take +const ( + CreditNotePretaxCreditAmountTypeCreditBalanceTransaction CreditNotePretaxCreditAmountType = "credit_balance_transaction" + CreditNotePretaxCreditAmountTypeDiscount CreditNotePretaxCreditAmountType = "discount" +) + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` type CreditNoteReason string @@ -399,6 +408,16 @@ type CreditNoteDiscountAmount struct { // The discount that was applied to get this discount amount. Discount *Discount `json:"discount"` } +type CreditNotePretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type CreditNotePretaxCreditAmountType `json:"type"` +} // The taxes applied to the shipping rate. type CreditNoteShippingCostTax struct { @@ -484,7 +503,8 @@ type CreditNote struct { // Amount that was credited outside of Stripe. OutOfBandAmount int64 `json:"out_of_band_amount"` // The link to download the PDF of the credit note. - PDF string `json:"pdf"` + PDF string `json:"pdf"` + PretaxCreditAmounts []*CreditNotePretaxCreditAmount `json:"pretax_credit_amounts"` // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` Reason CreditNoteReason `json:"reason"` // Refund related to this credit note. diff --git a/creditnotelineitem.go b/creditnotelineitem.go index 21375f3fdf..c42f540b66 100644 --- a/creditnotelineitem.go +++ b/creditnotelineitem.go @@ -6,6 +6,15 @@ package stripe +// Type of the pretax credit amount referenced. +type CreditNoteLineItemPretaxCreditAmountType string + +// List of values that CreditNoteLineItemPretaxCreditAmountType can take +const ( + CreditNoteLineItemPretaxCreditAmountTypeCreditBalanceTransaction CreditNoteLineItemPretaxCreditAmountType = "credit_balance_transaction" + CreditNoteLineItemPretaxCreditAmountTypeDiscount CreditNoteLineItemPretaxCreditAmountType = "discount" +) + // The type of the credit note line item, one of `invoice_line_item` or `custom_line_item`. When the type is `invoice_line_item` there is an additional `invoice_line_item` property on the resource the value of which is the id of the credited line item on the invoice. type CreditNoteLineItemType string @@ -22,6 +31,16 @@ type CreditNoteLineItemDiscountAmount struct { // The discount that was applied to get this discount amount. Discount *Discount `json:"discount"` } +type CreditNoteLineItemPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type CreditNoteLineItemPretaxCreditAmountType `json:"type"` +} // CreditNoteLineItem is the resource representing a Stripe credit note line item. // For more details see https://stripe.com/docs/api/credit_notes/line_item @@ -44,7 +63,8 @@ type CreditNoteLineItem struct { // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. Livemode bool `json:"livemode"` // String representing the object's type. Objects of the same type share the same value. - Object string `json:"object"` + Object string `json:"object"` + PretaxCreditAmounts []*CreditNoteLineItemPretaxCreditAmount `json:"pretax_credit_amounts"` // The number of units of product being credited. Quantity int64 `json:"quantity"` // The amount of tax calculated per tax rate for this line item diff --git a/customer.go b/customer.go index 4958a6eddd..dec82b80d5 100644 --- a/customer.go +++ b/customer.go @@ -329,9 +329,8 @@ type CustomerTax struct { Location *CustomerTaxLocation `json:"location"` } -// This object represents a customer of your business. Use it to create recurring charges and track payments that belong to the same customer. -// -// Related guide: [Save a card during payment](https://stripe.com/docs/payments/save-during-payment) +// This object represents a customer of your business. Use it to [create recurring charges](https://stripe.com/docs/invoicing/customer), [save payment](https://stripe.com/docs/payments/save-during-payment) and contact information, +// and track payments that belong to the same customer. type Customer struct { APIResource // The customer's address. diff --git a/example/generated_examples_test.go b/example/generated_examples_test.go index 9aeff183e2..81af6ce890 100644 --- a/example/generated_examples_test.go +++ b/example/generated_examples_test.go @@ -3070,19 +3070,6 @@ func TestTerminalReadersProcessPaymentIntentPost(t *testing.T) { assert.Nil(t, err) } -func TestTerminalReadersProcessSetupIntentPost(t *testing.T) { - params := &stripe.TerminalReaderProcessSetupIntentParams{ - SetupIntent: stripe.String("seti_xxxxxxxxxxxxx"), - CustomerConsentCollected: stripe.Bool(true), - } - result, err := terminal_reader.ProcessSetupIntent( - "tmr_xxxxxxxxxxxxx", - params, - ) - assert.NotNil(t, result) - assert.Nil(t, err) -} - func TestTestHelpersCustomersFundCashBalancePost(t *testing.T) { params := &stripe.TestHelpersCustomerFundCashBalanceParams{ Amount: stripe.Int64(30), diff --git a/invoice.go b/invoice.go index 76c27de045..79290331bb 100644 --- a/invoice.go +++ b/invoice.go @@ -230,6 +230,15 @@ const ( InvoiceStatusVoid InvoiceStatus = "void" ) +// Type of the pretax credit amount referenced. +type InvoiceTotalPretaxCreditAmountType string + +// List of values that InvoiceTotalPretaxCreditAmountType can take +const ( + InvoiceTotalPretaxCreditAmountTypeCreditBalanceTransaction InvoiceTotalPretaxCreditAmountType = "credit_balance_transaction" + InvoiceTotalPretaxCreditAmountTypeDiscount InvoiceTotalPretaxCreditAmountType = "discount" +) + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. type InvoiceTotalTaxAmountTaxabilityReason string @@ -3097,6 +3106,18 @@ type InvoiceTotalDiscountAmount struct { // The discount that was applied to get this discount amount. Discount *Discount `json:"discount"` } +type InvoiceTotalPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // The margin that was applied to get this pretax credit amount. + Margin *Margin `json:"margin"` + // Type of the pretax credit amount referenced. + Type InvoiceTotalPretaxCreditAmountType `json:"type"` +} // The aggregate amounts calculated per tax rate for all line items. type InvoiceTotalTaxAmount struct { @@ -3317,7 +3338,8 @@ type Invoice struct { // The aggregate amounts calculated per discount across all line items. TotalDiscountAmounts []*InvoiceTotalDiscountAmount `json:"total_discount_amounts"` // The integer amount in cents (or local equivalent) representing the total amount of the invoice including all discounts but excluding all tax. - TotalExcludingTax int64 `json:"total_excluding_tax"` + TotalExcludingTax int64 `json:"total_excluding_tax"` + TotalPretaxCreditAmounts []*InvoiceTotalPretaxCreditAmount `json:"total_pretax_credit_amounts"` // The aggregate amounts calculated per tax rate for all line items. TotalTaxAmounts []*InvoiceTotalTaxAmount `json:"total_tax_amounts"` // The account (if any) the payment will be attributed to for tax reporting, and where funds from the payment will be transferred to for the invoice. diff --git a/invoicelineitem.go b/invoicelineitem.go index 475fc9a9a0..2ba748388a 100644 --- a/invoicelineitem.go +++ b/invoicelineitem.go @@ -6,6 +6,15 @@ package stripe +// Type of the pretax credit amount referenced. +type InvoiceLineItemPretaxCreditAmountType string + +// List of values that InvoiceLineItemPretaxCreditAmountType can take +const ( + InvoiceLineItemPretaxCreditAmountTypeCreditBalanceTransaction InvoiceLineItemPretaxCreditAmountType = "credit_balance_transaction" + InvoiceLineItemPretaxCreditAmountTypeDiscount InvoiceLineItemPretaxCreditAmountType = "discount" +) + // A string identifying the type of the source of this line item, either an `invoiceitem` or a `subscription`. type InvoiceLineItemType string @@ -160,6 +169,18 @@ type InvoiceLineItemDiscountAmount struct { // The discount that was applied to get this discount amount. Discount *Discount `json:"discount"` } +type InvoiceLineItemPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // The margin that was applied to get this pretax credit amount. + Margin *Margin `json:"margin"` + // Type of the pretax credit amount referenced. + Type InvoiceLineItemPretaxCreditAmountType `json:"type"` +} // For a credit proration `line_item`, the original debit line_items to which the credit proration applies. type InvoiceLineItemProrationDetailsCreditedItems struct { @@ -208,7 +229,8 @@ type InvoiceLineItem struct { Object string `json:"object"` Period *Period `json:"period"` // The plan of the subscription, if the line item is a subscription or a proration. - Plan *Plan `json:"plan"` + Plan *Plan `json:"plan"` + PretaxCreditAmounts []*InvoiceLineItemPretaxCreditAmount `json:"pretax_credit_amounts"` // The price of the line item. Price *Price `json:"price"` // Whether this is a proration. diff --git a/margin.go b/margin.go new file mode 100644 index 0000000000..94102eefef --- /dev/null +++ b/margin.go @@ -0,0 +1,51 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// A (partner) margin represents a specific discount distributed in partner reseller programs to business partners who +// resell products and services and earn a discount (margin) for doing so. +type Margin struct { + // Whether the margin can be applied to invoices, invoice items, or invoice line items. Defaults to `true`. + Active bool `json:"active"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Name of the margin that's displayed on, for example, invoices. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Percent that will be taken off the subtotal before tax (after all other discounts and promotions) of any invoice to which the margin is applied. + PercentOff float64 `json:"percent_off"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` +} + +// UnmarshalJSON handles deserialization of a Margin. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (m *Margin) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + m.ID = id + return nil + } + + type margin Margin + var v margin + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *m = Margin(v) + return nil +} diff --git a/params.go b/params.go index a1dd51ebb2..b75ceb354f 100644 --- a/params.go +++ b/params.go @@ -172,6 +172,11 @@ type ListParamsContainer interface { GetListParams() *ListParams } +type APIMode string + +var V1APIMode APIMode = "v1" +var V2APIMode APIMode = "v2" + // Params is the structure that contains the common properties // of any *Params structure. type Params struct { @@ -261,6 +266,11 @@ type ParamsContainer interface { GetParams() *Params } +type RawParams struct { + Params `form:"*"` + StripeContext string `form:"-"` +} + // RangeQueryParams are a set of generic request parameters that are used on // list endpoints to filter their results by some timestamp. type RangeQueryParams struct { diff --git a/product.go b/product.go index e57223985f..955c57dc94 100644 --- a/product.go +++ b/product.go @@ -168,6 +168,18 @@ type ProductDefaultPriceDataCurrencyOptionsParams struct { UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` } +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type ProductDefaultPriceDataCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + // The recurring components of a price such as `interval` and `interval_count`. type ProductDefaultPriceDataRecurringParams struct { // Specifies billing frequency. Either `day`, `week`, `month` or `year`. @@ -182,11 +194,13 @@ type ProductDefaultPriceDataParams struct { Currency *string `form:"currency"` // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). CurrencyOptions map[string]*ProductDefaultPriceDataCurrencyOptionsParams `form:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *ProductDefaultPriceDataCustomUnitAmountParams `form:"custom_unit_amount"` // The recurring components of a price such as `interval` and `interval_count`. Recurring *ProductDefaultPriceDataRecurringParams `form:"recurring"` // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. TaxBehavior *string `form:"tax_behavior"` - // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount`, `unit_amount_decimal`, or `custom_unit_amount` is required. UnitAmount *int64 `form:"unit_amount"` // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` diff --git a/promotioncode.go b/promotioncode.go index 6af5c1ac07..ad37d381e7 100644 --- a/promotioncode.go +++ b/promotioncode.go @@ -55,7 +55,9 @@ type PromotionCodeParams struct { Params `form:"*"` // Whether the promotion code is currently active. A promotion code can only be reactivated when the coupon is still valid and the promotion code is otherwise redeemable. Active *bool `form:"active"` - // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. If left blank, we will generate one automatically. + // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. Valid characters are lower case letters (a-z), upper case letters (A-Z), and digits (0-9). + // + // If left blank, we will generate one automatically. Code *string `form:"code"` // The coupon for this promotion code. Coupon *string `form:"coupon"` @@ -109,7 +111,7 @@ type PromotionCode struct { APIResource // Whether the promotion code is currently active. A promotion code is only active if the coupon is also valid. Active bool `json:"active"` - // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for each customer. + // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for each customer. Valid characters are lower case letters (a-z), upper case letters (A-Z), and digits (0-9). Code string `json:"code"` // A coupon contains information about a percent-off or amount-off discount you // might want to apply to a customer. Coupons may be applied to [subscriptions](https://stripe.com/docs/api#subscriptions), [invoices](https://stripe.com/docs/api#invoices), diff --git a/rawrequest/client.go b/rawrequest/client.go new file mode 100644 index 0000000000..2f0904152e --- /dev/null +++ b/rawrequest/client.go @@ -0,0 +1,18 @@ +// Package rawrequest provides sending stripe-flavored untyped HTTP calls +package rawrequest + +import ( + "net/http" + + stripe "github.com/stripe/stripe-go/v79" +) + +func Get(path string, params *stripe.RawParams) (*stripe.APIResponse, error) { + return stripe.RawRequest(http.MethodGet, path, "", params) +} +func Post(path, content string, params *stripe.RawParams) (*stripe.APIResponse, error) { + return stripe.RawRequest(http.MethodPost, path, content, params) +} +func Delete(path string, params *stripe.RawParams) (*stripe.APIResponse, error) { + return stripe.RawRequest(http.MethodDelete, path, "", params) +} diff --git a/rawrequest/client_test.go b/rawrequest/client_test.go new file mode 100644 index 0000000000..d4be9fc7cb --- /dev/null +++ b/rawrequest/client_test.go @@ -0,0 +1,130 @@ +package rawrequest + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + assert "github.com/stretchr/testify/require" + stripe "github.com/stripe/stripe-go/v79" + _ "github.com/stripe/stripe-go/v79/testing" +) + +func stubAPIBackend(testServer *httptest.Server) { + backend := stripe.GetBackendWithConfig( + stripe.APIBackend, + &stripe.BackendConfig{ + LeveledLogger: &stripe.LeveledLogger{ + Level: stripe.LevelDebug, + }, + MaxNetworkRetries: stripe.Int64(0), + URL: stripe.String(testServer.URL), + }, + ).(*stripe.BackendImplementation) + + stripe.SetBackend(stripe.APIBackend, backend) +} + +func TestV2PostRequest(t *testing.T) { + var body string + var path string + var method string + var contentType string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + stubAPIBackend(testServer) + + var params *stripe.RawParams + + _, err := Post("/v2/abc", `{"xyz": {"def": "jih"}}`, params) + assert.NoError(t, err) + + assert.Nil(t, params) // original params should not be modified + assert.Equal(t, `{"xyz": {"def": "jih"}}`, body) + assert.Equal(t, `/v2/abc`, path) + assert.Equal(t, `POST`, method) + assert.Equal(t, `application/json`, contentType) + assert.NoError(t, err) + defer testServer.Close() +} + +func TestRawV1PostRequest(t *testing.T) { + var body string + var path string + var method string + var contentType string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + stubAPIBackend(testServer) + + var params *stripe.RawParams + + _, err := Post("/v1/abc", `abc=123&a[name]=nested`, params) + assert.NoError(t, err) + + assert.Nil(t, params) // original params should not be modified + assert.Equal(t, `abc=123&a[name]=nested`, body) + assert.Equal(t, `/v1/abc`, path) + assert.Equal(t, `POST`, method) + assert.Equal(t, `application/x-www-form-urlencoded`, contentType) + assert.NoError(t, err) + defer testServer.Close() +} + +func TestV2GetRequestWithAdditionalHeaders(t *testing.T) { + var body string + var path string + var method string + var contentType string + var fooHeader string + var stripeContext string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + fooHeader = r.Header.Get("foo") + stripeContext = r.Header.Get("Stripe-Context") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + stubAPIBackend(testServer) + + headers := http.Header{} + headers.Set("foo", "bar") + params := &stripe.RawParams{Params: stripe.Params{Headers: headers}, StripeContext: "acct_123"} + + _, err := Get("/v2/abc", params) + assert.NoError(t, err) + + assert.Equal(t, ``, body) + assert.Equal(t, `/v2/abc`, path) + assert.Equal(t, `GET`, method) + assert.Equal(t, `application/json`, contentType) + assert.Equal(t, `bar`, fooHeader) + assert.Equal(t, `acct_123`, stripeContext) + assert.NoError(t, err) + defer testServer.Close() +} diff --git a/stripe.go b/stripe.go index 74c695d98d..13d3891245 100644 --- a/stripe.go +++ b/stripe.go @@ -206,6 +206,10 @@ type Backend interface { SetMaxNetworkRetries(maxNetworkRetries int64) } +type RawRequestBackend interface { + RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error) +} + // BackendConfig is used to configure a new Stripe backend. type BackendConfig struct { // EnableTelemetry allows request metrics (request id and duration) to be sent @@ -417,14 +421,93 @@ func (s *BackendImplementation) CallMultipart(method, path, key, boundary string return nil } +// the stripe API only accepts GET / POST / DELETE +func validateMethod(method string) error { + if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete { + return fmt.Errorf("method must be POST, GET, or DELETE. Received %s", method) + } + return nil +} + +// RawRequest is the Backend.RawRequest implementation for invoking Stripe APIs. +func (s *BackendImplementation) RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error) { + var bodyBuffer = bytes.NewBuffer(nil) + var commonParams *Params + var err error + var contentType string + + err = validateMethod(method) + if err != nil { + return nil, err + } + + paramsIsNil := params == nil || reflect.ValueOf(params).IsNil() + var apiMode APIMode + if strings.HasPrefix(path, "/v1") { + apiMode = V1APIMode + } else if strings.HasPrefix(path, "/v2") { + apiMode = V2APIMode + } else { + return nil, fmt.Errorf("Unknown path prefix %s", path) + } + + _, commonParams, err = extractParams(params) + if err != nil { + return nil, err + } + + if apiMode == V1APIMode { + contentType = "application/x-www-form-urlencoded" + } else if apiMode == V2APIMode { + contentType = "application/json" + } else { + return nil, fmt.Errorf("Unknown API mode %s", apiMode) + } + + bodyBuffer.WriteString(content) + + req, err := s.NewRequest(method, path, key, contentType, commonParams) + + if err != nil { + return nil, err + } + + if !paramsIsNil { + if params.StripeContext != "" { + req.Header.Set("Stripe-Context", params.StripeContext) + } + } + + handleResponse := func(res *http.Response, err error) (interface{}, error) { + return s.handleResponseBufferingErrors(res, err) + } + + resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, bodyBuffer, handleResponse) + if err != nil { + return nil, err + } + requestID := resp.Header.Get("Request-Id") + s.maybeEnqueueTelemetryMetrics(requestID, requestDuration, []string{"raw_request"}) + body, err := ioutil.ReadAll(result.(io.ReadCloser)) + if err != nil { + return nil, err + } + return newAPIResponse(resp, body, requestDuration), nil +} + // CallRaw is the implementation for invoking Stripe APIs internally without a backend. func (s *BackendImplementation) CallRaw(method, path, key string, form *form.Values, params *Params, v LastResponseSetter) error { var body string if form != nil && !form.Empty() { body = form.Encode() - // On `GET`, move the payload into the URL - if method == http.MethodGet { + err := validateMethod(method) + if err != nil { + return err + } + + // On `GET` / `DELETE`, move the payload into the URL + if method != http.MethodPost { path += "?" + body body = "" } @@ -670,36 +753,39 @@ func (s *BackendImplementation) logError(statusCode int, err error) { } } +func (s *BackendImplementation) handleResponseBufferingErrors(res *http.Response, err error) (io.ReadCloser, error) { + // Some sort of connection error + if err != nil { + s.LeveledLogger.Errorf("Request failed with error: %v", err) + return res.Body, err + } + + // Successful response, return the body ReadCloser + if res.StatusCode < 400 { + return res.Body, err + } + + // Failure: try and parse the json of the response + // when logging the error + var resBody []byte + resBody, err = ioutil.ReadAll(res.Body) + res.Body.Close() + if err == nil { + err = s.ResponseToError(res, resBody) + } else { + s.logError(res.StatusCode, err) + } + + return res.Body, err +} + // DoStreaming is used by CallStreaming to execute an API request. It uses the // backend's HTTP client to execure the request. In successful cases, it sets // a StreamingLastResponse onto v, but in unsuccessful cases handles unmarshaling // errors returned by the API. func (s *BackendImplementation) DoStreaming(req *http.Request, body *bytes.Buffer, v StreamingLastResponseSetter) error { handleResponse := func(res *http.Response, err error) (interface{}, error) { - - // Some sort of connection error - if err != nil { - s.LeveledLogger.Errorf("Request failed with error: %v", err) - return res.Body, err - } - - // Successful response, return the body ReadCloser - if res.StatusCode < 400 { - return res.Body, err - } - - // Failure: try and parse the json of the response - // when logging the error - var resBody []byte - resBody, err = ioutil.ReadAll(res.Body) - res.Body.Close() - if err == nil { - err = s.ResponseToError(res, resBody) - } else { - s.logError(res.StatusCode, err) - } - - return res.Body, err + return s.handleResponseBufferingErrors(res, err) } resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, body, handleResponse) @@ -1495,3 +1581,10 @@ func normalizeURL(url string) string { return url } + +func RawRequest(method, path string, content string, params *RawParams) (*APIResponse, error) { + if bi, ok := GetBackend(APIBackend).(RawRequestBackend); ok { + return bi.RawRequest(method, path, Key, content, params) + } + return nil, fmt.Errorf("Error: cannot call RawRequest if backends.API is initialized with a backend that doesn't implement RawRequestBackend") +} diff --git a/stripe_test.go b/stripe_test.go index 335465d19d..537674e900 100644 --- a/stripe_test.go +++ b/stripe_test.go @@ -549,7 +549,7 @@ func TestCall_TelemetryEnabled(t *testing.T) { params.InternalSetUsage([]string{"llama", "bufo"}) for i := 0; i < 2; i++ { var response testServerResponse - err := backend.Call("get", "/hello", "sk_test_xyz", params, &response) + err := backend.Call("GET", "/hello", "sk_test_xyz", params, &response) assert.NoError(t, err) assert.Equal(t, message, response.Message) @@ -1280,6 +1280,213 @@ func TestBoolSlice(t *testing.T) { assert.Equal(t, 0, len(BoolSlice(nil))) } +func TestRawRequestPreviewPost(t *testing.T) { + var body string + var path string + var method string + var contentType string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + backend := GetBackendWithConfig( + APIBackend, + &BackendConfig{ + LeveledLogger: debugLeveledLogger, + MaxNetworkRetries: Int64(0), + URL: String(testServer.URL), + }, + ).(*BackendImplementation) + + type MyXYZ struct { + DEF string `json:"def"` + } + type MyABC struct { + Object string `json:"object"` + XYZ MyXYZ `json:"xyz"` + } + params := &RawParams{Params: Params{}} + response, err := backend.RawRequest(http.MethodPost, "/v2/abcs", "sk_test_xyz", `{"foo":"myFoo","bar":{"baz":false}}`, params) + assert.NoError(t, err) + myABC := &MyABC{} + assert.Nil(t, params.Headers) + assert.Equal(t, `{"foo":"myFoo","bar":{"baz":false}}`, body) + assert.Equal(t, `/v2/abcs`, path) + assert.Equal(t, `POST`, method) + assert.Equal(t, `application/json`, contentType) + // assert.Equal(t, previewVersion, stripeVersion) + err = json.Unmarshal(response.RawJSON, myABC) + assert.NoError(t, err) + assert.Equal(t, "jih", myABC.XYZ.DEF) + assert.Equal(t, "abc", myABC.Object) + defer testServer.Close() +} + +func TestRawRequestStandardGet(t *testing.T) { + var body string + var path string + var method string + var contentType string + var stripeVersion string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + stripeVersion = r.Header.Get("Stripe-Version") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + backend := GetBackendWithConfig( + APIBackend, + &BackendConfig{ + LeveledLogger: debugLeveledLogger, + MaxNetworkRetries: Int64(0), + URL: String(testServer.URL), + }, + ).(*BackendImplementation) + + _, err := backend.RawRequest(http.MethodGet, "/v1/abc?foo=myFoo", "sk_test_xyz", ``, nil) + assert.NoError(t, err) + assert.Equal(t, ``, body) + assert.Equal(t, `/v1/abc?foo=myFoo`, path) + assert.Equal(t, `GET`, method) + assert.Equal(t, `application/x-www-form-urlencoded`, contentType) + assert.Equal(t, apiVersion, stripeVersion) + assert.NoError(t, err) + defer testServer.Close() +} + +func TestRawRequestStandardPost(t *testing.T) { + var body string + var path string + var method string + var contentType string + var stripeVersion string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + stripeVersion = r.Header.Get("Stripe-Version") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + backend := GetBackendWithConfig( + APIBackend, + &BackendConfig{ + LeveledLogger: debugLeveledLogger, + MaxNetworkRetries: Int64(0), + URL: String(testServer.URL), + }, + ).(*BackendImplementation) + + _, err := backend.RawRequest(http.MethodPost, "/v1/abc", "sk_test_xyz", `foo=myFoo`, nil) + assert.NoError(t, err) + assert.Equal(t, `foo=myFoo`, body) + assert.Equal(t, `/v1/abc`, path) + assert.Equal(t, `POST`, method) + assert.Equal(t, `application/x-www-form-urlencoded`, contentType) + assert.Equal(t, apiVersion, stripeVersion) + assert.NoError(t, err) + defer testServer.Close() +} + +func TestRawRequestPreviewGet(t *testing.T) { + var body string + var path string + var method string + var contentType string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + backend := GetBackendWithConfig( + APIBackend, + &BackendConfig{ + LeveledLogger: debugLeveledLogger, + MaxNetworkRetries: Int64(0), + URL: String(testServer.URL), + }, + ).(*BackendImplementation) + + params := &RawParams{Params: Params{}} + _, err := backend.RawRequest(http.MethodGet, "/v2/abc?foo=myFoo", "sk_test_xyz", ``, params) + assert.NoError(t, err) + assert.Equal(t, ``, body) + assert.Equal(t, `/v2/abc?foo=myFoo`, path) + assert.Equal(t, `GET`, method) + assert.Equal(t, `application/json`, contentType) + // assert.Equal(t, previewVersion, stripeVersion) + assert.NoError(t, err) + defer testServer.Close() +} + +func TestRawRequestWithAdditionalHeaders(t *testing.T) { + var body string + var path string + var method string + var contentType string + var fooHeader string + var stripeContext string + testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req, _ := ioutil.ReadAll(r.Body) + r.Body.Close() + body = string(req) + path = r.URL.RequestURI() + method = r.Method + contentType = r.Header.Get("Content-Type") + fooHeader = r.Header.Get("foo") + stripeContext = r.Header.Get("Stripe-Context") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"object": "abc", "xyz": {"def": "jih"}}`)) + })) + + backend := GetBackendWithConfig( + APIBackend, + &BackendConfig{ + LeveledLogger: debugLeveledLogger, + MaxNetworkRetries: Int64(0), + URL: String(testServer.URL), + }, + ).(*BackendImplementation) + + headers := http.Header{} + headers.Set("foo", "bar") + params := &RawParams{Params: Params{Headers: headers}, StripeContext: "acct_123"} + + _, err := backend.RawRequest(http.MethodPost, "/v2/abc", "sk_test_xyz", `{"foo":"myFoo"}`, params) + assert.NoError(t, err) + assert.Equal(t, `{"foo":"myFoo"}`, body) + assert.Equal(t, `/v2/abc`, path) + assert.Equal(t, `POST`, method) + assert.Equal(t, `application/json`, contentType) + assert.Equal(t, `bar`, fooHeader) + assert.Equal(t, `acct_123`, stripeContext) + assert.NoError(t, err) + defer testServer.Close() +} + // // --- // diff --git a/subscription.go b/subscription.go index 38f9fc9ba6..6fbfddc9e4 100644 --- a/subscription.go +++ b/subscription.go @@ -278,11 +278,11 @@ type SubscriptionCancelCancellationDetailsParams struct { Feedback *string `form:"feedback"` } -// Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. +// Cancels a customer's subscription immediately. The customer won't be charged again for the subscription. After it's canceled, you can no longer update the subscription or its [metadata](https://stripe.com/metadata). // -// Note, however, that any pending invoice items that you've created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed. +// Any pending invoice items that you've created are still charged at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations are also left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations are removed. // -// By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. +// By default, upon subscription cancellation, Stripe stops automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. type SubscriptionCancelParams struct { Params `form:"*"` // Details about why this subscription was cancelled diff --git a/subscription/client.go b/subscription/client.go index 638891c786..ce97ede7db 100644 --- a/subscription/client.go +++ b/subscription/client.go @@ -112,20 +112,20 @@ func (c Client) Update(id string, params *stripe.SubscriptionParams) (*stripe.Su return subscription, err } -// Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. +// Cancels a customer's subscription immediately. The customer won't be charged again for the subscription. After it's canceled, you can no longer update the subscription or its [metadata](https://stripe.com/metadata). // -// Note, however, that any pending invoice items that you've created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed. +// Any pending invoice items that you've created are still charged at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations are also left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations are removed. // -// By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. +// By default, upon subscription cancellation, Stripe stops automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. func Cancel(id string, params *stripe.SubscriptionCancelParams) (*stripe.Subscription, error) { return getC().Cancel(id, params) } -// Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. +// Cancels a customer's subscription immediately. The customer won't be charged again for the subscription. After it's canceled, you can no longer update the subscription or its [metadata](https://stripe.com/metadata). // -// Note, however, that any pending invoice items that you've created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed. +// Any pending invoice items that you've created are still charged at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations are also left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations are removed. // -// By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. +// By default, upon subscription cancellation, Stripe stops automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. func (c Client) Cancel(id string, params *stripe.SubscriptionCancelParams) (*stripe.Subscription, error) { path := stripe.FormatURLPath("/v1/subscriptions/%s", id) subscription := &stripe.Subscription{} diff --git a/tax_settings.go b/tax_settings.go index 9c6b384c70..6fec34b3c2 100644 --- a/tax_settings.go +++ b/tax_settings.go @@ -16,7 +16,7 @@ const ( TaxSettingsDefaultsTaxBehaviorInferredByCurrency TaxSettingsDefaultsTaxBehavior = "inferred_by_currency" ) -// The `active` status indicates you have all required settings to calculate tax. A status can transition out of `active` when new required settings are introduced. +// The status of the Tax `Settings`. type TaxSettingsStatus string // List of values that TaxSettingsStatus can take @@ -87,7 +87,7 @@ type TaxSettings struct { Livemode bool `json:"livemode"` // String representing the object's type. Objects of the same type share the same value. Object string `json:"object"` - // The `active` status indicates you have all required settings to calculate tax. A status can transition out of `active` when new required settings are introduced. + // The status of the Tax `Settings`. Status TaxSettingsStatus `json:"status"` StatusDetails *TaxSettingsStatusDetails `json:"status_details"` } diff --git a/terminal_reader.go b/terminal_reader.go index 08a9b84fd1..79352094d1 100644 --- a/terminal_reader.go +++ b/terminal_reader.go @@ -138,6 +138,8 @@ type TerminalReaderProcessPaymentIntentProcessConfigTippingParams struct { // Configuration overrides type TerminalReaderProcessPaymentIntentProcessConfigParams struct { + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` // Enables cancel button on transaction screens. EnableCustomerCancellation *bool `form:"enable_customer_cancellation"` // Override showing a tipping selection screen on this transaction. @@ -171,8 +173,8 @@ type TerminalReaderProcessSetupIntentProcessConfigParams struct { // Initiates a setup intent flow on a Reader. type TerminalReaderProcessSetupIntentParams struct { Params `form:"*"` - // Customer Consent Collected - CustomerConsentCollected *bool `form:"customer_consent_collected"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` // Specifies which fields in the response should be expanded. Expand []*string `form:"expand"` // Configuration overrides diff --git a/treasury_receivedcredit.go b/treasury_receivedcredit.go index 3d8583ceb0..07a9c52947 100644 --- a/treasury_receivedcredit.go +++ b/treasury_receivedcredit.go @@ -11,9 +11,10 @@ type TreasuryReceivedCreditFailureCode string // List of values that TreasuryReceivedCreditFailureCode can take const ( - TreasuryReceivedCreditFailureCodeAccountClosed TreasuryReceivedCreditFailureCode = "account_closed" - TreasuryReceivedCreditFailureCodeAccountFrozen TreasuryReceivedCreditFailureCode = "account_frozen" - TreasuryReceivedCreditFailureCodeOther TreasuryReceivedCreditFailureCode = "other" + TreasuryReceivedCreditFailureCodeAccountClosed TreasuryReceivedCreditFailureCode = "account_closed" + TreasuryReceivedCreditFailureCodeAccountFrozen TreasuryReceivedCreditFailureCode = "account_frozen" + TreasuryReceivedCreditFailureCodeInternationalTransaction TreasuryReceivedCreditFailureCode = "international_transaction" + TreasuryReceivedCreditFailureCodeOther TreasuryReceivedCreditFailureCode = "other" ) // Set when `type` is `balance`.