Make a Stripe payment with Jquery AJAX? (Javascript ONLY)

11,761

Solution 1

Disclaimer: This works, but it is TERRIBLE practice. Don't use this for a real project. I needed it for a front-end only testing environment. As other users on this page has pointed out, you should be doing this on the backend!

I finally found some useful documentation at: https://stripe.com/docs/api#create_charge

As I suspected the URL I was using was wrong.

after getting the right URL, the following ajax call works:

Hope That helps someone else as well! As most answers, are PHP or other backend languages.

$.ajax({
        type: 'POST',
        url: 'https://api.stripe.com/v1/charges',
        headers: {
          Authorization: 'Bearer sk_test_YourSecretKeyHere'
        },
        data: {
          amount: 3000,
          currency: 'usd',
          source: response.id,
          description: "Charge for [email protected]"
        },
        success: (response) => {
          console.log('successful payment: ', response);
        },
        error: (response) => {
          console.log('error payment: ', response);
        }
      })

Solution 2

EDIT: This is insecure (and outdated)! You shouldn't send your user's card information directly to your own server. Instead, you should directly send it to Stripe. There's an up-to-date (using intents, etc) example here


You need to POST to a PHP file in your $.ajax() function:

  $.ajax({
    type: 'POST',
    url: './stripe-payment.php',
    headers: {
      stripeToken: response.id
    },
    data: {
      number: ccNum,
      cvc: ccCVC,
      exp_month: ccMonth,
      exp_year: ccYear
    },
    success: (response) => {
      console.log('successful payment: ', response);
    },
    error: (response) => {
      console.log('error payment: ', response);
    }
  })

Your PHP should have something like the Stripe PHP bindings require()d to use the Stripe payment API, and that PHP file should look something like this, from this SO question:

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

?>

Refer to that Github's README for more, as well as the Stripe documentation.

Share:
11,761
MLyck
Author by

MLyck

Updated on June 07, 2022

Comments

  • MLyck
    MLyck almost 2 years

    I am trying to make a custom payment form for Stripe, and I want to make the AJAX call to Stripe manually. (instead of a submit event)

    However, first off I am pretty sure I am posting it to the wrong place. But I can't figure out what URL I'm supposed to make this post request to.

    If I am using the right url. I am getting a 405 not allowed response. With no information on what is wrong with my request.

    Here's what I got:

    Stripe.setPublishableKey('pk_test_12345');
        Stripe.card.createToken({
          number: ccNum,
          cvc: ccCVC,
          exp_month: ccMonth,
          exp_year: ccYear
        }, stripeResponseHandler);
    

    This part works fine, gives me a 200 OK status and I got a token back from the server.

    function stripeResponseHandler(status, response) {
          console.log('card status: ', status);
          console.log('token: ', response.id);
          $.ajax({
            type: 'POST',
            url: 'https://checkout.stripe.com/checkout.js',
            headers: {
              stripeToken: response.id
            },
            data: {
              number: ccNum,
              cvc: ccCVC,
              exp_month: ccMonth,
              exp_year: ccYear
            },
            success: (response) => {
              console.log('successful payment: ', response);
            },
            error: (response) => {
              console.log('error payment: ', response);
            }
          })
        }
    

    This however, gives me the 405 Not Allowed. It seems a bit weird to me that the endpoint would be a .js file. Which is why I am assuming I got the wrong URL.

    Can anyone help me figure out how to make a manual post request for a Stripe payment?