条纹 - 由AJAX提交表单

时间:2018-04-02 15:18:55

标签: javascript php ajax stripe-payments stripe.js

我正在使用Stripe Elements创建付款并控制表单的外观。当提交时,我通过表单的操作得到了很好的工作。但是,现在我想尝试发送POST请求而不更改/加载页面。我认为最好通过AJAX完成。我试过这个但是我无法用JSON获得200响应。下面我已经包含了代码片段,对于我出错的地方的任何帮助将不胜感激。

JS

//snippet

const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
    event.preventDefault();
    const {token, error} = await stripe.createToken(card);
    if (error) {
        const errorElement = document.getElementById('card-errors');
        errorElement.textContent = error.message;
     } else {
        stripeTokenHandler(token);
    }
});

const stripeTokenHandler = (token) => {
const form = document.getElementById('payment-form');
const hiddenInput = document.createElement('input');
const submitButton = document.querySelector('.submit-form');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);

// form.submit();

//new AJAX code
const submitForm = (e) => {
    e.preventDefault();
    const request = new XMLHttpRequest();
    request.open('POST', e.target.action);
    if (e.target.status === 200) {
        console.log('successs:' + e.target.response)
    } else {
       console.log('fail')
    }
};
form.addEventListener('submit', submitForm);

FORM

<form action="<?= $page->url() ?>/charge" method="POST" id="payment-form">
   <input type="text" name="name" class="StripeElement StripeElement--empty" placeholder="First Name">
   <input type="email" name="email" class="StripeElement StripeElement--empty" placeholder="Email Address">
   <div id="card-element">
      <!-- A Stripe Element will be inserted here. -->
   </div>
       <!-- Used to display Element errors. -->
   <div id="card-errors" role="alert"></div>
   <button class="submit-form stripe-button">Pay <?= $symbol ?><?= $page->amount()->html() ?></button>
</form>

PHP

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

  \Stripe\Stripe::setApiKey(sk_test_xX5xxxxxxxxxxx);

  $POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);

  $name = $POST['name'];
  $email = $POST['email'];
  $token = $POST['stripeToken'];
  $currency = 'gbp';
  $amount = s::get('stripeAmount');
  $description = s::get('stripeDescription');

  $customer = \Stripe\Customer::create(array(
    'email' => $email,
    'source' => $token
  ));

  // Charge the user's card:
  $charge = \Stripe\Charge::create(array(
    "amount" => $amount,
    "currency" => $currency,
    "description" => $description,
    "customer" => $customer->id,
  ));

 // print_r($charge);

 $charge_json = $charge->__toJSON();
}

路线(路线内置于CMS

c::set('routes', array(
    array(
        'pattern' => 'products/(:any)/charge',
        'method' => 'POST',
        'action'  => function() {
            stripeCheckout();
        },
    )
));

==编辑==

网络请求的屏幕截图

enter image description here

0 个答案:

没有答案