Stripe API参考说明了authentication:
他们给出的例子如下:
require "stripe"
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
sk_test_BQokikJOvBiI2HlWgH4olfQ2
密钥可在Stripe网页的帐户设置中找到 . 我知道这是我的应用程序与Stripe交谈的秘密api密钥 .
但后来我在getting started with Stripe Connect上阅读了这个文档:
When using our official API libraries, we recommend that you pass in the
access_token with every request, instead of setting the API key globally.
This is because the access_token used in any API request depends on the user
you're charging on behalf of.
他们给出的例子是:
# Not recommended: setting global API key state
Stripe.api_key = ACCESS_TOKEN
Stripe::Customer.create(
:description => "example@stripe.com"
)
# Recommended: sending API key with every request
Stripe::Customer.create(
{:description => "example@stripe.com"},
ACCESS_TOKEN # user's access token from the Stripe Connect flow
)
此处,在用户通过Stripe Connect连接到应用程序后,访问令牌将返回到应用程序 . 访问令牌可用于代表该用户执行操作,例如为其卡充电 .
因此,他们会在每个请求中传递API密钥,但为什么用户的访问令牌是api密钥?我从第一篇文档中想到api密钥应该是我的应用程序的秘密api密钥?相反,他们正在设置用户的访问令牌 . 如果我设置用户的访问令牌而不是我自己的密钥,Stripe将如何识别我的应用程序?
然后,我阅读了他们关于将Stripe Checkout与Sinatra集成的示例 . 他们提供的代码示例是:
require 'sinatra'
require 'stripe'
set :publishable_key, ENV['PUBLISHABLE_KEY']
set :secret_key, ENV['SECRET_KEY']
Stripe.api_key = settings.secret_key
....
get '/' do
erb :index
end
post '/charge' do
# Amount in cents
@amount = 500
customer = Stripe::Customer.create(
:email => 'customer@example.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:amount => @amount,
:description => 'Sinatra Charge',
:currency => 'usd',
:customer => customer.id
)
erb :charge
end
因此,在这种情况下,他们将API密钥设置为应用程序的密钥 . 它们也不会在请求中传递任何访问令牌 . 所以我有点困惑为什么访问令牌将被设置为先前文档中的秘密API密钥,或者为什么我应该将它与每个请求一起传递,当他们所有的示例文档甚至都没有这样做时 .
1 回答
要理解这一点,您首先应该知道Stripe API可用于构建为两种受众提供服务的应用程序:
接受最终用户作为商家付款(正常用例)和
为拥有自己的Stripe帐户的商家提供附加服务(例如,一项服务可帮助我配置要在不同Stripe事件上发送的电子邮件)
因此,可以通过两种方式授权所有API endpoints :
您可以直接从“帐户设置”获取的API密钥方式 . 这标识了您的Stripe帐户
通过Stripe Connect访问令牌的方式 . 这标识了已连接商家的Stripe帐户 .
Stripe Connect文档告诉您的是,假设您正在构建一个服务于上述用例#2的应用程序,那么您必须记住使用正确的访问令牌授权每个API调用,而不是拥有全局API密钥(顺便说一下,对于用例#1完全可以接受,因为您可能会错误地更改错误的帐户 .
因此,如果用例#1是您想要做的,那么您根本不必担心Stripe Connect .