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.

PayPal and Stripe – Javascript

Whether you are creating an E-commerce website or simply wanted to receive payments from your website using PayPal and Stripe, this script already contains all the source code you need to show Stripe and PayPal payment buttons and receive payments directly in your Stripe and PayPal accounts.

It also has a full shopping cart implementation, where you can add products to the cart, update quantities, remove products from the cart and move to checkout.

Demo

Home page

Here you can add products to the shopping cart and also you can remove products from the shopping cart.

When you add or remove a product from the shopping cart, you will see the shopping cart badge on top updating its values in real-time.

Shopping cart

On clicking the above “Cart” button you will be redirected to the shopping cart page where you can change the number of products and can also remove the product from the shopping cart.

You can also see the grand total at the bottom right that changes in real-time as you change the quantity of product or when you remove a product from the shopping cart.

Checkout

Here you can make the payment using Stripe or Paypal.

Fully documented code

Comments have been added with each line of code for explanation.

Separate file for each function

To manage the code, each payment method is separated in its own file. So you can easily change and modify the code as per your needs.

How to get donations from Stripe in WordPress

In this tutorial, we are going to teach you how you can get donations in your WordPress site for non-profit organizations using Stripe. We assume that you already have registered a Stripe account and a WordPress site.

We will be using a WordPress plugin to get donations.

Learn how to integrate Stripe using Javascript.

Stripe Payment Gateway – Javascript, PHP

Following are the steps:

Video tutorial:

  1. Goto Plugins > Add New.
  2. Search for “Stripe”.
  3. Install and activate the plugin named “Stripe Payments by wptipsntricks”.
  4. Then you will see “Stripe Payments” menu on left sidebar on admin panel. Goto Stripe Payments > Settings.
  5. Scroll down and you will see 4 fields:
    • Live Stripe Publishable Key
    • Live Stripe Secret Key
    • Test Stripe Publishable Key
    • Test Stripe Secret Key
  6. Goto your stripe dashboard and from left sidebar, goto Developers > API keys.
  7. Copy the publishable and secret key and paste them in respective fields. Make sure if you are using test mode or live mode.
  8. Coming back to your WordPress admin panel, goto Stripe Payments > Add New Product.
  9. In “Price & Currency” section, select “Donation”.
  10. You will also see a section named “Embed Product” on right hand side below “Publish” button.
  11. Copy the shortcode and paste that in your post or wherever you want to show the payment button.

Now, you can use the following credentials for testing the payment method:

Card Number5555 5555 5555 4444
Expiry Month02
Expiry Year22
CVC314

Whenever someone makes a donation to your site, you will see that in your Stripe dashboard “Payments” page from the left sidebar. You can follow this link for sandbox accounts. For live accounts, simply remove the “test” part from the URL.

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