我正在构建一个使用Stripe的Django应用程序,让用户互相付款。卖家需要将他们的帐户连接到Stripe,这样我就可以保存他们的访问权限并将令牌刷新到数据库中。买家也可以在付款期间向服务捐款。
如果我试图向卖家收费,我会收到一个错误,我真的不明白:
"无效的令牌ID:tok_355k8o2rGvbwWLbLbNKPAcOk。用于创建此令牌的可发布密钥来自其他帐户。
卖家的访问令牌有问题,但我无法弄清楚它是什么。我已经仔细检查了我的秘密和可发布的密钥,他们没事。
以下是我在付款时使用的一段代码。
使用条纹连接卖家:
def callback(request):
code = request.GET.get('code')
profile = UserProfile.objects.get(user=request.user)
r = requests.post('https://connect.stripe.com/oauth/token', params={
'client_secret': settings.STRIPE_SECRET_KEY,
'code': code,
'grant_type': 'authorization_code'
}).json()
try:
profile.access_token = r['access_token']
profile.refresh_token = r['refresh_token']
profile.save()
messages.success(request, "Your account was successfully connected to Stripe.")
except KeyError:
messages.error(request, "Unable to connect your account to Stripe.")
return redirect('home')
收费:
def charge(request, item_id):
stripe.api_key = settings.STRIPE_SECRET_KEY
try:
item = Item.objects.get(pk=item_id)
profile = UserProfile.objects.get(user=item.owner)
access_token = profile.access_token
except Item.DoesNotExist:
raise Http404
if request.method == 'POST':
form = PaymentForm(request.POST)
if form.is_valid():
try:
charge = stripe.Charge.create(
# Multiply by 100 to get value in cents
amount=form.cleaned_data['amount'] * 100,
application_fee=form.cleaned_data['donation'] * 100,
currency='gbp',
card=form.cleaned_data['stripeToken'],
description="{} by {}".format(item.title, item.author),
api_key=access_token, # <-- This is the line where the error occurs
)
messages.success(request, "The payment was successful.")
except stripe.CardError, e:
messages.error(request, "The payment could not be completed.")
你知道如何纠正这个问题吗?非常感谢。
答案 0 :(得分:6)
访问令牌附带了自己的可发布密钥,在为该用户创建卡令牌时,您需要在表单上使用该密钥。您需要存储该可发布的密钥:
profile.access_token = r['access_token']
profile.refresh_token = r['refresh_token']
profile.publishable_key = r['stripe_publishable_key']
profile.save()