Home » Php » php – Stripe submitting a custom amount and token using jquery ajax

php – Stripe submitting a custom amount and token using jquery ajax

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to charge my users in a PAYG(pay as you go) model and everytime i want to charge a user, the amount is different from the next person. I therefore need to submit a custom amount to my charging php script in the backend.

here is my html and javascript

<form method="post" action="charge.php">
<div class="group">
<label>
<span>Name</span>
<input name="cardholder-name" class="field" name="name" placeholder="Name on card" required />
</label>
<label>
<span>Amount</span>
<input class="field" name="amount" placeholder="amount" type="number" required />
</label>
</div>
<div class="group">
<label>
<span>Card</span>
<div id="card-element" class="field"></div>
</label>
</div>
<button type="submit">Pay</button>
<div class="outcome">
<div class="error"></div>
<div class="success">
Success! Your Stripe token is <span class="token"></span>
</div>
</div>
</form>
<script src="https://js.stripe.com/v3/"></script>
<script>
        var stripe = Stripe('pk_test_');
        var elements = stripe.elements();

        var card = elements.create('card', {
          style: {
            base: {
              iconColor: '#666EE8',
              color: '#31325F',
              lineHeight: '40px',
              fontWeight: 300,
              fontFamily: 'Helvetica Neue',
              fontSize: '15px',

              '::placeholder': {
                color: '#CFD7E0',
              },
            },
          }
        });
        card.mount('#card-element');

        function setOutcome(result) {
          var successElement = document.querySelector('.success');
          var errorElement = document.querySelector('.error');
          successElement.classList.remove('visible');
          errorElement.classList.remove('visible');

          if (result.token) {
            // Use the token to create a charge or a customer
            // https://stripe.com/docs/charges
            successElement.querySelector('.token').textContent = result.token.id;
            successElement.classList.add('visible');
          } else if (result.error) {
            errorElement.textContent = result.error.message;
            errorElement.classList.add('visible');
          }
        }

        card.on('change', function(event) {
          setOutcome(event);
        });

        document.querySelector('form').addEventListener('submit', function(e) {
          e.preventDefault();
          var form = document.querySelector('form');
          var extraDetails = {
            name: form.querySelector('input[name=cardholder-name]').value,
          };
          stripe.createToken(card, extraDetails).then(setOutcome);
        });

        </script>

and this is my php code

<?php
// Set your secret key: remember to switch to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey('pk_test_');

// Token is created using Stripe Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
  'amount' => $_POST['amount'] * 100;,
  'currency' => 'usd',
  'description' => 'Charging',
  'source' => $token,
]);

How can i acquire and post the amount and token via jquery post?. I can get the amount posted via a simple jquery listener like $('.amount').val() but how can i acquire the token?. Also in the backend, how can i know if the transaction was successful or not and return to jquery this information?.

How to&Answers:

I did it this way

The html and js

    <form method="post" action="charge.php" name="crg">
    <div class="group">
        <label>
            <span>Email</span>
            <input  class="field" name="stripeEmail" placeholder="Your email" required/>
        </label>
        <label>
            <span>Name</span>
            <input name="cardholder-name" class="field" placeholder="Name on card" required/>
        </label>
        <label>
            <span>Amount</span>
            <input class="field" name="amount" placeholder="Amount to pay" type="number" required/>
        </label>
    </div>
    <div class="col-md-6">
        <div id="card-element" class="field"></div>
    </div>
    <button type="submit">Pay</button>
    <div class="outcome">
        <div class="error"></div>
        <div class="success">
            Success! Your Stripe token is <span class="token"></span>
        </div>
    </div>
</form>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<script>
    var stripe = Stripe('publishable key here');
    var elements = stripe.elements();
    var card = elements.create('card', {
        style: {
            base: {
                iconColor: '#666EE8',
                color: '#31325F',
                lineHeight: '40px',
                fontWeight: 300,
                fontFamily: 'Helvetica Neue',
                fontSize: '15px',
                '::placeholder': {
                    color: '#CFD7E0',
                },
            },
        }
    });
    card.mount('#card-element');
    function setOutcome(result) {
        var successElement = document.querySelector('.success');
        var errorElement = document.querySelector('.error');
        successElement.classList.remove('visible');
        errorElement.classList.remove('visible');
        if (result.token) {
            // Use the token to create a charge or a customer
            // https://stripe.com/docs/charges
            successElement.querySelector('.token').textContent = result.token.id;
            successElement.classList.add('visible');
            var config = {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Headers': 'X-Requested-With'
                }
            };
            var form = document.querySelector('form');
            axios.post('charge.php',{
                stripeToken: result.token.id,
                stripeEmail: form.querySelector('input[name=stripeEmail]').value,
                amount: form.querySelector('input[name=amount]').value,
            },config).then(resp=>{
                console.log(resp)
            });
        } else if (result.error) {
            errorElement.textContent = result.error.message;
            errorElement.classList.add('visible');
        }
    }
    card.on('change', function (event) {
        setOutcome(event);
    });
    document.querySelector('form').addEventListener('submit', function (e) {
        e.preventDefault();
        var form = document.querySelector('form');
        var extraDetails = {
            name: form.querySelector('input[name=cardholder-name]').value,
        };
        stripe.createToken(card, extraDetails).then(setOutcome);
    });
</script>

and the php

<?php
require_once('vendor/autoload.php');

$_POST = json_decode(file_get_contents("php://input"),true);
//composer require stripe/stripe-php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

\Stripe\Stripe::setApiKey('secret key here');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$in_cents = 100;
$charge = \Stripe\Charge::create([
    'amount' => $in_cents,
    'currency' => 'usd',
    'description' => 'Charging',
    'source' => $token,
]);

//echo $charge;

?>