我使用Stripe为我的django网站接受一次性付款。以下代码工作正常,charge
成功:
def pay(request):
# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_exhH8mdKfkXkaxzvtVphJOBZ"
# Token is created using Checkout or Elements!
# Get the payment token ID submitted by the form:
if request.POST.get('stripeToken'):
print(request.POST)
token = request.POST.get('stripeToken')
charge = stripe.Charge.create(
amount=999,
currency='usd',
description='Boosted Post',
source=token,
)
print('Charge:', charge)
return HttpResponseRedirect('/')
else:
print('NO')
context = {
'amount': 999,
}
return render(request, 'advertising/pay.html', context)
但是,如果我在此视图中添加上下文,则它无法正常工作(if request.POST.get('stripeToken')
不会触发):
def post_ad(request):
boost_form = AdvertisePostForm(request.POST or None, request.FILES or None)
if boost_form.is_valid():
instance = boost_form.save(commit=False)
instance.total_price = ad_price(instance.position, instance.duration)
instance.ad = True
instance.save()
context = {
'hash': instance.hash,
}
return pay(request, context)
else:
pass
context = {
'boost_form': boost_form
}
return render(request, 'advertising/post_ad.html', context)
def pay(request, context):
ad = get_object_or_404(AdvertisePost, hash=context['hash'])
amount = ad.total_price * 100
# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_exhH8mdKfkXkaxzvtVphJOBZ"
# Token is created using Checkout or Elements!
# Get the payment token ID submitted by the form:
if request.POST.get('stripeToken'):
print(request.POST)
token = request.POST.get('stripeToken')
charge = stripe.Charge.create(
amount=amount,
currency='usd',
description='Boosted Post',
source=token,
)
print('Charge:', charge)
return HttpResponseRedirect('/')
else:
print(request.POST)
print('NO')
context = {
'amount': amount,
'ad': ad
}
return render(request, 'advertising/pay.html', context)
知道为什么会这样,以及如何解决它?
如果你好奇,这是条纹形式:
<form action="" method="POST">{% csrf_token %}
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_8rSK77eA02iovefCmQCeV9su"
data-amount="{{ amount }}"
data-name="My name"
data-description="Example charge"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-currency="aud">
</script>
</form>