Rails Stripe 서브스크립션 결제 구현 초기 설정을 하여 API를 사용할 수 있는 상태로 한다

개요



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 [email protected] if you have any questions.

당연하지만 오류가 발생합니다.

API를 사용하는 데 필요한 계정 정보



필요한 정보는
  • Publishable key
  • Secret key

  • 같은 두 가지 키입니다.

    Stripe 관리 화면의 다음 부분에서 얻을 수 있습니다. (여러가지 흰색 빼고 있습니다)


    개발 단계의 경우 Test용 key를 사용하도록 합시다.

    설정 설명



    stripe-ruby의 README에는 이렇게 적혀 있습니다.
    htps : // 기주 b. 코 m / st ripe / st ripe-by # 토끼
    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_..."
    

    라고 쓰는 것은 효율이 좋다고는 말할 수 없고, 보안적으로도 아웃입니다.

    그래서 이번에는 다음 두 파일에 키 정보를 기술합니다.
  • 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인 경우는 보이는 방법이 다를지도...)

    참고


  • Stripe API Reference
    htps : // st 리페. 코 m / cs / 아피
  • 일본 정식 릴리스한 Stripe를 사용해 서브스크립션형 결제 시스템을 구현한다
    ぃ tp // m / dy / ms / 7617 62b2 a 5402 에 bd0fb
  • Stripe가 Rails에서 움직이는 메커니즘
    ぃ tp // m / 100010 / ms / c09fb08 ~ d555b32 a 2652
  • Rails 5.1의 encrypted secrets의 운영에 대해 생각한다 ぃ tp // 코 m / 키쿠 어떻게든 / ms / d22cf51071b93ba 5b62
  • 좋은 웹페이지 즐겨찾기