如何使用通过AJAX发送到php的结帐令牌创建数据条费用 [英] How to create a stripe charge with a checkout token sent via AJAX to php

查看:89
本文介绍了如何使用通过AJAX发送到php的结帐令牌创建数据条费用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试将Stripe的新结帐功能与自定义按钮一起使用,通过AJAX POST将令牌发送到php文件,然后执行费用.不幸的是,我在从POST变量中检索令牌时遇到了一些麻烦.我希望这里的人能够告诉我我过于复杂的事情,以及是否有更简单的方法可以做到这一点.

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.

在客户端,我有5个带有不同可能捐赠"的按钮.到目前为止,这是为此编写的js(不包括html):

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):

$(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();
  });
});

这是我的php,正在处理AJAX POST调用:

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

<?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发送令牌时,令牌便消失了.

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.

每个人都在说Stripe非常易于实现,所以我真的感觉到我在这里遗漏了一些东西.有人可以阐明一些想法吗?

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?

谢谢!

推荐答案

因此,在小睡了10个小时之后,头脑更加清晰,我决定以一种略有不同的方式来解决这个问题.这适用于遇到我同样问题的其他任何人,希望它可以作为stripe/ajax/php教程工作得很好.原来我一直在考虑POST数据全错了.即使使用AJAX,您也需要一个键和值对来发送任何类型的POST数据.我已经为此编写了js的这一部分:

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:

  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方法的data属性.控制台记录令牌对象会显示整个JSON令牌对象,您可以用来提取ID(您的服务器需要发送该数据以分条以收取费用)以及电子邮件(用于记录目的).由于我的捐赠金额是可变的,因此我也将其作为第三个密钥.

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.

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

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

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

然后,其他所有内容都应该是自我解释的(跟条纹php教程几乎完全相同的示例).

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

无论如何,希望这对外面的人有所帮助.祝你好运!

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

这篇关于如何使用通过AJAX发送到php的结帐令牌创建数据条费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆