Chapter 04無料公開

Stripe Resource commandsでStripeリソースにアクセスする

hidetaka okamoto
hidetaka okamoto
2021.03.09に更新

Stripeはほぼ全てのリソースがAPIを通してアクセス・操作できます。そしてStripe CLIは、このAPIを呼び出してStripeのリソースにアクセスするためのコマンドも用意しています。

stripe resources helpコマンドで、アクセス可能なリソースをチェックする

Stripe CLIでアクセスできるリソースの確認は、stripe resources helpコマンドで行えます。

% stripe resources help
Available commands:
  3d_secure                     
  account_links                 
  accounts                      
  apple_pay_domains             
  application_fees              
  balance                       
  balance_transactions          
  bank_accounts                 
  billing_portal                
  capabilities                  
  cards                         
  charges                       
  checkout
  ...

Dashboardの表示名ではなく、APIのパス・リソース名ベースで探す必要があります。

[v1.5.9時点情報]Billingsのplansとpricesは互換性あり

PlanからPriceに変更されたStripe Billingsの価格ですが、今のところstripe prices retrive plan_xxxstripe plans retrieve price_xxxのような使い方をしてもデータを取得できます。

ただしPlanとPriceはそれぞれデータ構造が異なりますので、できるだけPrice側を使う・Price側に切り替えていくことをお勧めします。

Stripe CLIからtest環境でCustomerを作成・取得・削除する

Stripe CLIからリソースを早速操作してみましょう。リソース系のコマンドは、原則stripe <リソース名> <操作> <オプション>で構成されています。

StripeのCustomerを作成する場合は、以下のようなコマンドを実行しましょう。

$ stripe customers create \
  --description="My First Test Customer (created for API docs)"

{
  "id": "cus_J5DadJ0IR5nS0d",
  "object": "customer",
  "address": null,
  "balance": 0,
  "created": 1615287033,
  "currency": null,
  "default_source": null,
  "delinquent": false,
  "description": "My First Test Customer (created for API docs)",
  ...

API同様、作成したリソースはretrieve <customer_id>で取得できます。

% stripe customers retrieve cus_J5DadJ0IR5nS0d
{
  "id": "cus_J5DadJ0IR5nS0d",
  "object": "customer",
  "address": null,
  "balance": 0,
  "created": 1615287033,
  "currency": null,
  "default_source": null,
  "delinquent": false,
  "description": "My First Test Customer (created for API docs)",

最後に削除ですが、こちらもdelete <customer_id>で実行できます。
ただし、削除については削除の確認が行われますので、yesと入力してやる必要があります。

% stripe customers delete cus_J5DadJ0IR5nS0d
This command will be executed on the account with the following details:
> Mode: Test
> Account Name: api-test
Are you sure you want to perform the command: DELETE?
Enter 'yes' to confirm: yes
{
  "id": "cus_J5DadJ0IR5nS0d",
  "object": "customer",
  "deleted": true
}

もし確認ステップが不要の場合は、--confirmを追加しましょう。

% stripe customers delete cus_J5DadJ0IR5nS0d --confirm
This command will be executed on the account with the following details:
> Mode: Test
> Account Name: api-test
{
  "id": "cus_J5DadJ0IR5nS0d",
  "object": "customer",
  "deleted": true
}

リソース別の操作方法やオプションは、APIドキュメントで調べよう

操作できるリソースの数が膨大なため、本書では一例のみの紹介としています。

それぞれのリソースでのコマンド名や引数については、APIドキュメントを見ることをお勧めします。

$ stripe open api  

StripeのAPIドキュメントには、言語別のコードサンプルが表示されています。その中に[Stripe CLI]も含まれていますので、画像のように設定してやることで、Stripe CLIでどのようにコマンドを入力すれば良いかを調べることができます。

stripe fixturesコマンドで複数のAPI操作をまとめて実行する

「Customerを作成した後、請求の実行も行う」のように、複数のAPIを呼び出す必要があるオペレーションがStripeでは少なくありません。

そんな時にコマンドを何度も実行しなくても済むようにできるのが、stripe fixturesコマンドです。

このコマンドは、実行するAPIリクエスト内容を事前にJSONで定義して、その順番にAPIを呼び出すことができます。

カスタマー作成 -> 請求 -> 確定をまとめて行うJSONサンプル

これはstripe fixturesのサンプルとして紹介されているJSONです。

fixturesの中に配列で実行するAPIのパスやメソッド、パラメーターを定義していることがわかります。

{
    "_meta": {
      "template_version": 0
    },
    "fixtures": [
      {
        "name": "cust_bender",
        "path": "/v1/customers",
        "method": "post",
        "params": {
          "name": "Bender Bending Rodriguez",
          "email": "bender@planex.com",
          "source": "tok_visa",
          "address": {
            "line1": "1 Planet Express St",
            "city": "New New York"
          }
        }
      },
      {
        "name": "char_bender",
        "path": "/v1/charges",
        "method": "post",
        "params": {
          "customer": "${cust_bender:id}",
          "amount": 100,
          "currency": "usd",
          "capture": false
        }
      },
      {
        "name": "capt_bender",
        "path": "/v1/charges/${char_bender:id}/capture",
        "method": "post"
      }
    ]
  }

このJSONファイルを指定するようにコマンドを実行することで、複数の操作をまとめて実行することができます。

% stripe fixtures ./fixtures.json
Setting up fixture for: cust_bender
Setting up fixture for: char_bender
Setting up fixture for: capt_bender

Stripe Dashboardで確認すると、確かに複数のAPIが呼び出されていることが確認できます。

fixtureでレスポンスを使う場合は、name属性を利用する

APIのレスポンスをfixturesの中で利用したい場合、「利用したい値を返すfixtureのname」をキーとします。

先程のJSONでは、2つ目のfixtureが以下のように記述されています。

      {
        "name": "char_bender",
        "path": "/v1/charges",
        "method": "post",
        "params": {
          "customer": "${cust_bender:id}",
          "amount": 100,
          "currency": "usd",
          "capture": false
        }
      }

Chargeを実行したいCustomerのIDは1つ目のfixtureのレスポンスから取得する必要があります。

そのため、1つ目のfixtureのnameであるcust_benderに、customerオブジェクトのidをつなげた「${cust_bender:id}」がパラメータとして設定されています。

同様に3つ目のfixuterでも、2つ目のfixture名を使ってchargeのIDを取得しています。

      {
        "name": "capt_bender",
        "path": "/v1/charges/${char_bender:id}/capture",
        "method": "post"
      }

この他にも${.env:EMAIL|jane@stripe.com}のように書くことで、環境変数を利用しつつ、デフォルトの値も設定する方法などもあります。

https://stripe.com/docs/cli/fixtures

バッチ処理とfixtures

「得意なプログラミング言語でバッチ処理を実装・実行する」場合の方が早いケースもあるとは思います。が、この方法を知っていると、わざわざnpm init -y && npm install stripeのような環境準備をする必要などがなくなります。

「よくやるワークフローをfixture.jsonにして社内で共有する」などの使い方もあると思いますので、ぜひいろいろな使い方に挑戦してみてください。