【发布时间】:2014-04-22 02:38:26
【问题描述】:
我正在尝试通过自定义按钮使用 Stripe 的新结帐功能,通过 AJAX POST 将令牌发送到 php 文件,然后该文件将执行收费。不幸的是,我在从 POST 变量中检索令牌时遇到了一些麻烦。我希望这里的某个人能够告诉我我过于复杂,以及是否有更简单的方法来做到这一点。
在客户端,我有 5 个按钮,其中包含不同的可能“捐赠”。到目前为止,这是为此编写的 js(不包括 html):
$(function() {
var donationAmt = '';
var handler = StripeCheckout.configure({
key: 'pk_test_3plF76arhkygGMgwCEerThpa',
image: '/square-image.png',
token: function(token, args) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
console.log(token)
var chargeData = {
donationAmt: donationAmt,
token: token
}
$.ajax({
url: '/link/to/php/stripeDonate.php',
type: 'post',
data: {chargeData: chargeData},
success: function(data) {
if (data == 'success') {
console.log("Card successfully charged!")
}
else {
console.log("Success Error!")
}
},
error: function(data) {
console.log("Ajax Error!");
console.log(data);
}
}); // end ajax call
}
});
$('.donate-button').bind('click', function(e) {
donationAmt = $(this).html().substring(1) + '00';
donationAmt = parseInt(donationAmt); // Grabs the donation amount in the html of the button and store it in a variable
// Open Checkout with further options
handler.open({
name: 'Company Name',
description: 'A donation',
amount: donationAmt
});
e.preventDefault();
});
});
这是我正在处理 AJAX POST 调用的 php:
<?php
require_once('Stripe.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account
Stripe::setApiKey("sk_test_APIKEYREDACTED");
// Get the credit card details submitted by the form
$token = json_decode($_POST['chargeData']);
$tokenid = $token['id'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
"amount" => 2000, // amount in cents, again
"currency" => "usd",
"card" => $tokenid,
"description" => "payinguser@example.com")
);
echo 'success';
} catch(Stripe_CardError $e) {
// The card has been declined
echo $tokenid;
}
?>
如 php 错误日志中所述,此代码的直接结果是无法“读取”令牌的 POST 变量。令牌创建得很好(我看到它记录在控制台上)但是当我通过 AJAX 发送它时它消失了。
每个人都在说 Stripe 非常容易实现,所以我真的觉得我在这里遗漏了一些东西。有人能解释一下吗?
谢谢!
【问题讨论】:
标签: javascript php jquery ajax stripe-payments