【问题标题】:How to create a stripe charge with a checkout token sent via AJAX to php如何使用通过 AJAX 发送到 php 的结帐令牌创建条带收费
【发布时间】: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


    【解决方案1】:

    因此,经过 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
        }
      });
    

    请注意,一个主要的变化是 ajax 方法的数据属性。控制台记录令牌对象会显示整个 JSON 令牌对象,您可以使用它来提取 ID(您的服务器需要发送到条带以收取付款的内容)以及电子邮件(用于您的日志记录目的)。由于我的捐款金额是可变的,因此我也将其作为第三个关键。

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

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

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

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

    【讨论】:

    • 是否需要 ajax 才能使自定义按钮工作?也许你可以帮我用我的按钮,我无法用它来为卡充电。
    • 不,你没有。您可以随时提交表单。我选择了 AJAX,所以我不必添加额外的标记(比如对表单进行编码)。请注意,stripe 的“自定义按钮结帐”功能不收取任何费用,它只是创建一个令牌。您用于在 php 中创建费用的 ID。
    • 你不知道这对我有多大帮助。非常感谢!
    • 在这方面的出色工作。在这个上挣扎了 2 个小时!
    猜你喜欢
    • 2016-01-10
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2016-04-07
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多