Stripe Payment Gateway – Javascript, PHP

In this tutorial, we are going to teach you how you can receive payments online with Stripe using simple Javascript and PHP.

Video Tutorial:

Installing Stripe PHP SDK

First, you need to open the command prompt or terminal in your project’s root folder and run the following command. Make sure you have the composer installed, if not, you can download it from here.

COMPOSER_MEMORY_LIMIT=-1 composer require stripe/stripe-php

After that, you need to go to stripe.com and go to the Developers page (from the top menu) and then the API keys section. You can directly visit this page. Copy the secret key, you will need it in the next step.

Client-Side : Receive the Payment

The following code will create a payment intent for $10 USD, but you can change it as per your need:

<?php

	require_once "vendor/autoload.php";

	$amount = 10;

	$stripe = new \Stripe\StripeClient("{your_secret_key}");

	// creating setup intent
    $payment_intent = $stripe->paymentIntents->create([
        'payment_method_types' => ['card'],

        // convert double to integer for stripe payment intent, multiply by 100 is required for stripe
        'amount' => round($amount) * 100,
        'currency' => 'usd',
    ]);

?>

<input type="hidden" id="stripe-public-key" value="{your_publishable_key}" />
<input type="hidden" id="stripe-payment-intent" value="<?php echo $payment_intent->client_secret; ?>" />

<!-- credit card UI will be rendered here -->
<div id="stripe-card-element" style="margin-top: 20px; margin-bottom: 20px;"></div>

<button type="button" onclick="payViaStripe();">Pay via stripe</button>

<!-- billing details is required for some countries -->
<input type="hidden" id="user-email" value="support@adnan-tech.com" />
<input type="hidden" id="user-name" value="AdnanTech" />
<input type="hidden" id="user-mobile-number" value="123456789" />

<!-- include Stripe library -->
<script src="https://js.stripe.com/v3/"></script>

<script>
    // global variables
    var stripe = null;
    var cardElement = null;

    const stripePublicKey = document.getElementById("stripe-public-key").value;

    // initialize stripe when page loads
    window.addEventListener("load", function () {
        stripe = Stripe(stripePublicKey);
        var elements = stripe.elements();
        cardElement = elements.create('card');
        cardElement.mount('#stripe-card-element');
    });
</script>

Make sure to write your secret key (line #7) and publishable key (line #20). For billing details, you can show your user’s details dynamically from the database, etc. Contact us if you face any problems in this step.

If you refresh the page now, you will see an input field to enter your debit card number, CVV, and expiry date. And a button that says “Pay via stripe“. On clicking that button, nothing happens.

So we will create a function that will be called when this button is clicked and it will make the payment. So, create the following Javascript function:

function payViaStripe() {
	// get stripe payment intent
    const stripePaymentIntent = document.getElementById("stripe-payment-intent").value;

    // execute the payment
    stripe
        .confirmCardPayment(stripePaymentIntent, {
            payment_method: {
                    card: cardElement,
                    billing_details: {
                        "email": document.getElementById("user-email").value,
                        "name": document.getElementById("user-name").value,
                        "phone": document.getElementById("user-mobile-number").value
                    },
                },
            })
            .then(function(result) {

                // Handle result.error or result.paymentIntent
                if (result.error) {
                    console.log(result.error);
                } else {
                    console.log("The card has been verified successfully...", result.paymentIntent.id);

                    // [call AJAX function here]
                }
            });
}

Refresh the page now and try to make the payment now. You can use the following information for testing the payment:

Debit Card Number4242 4242 4242 4242
CVV422
Expiry date (month)04
Expiry date (year)27
Stripe sandbox testing payment information

You will see a payment ID in the console if the payment is successful. Now we need to validate this payment from the server-side as well.

Server Side : Verify the Payment

The following code goes in the [call AJAX function here] section of the previous step. We will call an AJAX to the server with the payment ID to verify this payment.

confirmPayment(result.paymentIntent.id);

Then we need to create this function in Javascript:

function confirmPayment(paymentId) {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "stripe.php", true);
 
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                var response = JSON.parse(this.responseText);
                console.log(response);
            }
 
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };
 
    var formData = new FormData();
    formData.append("payment_id", paymentId);
    ajax.send(formData);
}

After that, we need to create a file named stripe.php that will handle this request. You can set the server file as your own. The following code goes in the stripe.php file:

<?php

	require_once "vendor/autoload.php";

	$stripe = new \Stripe\StripeClient('{your_secret_key}');

	try
	{
		$payment = $stripe->paymentIntents->retrieve(
			$_POST["payment_id"],
			[]
		);

		if ($payment->status == "succeeded")
		{
			echo json_encode([
				"status" => "success",
				"payment" => $payment,
			]);
			exit();
		}
	}
	catch (\Exception $exp)
	{
		echo json_encode([
			"status" => "error",
			"message" => $exp->getMessage()
		]);
		exit();
	}

Make sure to replace your own secret key in line #5. Refresh the page now and try to make another payment, now you will see 2 console messages.

  1. The first console message will tell the payment ID if the payment is made, or an error message otherwise.
  2. The second console message will be the response sent from the server, whether the payment is verified or not.

You can also check the payment from your Stripe dashboard directly from here.

For Laravel Developers

If you are developing your application in Laravel, you do not need to write the require_once line.

So now you have learned how to integrate stripe in your website using Javascript and PHP. You can also learn how to receive donations from Stripe on your WordPress website for non-profit organizations.

If you face any problems in following this, kindly do let me know in the comments section below.

Note: I will add Stripe payment gateway in your website in just $5.

2 Replies to “Stripe Payment Gateway – Javascript, PHP”

  1. hi,
    Everything as per the instructions. I am facing this issue.

    Fatal error: Uncaught (Status 401) Invalid API Key provided: {‘sk_tes***************************************************************************************************WX’} thrown in C:\xampp\htdocs\QuwatAli\vendor\stripe\stripe-php\lib\Exception\ApiErrorException.php on line 38

Leave a Reply

Your email address will not be published. Required fields are marked *