Skip to content

Commit

Permalink
Merge branch 'master' into latest-codegen-master
Browse files Browse the repository at this point in the history
  • Loading branch information
prathmesh-stripe authored Oct 29, 2024
2 parents 9a0f02f + 1665054 commit 36e4985
Show file tree
Hide file tree
Showing 11 changed files with 373 additions and 39 deletions.
38 changes: 23 additions & 15 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
# Changelog

## 80.2.0 - 2024-10-09
* [#1929](https://github.com/stripe/stripe-go/pull/1929), [#1933](https://github.com/stripe/stripe-go/pull/1933) Remove rawrequests Post, Get, and Delete in favor of rawrequests.Client
* The individual `rawrequests` functions for Post, Get, and Delete methods are removed in favor of the client model which allows local configuration of backend and api key, which enables more flexible calls to new/preview/unsupported APIs.

## 80.1.0 - 2024-10-03
* [#1928](https://github.com/stripe/stripe-go/pull/1928) Update generated code
* Remove the support for resource `Margin` that was accidentally made public in the last release

## 80.0.0 - 2024-10-01
* [#1926](https://github.com/stripe/stripe-go/pull/1926) Support for APIs in the new API version 2024-09-30.acacia

This release changes the pinned API version to `2024-09-30.acacia`. Please read the [API Upgrade Guide](https://stripe.com/docs/upgrades#2024-09-30.acacia) and carefully review the API changes before upgrading.

### ⚠️ Breaking changes

* Rename `usage_threshold_config` to `usage_threshold` on `BillingAlertParams` and `BillingAlert`
* Remove support for `filter` on `BillingAlertParams` and `BillingAlert`. Use the filters on the `usage_threshold` instead
* Remove support for `CustomerConsentCollected` on `TerminalReaderProcessSetupIntentParams`


### Additions
* Add support for `CustomUnitAmount` on `ProductDefaultPriceDataParams`
* Add support for `AllowRedisplay` on `TerminalReaderProcessPaymentIntentProcessConfigParams` and `TerminalReaderProcessSetupIntentParams`
* Add support for new value `international_transaction` on enum `TreasuryReceivedCreditFailureCode`
* Add method [RawRequest()](https://github.com/stripe/stripe-go/tree/master?tab=readme-ov-file#custom-requests) that takes a HTTP method type, url and relevant parameters to make requests to the Stripe API that are not yet supported in the SDK.

This release changes the pinned API version to `2024-09-30.acacia`. Please read the [API Upgrade Guide](https://stripe.com/docs/upgrades#2024-09-30.acacia) and carefully review the API changes before upgrading.

### ⚠️ Breaking changes

* Rename `usage_threshold_config` to `usage_threshold` on `BillingAlertParams` and `BillingAlert`
* Remove support for `filter` on `BillingAlertParams` and `BillingAlert`. Use the filters on the `usage_threshold` instead
* Remove support for `CustomerConsentCollected` on `TerminalReaderProcessSetupIntentParams`


### Additions
* Add support for `CustomUnitAmount` on `ProductDefaultPriceDataParams`
* Add support for `AllowRedisplay` on `TerminalReaderProcessPaymentIntentProcessConfigParams` and `TerminalReaderProcessSetupIntentParams`
* Add support for new value `international_transaction` on enum `TreasuryReceivedCreditFailureCode`
* Add method [RawRequest()](https://github.com/stripe/stripe-go/tree/master?tab=readme-ov-file#custom-requests) that takes a HTTP method type, url and relevant parameters to make requests to the Stripe API that are not yet supported in the SDK.

## 79.12.0 - 2024-09-18
* [#1919](https://github.com/stripe/stripe-go/pull/1919) Update generated code
Expand Down
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ We would love for you to try these and share feedback with us before these featu
To install a beta version of stripe-go use the commit notation of the `go get` command to point to a beta tag:

```
go get -u github.com/stripe/stripe-go/v80@v77.1.0-beta.1
go get -u github.com/stripe/stripe-go/v80@beta
```

> **Note**
Expand Down Expand Up @@ -574,6 +574,13 @@ import (
func make_raw_request() error {
stripe.Key = "sk_test_123"

b, err := stripe.GetRawRequestBackend(stripe.APIBackend)
if err != nil {
return err
}

client := rawrequest.Client{B: b, Key: apiKey}

payload := map[string]interface{}{
"event_name": "hotdogs_eaten",
"payload": map[string]string{
Expand All @@ -588,7 +595,7 @@ func make_raw_request() error {
return err
}

v2_resp, err := rawrequest.Post("/v2/billing/meter_events", string(body), nil)
v2_resp, err := client.RawRequest(http.MethodPost, "/v2/billing/meter_events", string(body), nil)
if err != nil {
return err
}
Expand All @@ -605,7 +612,7 @@ func make_raw_request() error {
form.AppendTo(formValues, payload)
content := formValues.Encode()

v1_resp, err := rawrequest.Post("/v1/billing/meter_events", content, nil)
v1_resp, err := client.RawRequest(http.MethodPost, "/v1/billing/meter_events", content, nil)
if err != nil {
return err
}
Expand All @@ -619,7 +626,9 @@ func make_raw_request() error {

return nil
}

```
See more examples in the [/example/v2 folder](example/v2).

## Support

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
80.0.0
80.2.0
112 changes: 112 additions & 0 deletions example/v2/meter_event_stream/meter_event_stream.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// meter_event_stream.go - use the high-throughput meter event stream to report create billing meter events.
//
// This example uses the rawrequests module to make calls to /v2 APIs.
//
// In this example, we:
// - create a meter event session and store the session's authentication token
// - define an event with a payload
// - post the event to /v2/billing/meter_event_stream to create an event stream that reports this event
//
// This example expects a billing meter with an event_name of 'alpaca_ai_tokens'. If you have
// a different meter event name, you can change it before running this example.
package main

import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"

stripe "github.com/stripe/stripe-go/v80"
rawrequest "github.com/stripe/stripe-go/v80/rawrequest"
)

var sessionAuthToken string = ""
var sessionAuthExpiresAt string = ""

func refreshMeterEventSession(client rawrequest.Client) (err error) {
currentTime := time.Now().Format(time.RFC3339)
// Check if session is null or expired
if sessionAuthToken == "" || sessionAuthExpiresAt <= currentTime {
// Create a new meter event session in case the existing session expired
rawResp, err := client.RawRequest(http.MethodPost, "/v2/billing/meter_event_session", "", nil)
if err != nil {
return err
}
if rawResp.StatusCode != 200 {
return fmt.Errorf(rawResp.Status)
}

var resp map[string]interface{}
err = json.Unmarshal(rawResp.RawJSON, &resp)
if err != nil {
return err
}

sessionAuthToken = resp["authentication_token"].(string)
sessionAuthExpiresAt = resp["expires_at"].(string)

fmt.Println("Meter event session created!")
}
return nil
}

func sendMeterEvent(client rawrequest.Client, eventName string, stripeCustomerID string, value string) (err error) {
// Refresh the meter event session if necessary
refreshMeterEventSession(client)

if sessionAuthToken == "" {
err = fmt.Errorf("Unable to refresh meter event session")
return
}

b, err := stripe.GetRawRequestBackend(stripe.MeterEventsBackend)
if err != nil {
return err
}

sessionClient := rawrequest.Client{B: b, Key: sessionAuthToken}

params := map[string]interface{}{
"events": []interface{}{
map[string]interface{}{
"event_name": eventName,
"payload": map[string]interface{}{
"stripe_customer_id": stripeCustomerID,
"value": value,
},
},
},
}

contentBytes, err := json.Marshal(params)
if err != nil {
return
}

content := string(contentBytes)
_, err = sessionClient.RawRequest(http.MethodPost, "/v2/billing/meter_event_stream", content, nil)
return
}

func main() {

apiKey := "{{API_KEY}}"
customerID := "{{CUSTOMER_ID}}"

b, err := stripe.GetRawRequestBackend(stripe.APIBackend)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

client := rawrequest.Client{B: b, Key: apiKey}

err = sendMeterEvent(client, "alpaca_ai_tokens", customerID, "25")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Meter event sent successfully!")
}
106 changes: 106 additions & 0 deletions example/v2/thinevent_webhook_handler/thinevent_webhook_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// thinevent_webhook_handler.go - receive and process thin events like the
// v1.billing.meter.error_report_triggered event.
//
// This example uses the rawrequests module to make calls to /v2 APIs.
//
// In this example, we:
// - parse the incoming thin event payload and get the event id
// - get the full event from /v2/core/events/ with the event id from the thin event
// - if the full event is a v1.billing.meter.error_report_triggered, use the
// billing/meter package to retrieve the Billing Meter object associated with the
// event.
package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"

"github.com/stripe/stripe-go/v80"
billingMeters "github.com/stripe/stripe-go/v80/billing/meter"
"github.com/stripe/stripe-go/v80/rawrequest"
webhook "github.com/stripe/stripe-go/v80/webhook"
)

var apiKey = "{{API_KEY}}"
var webhookSecret = "{{WEBHOOK_SECRET}}"

func main() {
b, err := stripe.GetRawRequestBackend(stripe.APIBackend)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

client := rawrequest.Client{B: b, Key: apiKey}

http.HandleFunc("/webhook", func(w http.ResponseWriter, req *http.Request) {
const MaxBodyBytes = int64(65536)
req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes)
payload, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

err = webhook.ValidatePayload(payload, req.Header.Get("Stripe-Signature"), webhookSecret)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

var thinEvent map[string]interface{}

if err := json.Unmarshal(payload, &thinEvent); err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse thin event body json: %v\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}

eventID := thinEvent["id"].(string)

var event map[string]interface{}

resp, err := client.RawRequest(http.MethodGet, "/v2/core/events/"+eventID, "", nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get pull event: %v\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}

if err := json.Unmarshal(resp.RawJSON, &event); err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse pull event body json: %v\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
// Unmarshal the event data into an appropriate struct depending on its Type
switch t := event["type"].(string); t {
case "v1.billing.meter.error_report_triggered":
relatedObject := event["related_object"].(map[string]interface{})
meter, err := billingMeters.Get(relatedObject["id"].(string), nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get related meter object: %v\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}

meterID := meter.ID
fmt.Printf("Success! %s\n", meterID)
// Verify we can see event data
fmt.Println(fmt.Sprint(event["data"]))
default:
fmt.Fprintf(os.Stderr, "Unhandled event type: %s\n", t)
}

w.WriteHeader(http.StatusOK)
})
err = http.ListenAndServe(":4242", nil)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
16 changes: 7 additions & 9 deletions rawrequest/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
package rawrequest

import (
"net/http"

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

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)
// Client is used to invoke raw requests against the specified backend
type Client struct {
B stripe.RawRequestBackend
Key string
}
func Delete(path string, params *stripe.RawParams) (*stripe.APIResponse, error) {
return stripe.RawRequest(http.MethodDelete, path, "", params)

func (c Client) RawRequest(method string, path string, content string, params *stripe.RawParams) (*stripe.APIResponse, error) {
return c.B.RawRequest(method, path, c.Key, content, params)
}
Loading

0 comments on commit 36e4985

Please sign in to comment.