LoginSignup
12
3

More than 5 years have passed since last update.

Stripeを使って開発をするときにmockサーバーを利用する

Last updated at Posted at 2017-11-25

やりたいこと

決済サービスの一つであるStripeを利用するサービスを開発する際に、実際のサービスAPIを利用せず開発を進められるようにします。

stripe-mockのインストール

実際のStripe APIを模倣するmockサーバーサービスがStripeによって提供されているので、これをインストールして利用できるようにします。

for macOS

homebrew を使ったインストールとサービスの有効化について紹介します。

$ brew install stripe/stripe-mock/stripe-mock
$ brew services start stripe/stripe-mock/stripe-mock

デフォルトではhttp://localhost:12111でmockサーバーが動作するようです。

mockサーバーを利用するように設定を変更する

ここでは、railsを利用する場合の設定方法について紹介します。

サービスAPIエンドポイントの設定はStripe.api_baseにあるので、development環境でrailsが動作する場合には、mockサーバーを参照するように設定を追加します。

# config/environments/development.rb

Rails.application.configure do
  # other something...
  Stripe.api_base = 'http://localhost:12111'
end

確認

rails consoleを使って動作を確認してみます。

$ bin/rails console

> Stripe.api_base
=> "http://localhost:12111"

> Stripe::Charge.list
=> 
<Stripe::ListObject:0x3fe3bb271990> JSON: {
  "data": [{
    "id":"ch_1B3q3s2eZvKYlo2CLdghKZFC",
    "amount":2000,
    "amount_refunded":0,
    "balance_transaction":"txn_1B3kCO2eZvKYlo2CQHzTvqYJ",
    "captured":false,
    "created":1234567890,
    "currency":"usd",
    "description":"My First Test Charge (created for API docs)",
    "fraud_details":{},
    "livemode":false,
    "metadata":{},
    "object":"charge",
    "paid":false,
    "refunded":false,
    ...,
  ],
  "has_more": false,
  "object": "list",
  "url": "/v1/charges"
}

mockサーバーにあらかじめ登録されていた購入データが表示されるのが確認できます。

できないこと

  • APIからのレスポンスはあらかじめ規定されたものが返されるため、データの永続化を含む検証は難しいみたいです。

参考

12
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
3