LoginSignup
36
29

More than 1 year has passed since last update.

Rails Stripe サブスクリプション決済実装 初期設定をしてAPIを使える状態にする

Last updated at Posted at 2017-09-06

概要

Stripeでのサブスクリプション決済実装をRailsで行う場合、
公式で提供されているgemを使用することになると思います。

実装に当たって
Stripe::Plan.create()
Stripe::Customer.create()
のようなAPIメソッドを使用していくことになるのですが、
今回はAPIを使える状態にするまでの初期設定についてまとめました。

事前準備

いつもの

Gemfileに
gem 'stripe'
を追加して
bundle install
しておきましょう。

確認

rails cでStripeメソッドが使えるか試しておきましょう。
Stripe::Customer.listは登録されている顧客の情報リストを取得するメソッドです。

irb(main):001:0> Stripe::Customer.list
Stripe::AuthenticationError: No API key provided. Set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.

当たり前ですが、エラーとなります。

APIを使用するのに必要なアカウント情報

必要な情報は

  • Publishable key
  • Secret key

といった2つのkeyです。

Stripe管理画面の以下の箇所より取得できます。(色々白抜きしてます)
スクリーンショット 2017-09-06 17.30.17.png

開発フェーズの場合、Test用のkeyを使用するようにしましょう。

設定記述

stripe-rubyのREADMEにはこう書かれています。
https://github.com/stripe/stripe-ruby#usage

require "stripe"
Stripe.api_key = "sk_test_..."

# list charges
Stripe::Charge.list()

# retrieve single charge
Stripe::Charge.retrieve(
  "ch_18atAXCdGbJFKhCuBAa4532Z",
)

もちろんこれでもAPIは使用できます。
しかし、必要な箇所で毎回

require "stripe"
Stripe.api_key = "sk_test_..."

と書くのは効率がいいとは言えませんし、セキュリティ的にもアウトです。

なので、今回は以下の2つのファイルにkey情報を記述します。

  • config/secrets.yml
  • config/initializers/stripe.rb

secrets.ymlについては以下の記事を参照してください。
Rails 5.1のencrypted secretsの運用について考える

config/secrets.yml

stripe_publishable_keyとstripe_secret_keyを定義します。
環境に合わせてdevelopment、test、productionは切り替えてください。

config/secrets.yml
development:
  # stripe
  stripe_publishable_key: pk_test_********************
  stripe_secret_key: sk_test_********************

config/initializers/stripe.rb

デプロイ時にStripeの定義を読み込みます。

config/initializers/stripe.rb
Rails.configuration.stripe = {
  publishable_key: Rails.application.secrets.stripe_publishable_key,
  secret_key: Rails.application.secrets.stripe_secret_key
}

Stripe.api_key = Rails.application.secrets.stripe_secret_key

準備完了

以上でAPIを使用する準備は完了となります。
簡単ですね!!

確認

先ほどと同じメソッドを使って確認します。
(サーバー再起動してくださいね)

irb(main):001:0> Stripe::Customer.list
=> #<Stripe::ListObject:*****> JSON: {
  "object": "list",
  "data": [....],
  "has_more": true,
  "url": "/v1/customers"
}

正常なレスポンスが返ってきました。
(Customerがemptyの場合は見え方が違うかも...)

参考

36
29
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
36
29