简体   繁体   English

完全坚持 Stripe Checkout

[英]Completely stuck with Stripe Checkout

The Goal: There are a few buttons on the screen, like so –目标:屏幕上有几个按钮,就像这样——

[Product 1 – $20] [产品 1 – 20 美元]

[Product 2 – $35] [产品 2 – 35 美元]

and so on...等等...

Users can select as many products as they like.用户可以选择任意数量的产品。 In the JavaScript, I have a variable amount that increments by how much ever the product costs when the user selects it.在 JavaScript 中,我有一个可变amount ,当用户选择它时,它会随着产品成本的增加而增加。 So the flow is like this:所以流程是这样的:

User selects product 1 & 2 --> amount = 20 + 35 = 55用户选择产品 1 和 2 --> 数量 = 20 + 35 = 55

Then, the user can press the Pay with Card button to launch the Stripe Checkout modal.然后,用户可以按下 Pay with Card 按钮来启动 Stripe Checkout 模式。 Fill that out, pay, done.填写,付款,完成。

The Problem: Now, I'm using the custom button version of Checkout, so I can style the button my way and put this variable amount in. So, that implementation is pretty simple:问题:现在,我正在使用 Checkout 的自定义按钮版本,因此我可以按照自己的方式设置按钮样式并将此变量放入。因此,该实现非常简单:

       var handler = StripeCheckout.configure({
            key: 'pk_test_XXXXXX',
            image: 'assets/logo-stripe.png',
            locale: 'auto',
            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`
                $.ajax({
                    url: 'php/charge.php',
                    type: 'post',
                    data: {tokenid: token.id, email: token.email, amount: amount},
                    success: function(data) {
                        if (data == 'success') {
                            console.log("Card successfully charged!");
                        }
                        else if (data == 'failure') {
                            console.log("Card error");
                        } else {
                            console.log("Other error");
                        }
                    },
                    error: function(data) {
                        console.log("AJAX error!");
                        console.log(data);
                    }
                });
            }
        });

        $('#pay-button').on('click', function(e) {
            if (amount == 0) {
                $('#pay-button').addClass('animated shake'); // Animates the button and refuses to open the modal if user didn't select any products
                $('#pay-button').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', removeAnimation);
            } else {
                handler.open({
                    name: 'Company, Inc.',
                    description: "Description",
                    amount: amount // Here's the variable
                });
                e.preventDefault();
            }
        });

        // Close Checkout on page navigation
        $(window).on('popstate', function() {
            handler.close();
        });

This is the JavaScript logic.这就是 JavaScript 逻辑。 I left out the call to checkout.js, since that's not really of any consequence to this question.我省略了对 checkout.js 的调用,因为这对这个问题没有任何影响。

From a front end perspective, this is peachy.从前端的角度来看,这是桃子。 Now comes tokenization and actually charging the card.现在是标记化并实际为卡充电。 Here's where things start having issues.这就是事情开始出现问题的地方。 If you look at the token handling, I'm trying to POST email, amount, and token data to charge.php.如果您查看令牌处理,我正在尝试将电子邮件、金额和令牌数据发布到 charge.php。 Based on the fact that I don't get any errors from the console about this, I think that's working.基于我没有从控制台收到任何关于此的错误的事实,我认为这是有效的。

In charge.php, I have this: (updated Apr. 20: This is working code)在charge.php中,我有这个: (4月20日更新:这是工作代码)

<?php
  require_once('stripe-php/init.php');

  // Set secret key
  \Stripe\Stripe::setApiKey("sk_test_XXXXXXX");

  // Get the credit card details submitted by the form
  $token = $_POST['tokenid'];

  // Create the charge on Stripe's servers - this will charge the user's card
  try {
    $customer = \Stripe\Customer::create(array(
      'email' => $_POST['email'],
      'source'  => $token
    ));

    $charge = \Stripe\Charge::create(array(
      "amount" => $_POST['amount'],
      "currency" => "usd",
      "customer" => $customer->id
      ));

    echo "success";
  } catch(\Stripe\Error\Card $e) {
    // The card has been declined
    echo "failure";
  }

?>

Whenever I try to make a purchase, the log gives me "Success Error."每当我尝试购买时,日志都会显示“成功错误”。 I'm loosely following code presented here – How to create a stripe charge with a checkout token sent via AJAX to php .我大致遵循此处提供的代码 – 如何使用通过 AJAX 发送到 php 的结帐令牌创建条带费用 So, I don't know what Success Error is, but my guess is that the data was sent to charge.php fine, but the card wasn't charged.所以,我不知道成功错误是什么,但我的猜测是数据被发送到charge.php 很好,但卡没有被收费。 This is supported by the fact that my Stripe dashboard doesn't show any record of payment.我的 Stripe 仪表板不显示任何付款记录这一事实支持了这一点。

What I have tried:我尝试过的:

1) I thought the error might be my config.php. 1) 我认为错误可能是我的 config.php。 I'm not using Composer (because I have no idea what that is or how to even start using it), so instead I'm calling init.php from stripe-php.我没有使用 Composer(因为我不知道那是什么,也不知道如何开始使用它),所以我从 stripe-php 调用 init.php。 This is an acceptable alternative to Composer, according to Stripe's own documentation.根据 Stripe 自己的文档,这是 Composer 的可接受替代方案。

Here's the config.php: 这是 config.php:

 
 
 
 
  
  
  <?php require_once('php/stripe-php/init.php'); $stripe = array( secret_key => getenv('sk_test_XXXXXX'), publishable_key => getenv('pk_test_XXXXXX') ); \\Stripe\\Stripe::setApiKey($stripe['secret_key']); ?>
 
 
 

No longer using config.php, all combined into charge.php不再使用config.php,全部合并成charge.php

2) In my POST call, I pass a tokenid but in my charge.php, I use stripeToken. 2) 在我的POST 调用中,我传递了一个tokenid,但在我的charge.php 中,我使用了stripeToken。 This probably happened because I tried using a Stack Overflow answer and the Stripe docs to craft a complete solution.这可能是因为我尝试使用 Stack Overflow 答案和 Stripe 文档来制定完整的解决方案。 I thought it was odd that stripeToken isn't being sent from my front-end.我认为没有从我的前端发送 stripeToken 很奇怪。 So, I tried using tokenid in my charge.php (replace stripeToken with tokenid . Changing to tokenid didn't work and presented safety concerns (I'd rather stick to the compliant stripeToken, but I don't know how to implement it).所以,我想在我的charge.php使用tokenid(更换stripeTokentokenid 。改为tokenid没有工作,并提出安全问题(我宁愿坚持到顺应stripeToken,但我不知道如何实现它) .

3) I worried about sending the amount variable to charge.php. 3)我担心将金额变量发送到charge.php。 I didn't want users to change it in their console, but if I don't send it, I don't know how to have variable pricing.我不希望用户在他们的控制台中更改它,但是如果我不发送它,我不知道如何进行可变定价。 I need variable pricing, since users are selecting multiple products with different prices (see: The Goal).我需要可变定价,因为用户正在选择具有不同价格的多种产品(请参阅:目标)。 So, that's another conundrum for me.所以,这对我来说是另一个难题。

It might be worth noting that I had to test this in production to even get Success Error.可能值得注意的是,我必须在生产中对此进行测试才能获得成功错误。 In localhost, I get a 500 Internal Server Error.在本地主机中,我收到 500 内部服务器错误。 Don't know why, but guessing it has to do with the lack of PHP environment or file structure.不知道为什么,但猜测与缺乏PHP环境或文件结构有关。

Any help would be greatly appreciated!任何帮助将不胜感激! Thank you.谢谢你。

Your token callback functions checks if the string "success" is returned:您的token回调函数检查是否返回字符串"success"

                success: function(data) {
                    if (data == 'success') {

But your charge.php file does not return "success" , it returns但是你的charge.php文件没有返回"success" ,它返回

echo '<h1>Successfully charged [amount]!</h1>';

or或者

echo '<h1>Charge failed</h1>';

You should modify your charge.php file to return the data expected by your frontend code.您应该修改您的charge.php文件以返回您的前端代码预期的数据。 Since it is called via AJAX, its output will not be displayed by the browser.由于它是通过 AJAX 调用的,因此浏览器不会显示其输出。

A few other remarks:其他几点说明:

  • you should move the customer creation call ( \\Stripe\\Customer::create(...) ) inside the try/catch clause.您应该在try/catch子句中移动客户创建调用( \\Stripe\\Customer::create(...) )。 When creating a customer with a card token, Stripe will check that the card is valid, and return a card error if that's not the case使用卡令牌创建客户时,Stripe 将检查卡是否有效,如果不是,则返回卡错误

  • outside of scenarios where the customer should explicitly choose the amount themselves (eg taking customer-specified donations), you should not rely on an amount that's sent by the customer's browser, as it is very easy to change it.除了客户应该自己明确选择金额(例如接受客户指定的捐赠)的情况之外,您不应依赖客户浏览器发送的金额,因为更改它非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM