javascript 如何使用通过 AJAX 发送到 php 的结帐令牌创建条带费用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22445078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:10:30  来源:igfitidea点击:

How to create a stripe charge with a checkout token sent via AJAX to php

javascriptphpjqueryajaxstripe-payments

提问by jdchizzle

I'm trying to use Stripe's new checkout feature with a custom button, send the token via AJAX POST to a php file which will then execute the charge. Unfortunately, I'm having some trouble retrieving the token from the POST variable. I'm hoping someone here might be able to tell me what I'm overcomplicating and if there's a simpler way to do this.

我正在尝试使用带有自定义按钮的 Stripe 的新结帐功能,通过 AJAX POST 将令牌发送到一个 php 文件,然后该文件将执行收费。不幸的是,我在从 POST 变量中检索令牌时遇到了一些问题。我希望这里的某个人能够告诉我什么我过于复杂,以及是否有更简单的方法来做到这一点。

On the client-side, I've got 5 buttons with different possible "donations". Here's the js written up for that so far (doesn't include the html):

在客户端,我有 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();
  });
});

And this is my php that is processing the AJAX POST call:

这是我正在处理 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" => "[email protected]")
);
echo 'success';
} catch(Stripe_CardError $e) {
  // The card has been declined
    echo $tokenid;
}

?>

The direct result of this code as noted in the php error logs is that the POST variable for the token cannot be "read". The token is being created alright (I'm seeing it logged on the console) but it disappears when I send it via AJAX.

如 php 错误日志中所述,此代码的直接结果是无法“读取”令牌的 POST 变量。令牌正在创建中(我看到它记录在控制台上)但是当我通过 AJAX 发送它时它消失了。

Everyone has been saying that Stripe is super easy to implement so I'm really feeling that i'm missing something here. Would someone be able to shed some light?

每个人都说 Stripe 非常容易实现,所以我真的觉得我在这里错过了一些东西。有人能解释一下吗?

Thanks!

谢谢!

回答by jdchizzle

So after a 10 hour nap and a much clearer head, I've decided to tackle this in a slightly different way. This is for anyone else who stumbles into the same problems I am and will hopefully work really well as a stripe/ajax/php tutorial. Turns out I've been thinking about POST data all wrong. Even with AJAX, you'll need a key and value pair to send any kind of POST data. I've recoded this part of my js for this:

因此,经过 10 个小时的小睡和更清晰的头脑后,我决定以稍微不同的方式解决这个问题。这适用于遇到与我相同的问题的任何其他人,并且希望作为 stripe/ajax/php 教程能够很好地工作。结果我一直在想 POST 数据全错了。即使使用 AJAX,您也需要一个键值对来发送任何类型的 POST 数据。我已经为此重新编码了我的 js 的这一部分:

  var handler = StripeCheckout.configure({
    key: 'PUBLISHABLEKEY',
    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)
      $.ajax({
          url: 'link/to/php/stripeDonate.php',
          type: 'post',
          data: {tokenid: token.id, email: token.email, donationAmt: donationAmt},
          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
    }
  });

Note that the one primary change is the data attribute of the ajax method. Console logging the token object reveals the entire JSON token object which you can use to extract the ID (what your server needs to send to stripe to charge a payment for) as well as the email (for your logging purposes). Since I have a variable donation amount, I've included that as a third key as well.

请注意,一个主要更改是 ajax 方法的 data 属性。控制台记录令牌对象会显示整个 JSON 令牌对象,您可以使用它来提取 ID(您的服务器需要发送到 Stripe 以收取费用)以及电子邮件(用于您的记录目的)。由于我有可变的捐赠金额,因此我也将其作为第三个键。

Now in your php, in order to obtain these POST variables and put them into php variables, you grab them using their respective keys:

现在在您的 php 中,为了获取这些 POST 变量并将它们放入 php 变量中,您可以使用它们各自的键来获取它们:

$tokenid = $_POST['tokenid'];
$donation = $_POST['donationAmt'];
$email = $_POST['email'];

And then everything else should be self explanatory (following pretty much the exact same example as the stripe php tutorial).

然后其他一切都应该是不言自明的(遵循与条纹 php 教程几乎完全相同的示例)。

Anyway, hope this helps someone out there. Good luck!

无论如何,希望这可以帮助那里的人。祝你好运!