A Guide For Stripe Integration In Website With PHP

If you are running a website where you are collecting an online payment from the users then probably you heard about the Stripe Payments. Using Stripe, one can accept the payment using credit or debit card of a user. This is a more convenient way to pay online for your users.

In this article, we study about Stripe integration to the website with PHP.

Why Should Use Stripe?

Stripe is one of the most popular and secure payment gateway on the internet. When using a Stripe, the user does not need to leave your website. We can charge amount through Stripe webhooks without leaving a website. This feature adds a better user experience.

Another benefit is, user’s card details are always safe. In fact, on Stripe checkout they provide a generated elements where a user has to enter card details. Remember, these are not input elements created by the site owner. These elements are generated by Stripe which is way more secure.

After entering the card details, Stripe generates a token which will use for charge the card payment. There is no question of storing card details at all.

That being said, let’s take a look at Stripe integration to a website.

Stripe Integration

For getting started, you should have Stripe account. To accept payment online you need to get your Stripe secret kay and publishable key.

Login to your Stripe dashboard. You will get those keys from API->Test Data. We recommend first test payment transactions with the test mode. If everything works well, then go into live mode.

Next thing needs to do is create a checkout form. As we mentioned earlier, Stripe generates card elements for you. We will generate these elements by following this Stripe documentation.

Place the below code on your checkout page where the user can enter the card details.

<form action="payment.php" method="post" id="payment-form">
    <input type="text" name="email" placeholder="Enter Email"><br>
    <input type="text" name="amount" placeholder="Enter Amount">
    <input type="hidden" name="token" class="token">
    <div class="form-row">
        <label for="card-element">Credit or debit card</label>
        <div id="card-element">
            <!-- a Stripe Element will be inserted here. -->
        </div>

        <!-- Used to display form errors -->
        <div id="card-errors" role="alert"></div>
        </div>

        <button>Submit Payment</button>
</form>
<script src="https://js.stripe.com/v3/"></script>
<script>
    // Create a Stripe client
    var stripe = Stripe('PASTE_YOUR_PUBLISHABLE_KEY');

    // Create an instance of Elements
    var elements = stripe.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
    base: {
        color: '#32325d',
        lineHeight: '18px',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
        color: '#aab7c4'
        }
    },
    invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
    }
    };

    // Create an instance of the card Element
    var card = elements.create('card', {style: style});

    // Add an instance of the card Element into the `card-element` <div>
    card.mount('#card-element');

    // Handle real-time validation errors from the card Element.
    card.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
    });

    // Handle form submission
    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();

        stripe.createToken(card).then(function(result) {
            if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
            } else {
                // Send the token to your server. Use ajax request
                document.querySelector('.token').value = result.token.id;
                
                document.getElementById('payment-form').submit();
            }
        });
    });
</script>

Make sure to replace the placeholder with the actual value. Add the below CSS for the form.

.StripeElement {
    background-color: white;
    height: 40px;
    width: 500px;
    padding: 10px 12px;
    border-radius: 4px;
    border: 1px solid transparent;
    box-shadow: 0 1px 3px 0 #e6ebf1;
    -webkit-transition: box-shadow 150ms ease;
    transition: box-shadow 150ms ease;
}

.StripeElement--focus {
    box-shadow: 0 1px 3px 0 #cfd7df;
}

.StripeElement--invalid {
    border-color: #fa755a;
}

.StripeElement--webkit-autofill {
    background-color: #fefde5 !important;
}

After adding above code and CSS your form will look like as below:

Along with the card elements, we have added email and amount fields in the above form.

You can adjust the form design to fit with your website. Additionally, Stripe provides different designs of card elements. Read more about this here.

When the user submits a form with card details then Stripe generates a token. We set this token value in our form hidden field name ‘token’. This token will use for charge a card payment using Stripe SDK.

So we are passing the form data to the URL payment.php. In this PHP file, we will handle actual payment process.

Stripe SDK

To charge the card for payment, we need to install Stripe sdk library. We recommend to use Composer to install the library.

Open the terminal in your project root directory and run the command below:

composer require stripe/stripe-php

After installing the library, in our payment.php we write the code as follows.

payment.php

<?php
require_once "vendor/autoload.php";

if(!empty($_POST['token'])) {
    $token = $_POST['token'];
    $email = $_POST['email'];
    $amount = $_POST['amount'];

    //set api key
    $stripe = array(
        "secret_key"      => 'PASTE_YOUR_SECRET_KEY',
        "publishable_key" => 'PASTE_YOUR_PUBLISHABLE_KEY'
    );

    \Stripe\Stripe::setApiKey($stripe['secret_key']);

    //Add customer to stripe
    $customer = \Stripe\Customer::create(array(
        'email' => $email,
        'source'  => $token
    ));

    //item meta
    $item_name = 'My Website Registration Fee';
    $item_price = $amount * 100;
    $currency = "usd";
    $order_id = uniqid();

    //charge a credit or a debit card
    $charge = \Stripe\Charge::create(array(
        'customer' => $customer->id,
        'amount'   => $item_price,
        'currency' => $currency,
        'description' => $item_name,
        'metadata' => array(
            'order_id' => $order_id
        )
    ));

    //retrieve charge details
    $chargeResponse = $charge->jsonSerialize();

    //if charge is successful
    if($chargeResponse['paid'] == 1 && $chargeResponse['captured'] == 1) {

        //save txn_id in the database here
        $txn_id = $chargeResponse['balance_transaction'];

        echo "Payment successful";
    }
}
?>

Replace the placeholders with the actual values. One more thing to say, while passing amount we multiply it by 100. This is because Stripe treats as 100 cents means $1.00. Please refer documentation here.

If our payment executed successfully, then we get the transaction_id with $chargeResponse['balance_transaction'].

When we go live, all you need to do is change your secret and publishable key with the live mode.

We hope you may learn about the Strip integration on a website with PHP. You may also like to see our related articles below:

If you liked this article, then please subscribe to our Youtube Channel for video tutorials.

Recommended Tutorials For You

Posted in PHP

Leave a Reply

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