こちらのページの続きです。
stripe API 使い方 (List all customers)
#Go http でカスタマーの一覧を取得#
必要なライブラリーのインストール
go get github.com/joho/godotenv
go mod init get_customers_http
go mod tidy
get_customers_http.go
// ---------------------------------------------------------------
// get_customers_http.go
//
// Dec/17/2021
// ---------------------------------------------------------------
package main
import (
"os"
"fmt"
"io/ioutil"
"net/http"
"github.com/joho/godotenv"
"encoding/json"
)
// ---------------------------------------------------------------
func main() {
fmt.Printf ("*** 開始 ***\n")
err := godotenv.Load(".env")
if err != nil {
panic(err)
}
secret_key := os.Getenv("SECRET_KEY")
url_target := "https://api.stripe.com/v1/customers"
req, _ := http.NewRequest("GET", url_target, nil)
req.Header.Set("Authorization", "Bearer " + secret_key)
client := new(http.Client)
res, err := client.Do(req)
if err != nil {
fmt.Println("Request error:", err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Request error:", err)
return
}
str_json := string(body)
var dict_aa map[string]interface{}
json.Unmarshal ([]byte(str_json), &dict_aa )
slice_aa := dict_aa["data"].([]interface{})
nn := len(slice_aa)
fmt.Printf("nn = %d\n", nn)
for it := 0; it < nn; it++ {
unit := dict_aa["data"].([]interface{})[it]
fmt.Println(unit.(map[string]interface{})["id"])
}
fmt.Printf ("*** 終了 ***\n")
}
// ---------------------------------------------------------------
実行結果
$ go run get_customers_http.go
*** 開始 ***
nn = 4
cus_KmrIU4hzWqYt7R
cus_KmoG4k1wiKxSDc
cus_KmnqmJhBAvPGMq
cus_KmnpiRFjm8he97
*** 終了 ***
#Go sdk でカスタマーの一覧を取得#
sdk のインストール
go get github.com/stripe/stripe-go/v72
go mod init get_customers_sdk
go mod tidy
get_customers_sdk.go
// ---------------------------------------------------------------
// get_customers_sdk.go
//
// Dec/17/2021
// ---------------------------------------------------------------
package main
import (
"os"
"fmt"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/customer"
"github.com/joho/godotenv"
)
// ---------------------------------------------------------------
func main () {
err := godotenv.Load(".env")
if err != nil {
panic(err)
}
stripe.Key = os.Getenv("SECRET_KEY")
params := &stripe.CustomerListParams{}
params.Filters.AddFilter("limit", "", "10")
ii := customer.List(params)
for ii.Next() {
cc := ii.Customer()
fmt.Println(cc.ID)
}
}
// ---------------------------------------------------------------
実行結果
$ go run get_customers_sdk.go
cus_KmrIU4hzWqYt7R
cus_KmoG4k1wiKxSDc
cus_KmnqmJhBAvPGMq
cus_KmnpiRFjm8he97