【问题标题】:PHP/Javascript - Add payment method with Stripe APIPHP/Javascript - 使用 Stripe API 添加支付方式
【发布时间】:2019-04-04 02:07:44
【问题描述】:

我使用的是 Wordpress,但我使用的是“开箱即用”的解决方案,因为我的客户特别要求它。我有这个创建表单的 Javascript,当表单被提交时,它会创建一个带有令牌的 cookie,所以我可以从 PHP 中检索它,它看起来像这样:

<form action="/wp-content/themes/betheme/includes/add_payment_method.php" method="post" id="add-card-form">
      <div class="form-row">
        <label for="card-element">
          Credit or debit card
        </label>

        <div id="card-element"></div>

        <!-- Used to display Element errors. -->
        <div id="card-errors" role="alert"></div>
      </div>

      <button>Add payment method</button>
    </form>

    <script src="https://js.stripe.com/v3/"></script>

    <script>
        var style = {
          base: {
            color: '#ffffff',
            fontSize: '14px',
            fontSmoothing: 'antialiased',
            '::placeholder': {
              color: '#ccc',
            },
            iconColor: "#fff"
          },
          invalid: {
            color: '#e5424d',
            ':focus': {
              color: '#303238',
            },
          },
        };
        var stripe = Stripe('xxxxxxxxxxxxxxxxxxxxxxx');
        var elements = stripe.elements();
        var cardElement = elements.create('card', {style: style, hidePostalCode: true});

        window.mobilecheck = function() {
          var check = false;
          (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
          return check;
        };

        if(mobilecheck()) {
            cardElement.mount('#Content > div > div > div > div.section.mcb-section.hide-desktop > div > div > div > div > div > div > div > form > div.form-row >div#card-element');
        }
        else {
            cardElement.mount('#Content > div > div > div > div.section.mcb-section.hide-tablet.hide-mobile > div > div > div > div > div > div > div > form > div.form-row > div#card-element');
        }

        cardElement.addEventListener('change', function(event) {
          var displayError = document.getElementById('card-errors');
          if (event.error) {
            displayError.textContent = event.error.message;
          } else {
            displayError.textContent = '';
          }
        });

        // Create a token or display an error when the form is submitted.
        var form = document.getElementById('add-card-form');
        form.addEventListener('submit', function(event) {
          event.preventDefault();

          stripe.createToken(cardElement).then(function(result) {
            if (result.error) {
              // Inform the customer that there was an error.
              var errorElement = document.getElementById('card-errors');
              errorElement.textContent = result.error.message;
            } else {
              // Send the token to your server.
              stripeTokenHandler(result.token);
            }
          });
        });

        function createCookie(name, value, days) {
          var expires;
          if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
          } else {
           expires = "";
          }
          document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
        }

        function stripeTokenHandler(token) {
            createCookie("stripe_token", token, 1);

            var form = document.getElementById('add-card-form');
            form.submit();
        }
</script>

当表单提交时,它在add_payment_method.php中执行这个PHP:

<?php
    require_once("../../../../wp-load.php");
    submit_stripe_payment_method($_COOKIE['stripe_token']);
?>

在我的主题的functions.php 文件中,我有:

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

....

function submit_stripe_payment_method($token) {
    print_r($token);

    $current_user_id = get_current_user_id();
    echo 'Your User ID is: ' .$current_user_id;

    $customer_id = get_user_meta( $current_user_id, '_stripe_customer_id', true );
    echo "CUSTOMER_ID: ".(string)$customer_id;

    \Stripe\Stripe::setApiKey("xxxxxxxxxxxxxxxxxxxxxxx");

    echo "MADE IT HERE";

    $customer = \Stripe\Customer::retrieve((string)$customer_id);

    echo "CUSTOMER: ".$customer;

    $customer_card = $customer->sources->create(["source" => $token]);
    echo "<pre>";
    var_dump($customer_card);
    echo "</pre>";
}

上面的输出是:

[object Object]Your User ID is: 1CUSTOMER_ID: cus_DsoF18uw1dR0ujMADE IT HERE

如您所见,它只能达到“MADE IT HERE”echo

我已经在 Stripe Web 控制台中验证了我使用的 $customer_id 是正确的,并且我没有任何错误,无论是 PHP 还是其他错误。我唯一能想到的是我使用了错误的令牌,但它看起来很简单。如您所见,$token 打印为 [Object object],无论我如何尝试记录它,它都会执行此操作,因此我无法确切看到它是什么,但这是有道理的,因为它包含使用的敏感信息验证信用卡...也许它永远不会到达那一点,因为我从来没有看到echo "CUSTOMER: ".$customer; 声明,所以它可能会挂断:

$customer = \Stripe\Customer::retrieve((string)$customer_id);

另外,我在没有(string) 的情况下尝试了上述方法,但得到了相同的结果。

所以在这一切之后,我检查了 Stripe 控制台,并没有添加任何卡。

更新

显然我使用的API版本不是最新版本,我可以升级,我只是想知道在我这样做之前是否有人认为这是一个可能的解决方案。因为它可能会改变条带在整个站点中的工作方式(使用插件)。我正在使用2018-02-28,我可以升级到2018-09-24 。我也在localhost 环境中进行测试,所以我不是https,但我认为这对测试并不重要。

更新

我意识到我没有将localhost 设置的端点添加到stripe 控制台管理区域。为此,我必须使用 ngrok(如果您使用的是 localhost,则按照 Stripe 的建议)。我在端口8888 上使用localhost,所以我做了./ngrok http 8888,然后再次尝试,但没有成功。它确实在 Wordpress 中说端点将 enable you to receive notifications on the charge statuses. 所以也许它与添加付款方式无关。我将http 网址用于ngrok 而不是https 网址。

更新

我手动安装了stripe-php,所以我尝试使用composer,但没有帮助,结果相同。

更新

我将密钥更改为secret key,这使我可以检索$customer,但我没有看到$customer_card 的任何输出,当我查看仪表板时,没有创建任何卡。

更新

我检查了Stripe 仪表板,当我尝试创建源时收到错误消息:

{
  "error": {
    "code": "resource_missing",
    "doc_url": "https://stripe.com/docs/error-codes/resource-missing",
    "message": "No such token: [object Object]",
    "param": "source",
    "type": "invalid_request_error"
  }
}

我对令牌做错了什么?

更新

token问题的解决方案:在测试模式下,token只是一个字符串,与你正在使用的测试信用卡号对应,我需要"tok_visa"4242424242424242https://stripe.com/docs/testing

【问题讨论】:

  • 你应该尝试print_r($customer); die;而不是echo $customer;

标签: javascript php wordpress woocommerce stripe-payments


【解决方案1】:

问题可能是 排队

\Stripe\Stripe::setApiKey("xxxxxxxxxxxxxxxxxxxxxxx");

您使用的Publishable keypk_xxx 开头,而您应该在您的帐户中使用Secret Key sk_xxxx

你可以从 Stripe Dashboard 看到错误

https://dashboard.stripe.com/test/logs?method%5B%5D=get&method%5B%5D=post&method%5B%5D=delete&direction%5B%5D=connect_in&direction%5B%5D=self

登录后。

如果有帮助请告诉我

编辑

我还需要使用测试令牌,它只是一个字符串,与您正在使用的测试信用卡号相对应。 https://stripe.com/docs/testing。请参阅Tokens 标签。

【讨论】:

  • 谢谢,这行得通,我现在可以检索客户,但是没有添加以令牌作为“来源”的卡,我将使用输出更新我的问题。如果您有任何想法,请告诉我,谢谢
【解决方案2】:

您不能静态调用 Stripe\PaymentMethod::attach()。您必须先获取 PaymentMethod,然后将其附加到客户。代码应该是:

$pm = \Stripe\PaymentMethod::retrieve('pm_123'); $pm->attach(['customer' => 'cus_123']);

我会努力更新文档以避免这种混乱!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 2022-08-17
    • 2019-04-06
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2020-10-13
    • 2018-09-01
    相关资源
    最近更新 更多