Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stripe charge with a checkout token sent via AJAX to php

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.

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

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" => "[email protected]")
);
echo 'success';
} catch(Stripe_CardError $e) {
  // The card has been declined
    echo $tokenid;
}

?>

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.

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?

Thanks!

like image 941
jdchizzle Avatar asked Mar 17 '14 00:03

jdchizzle


1 Answers

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

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.

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'];

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!

like image 165
jdchizzle Avatar answered Oct 13 '22 00:10

jdchizzle