This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Streamline Your Online Payments With PHP Stripe Payment Gateway Integration

October 22, 2021

6 Min Read
Stripe PHP API

Collecting credit card payments is difficult for new companies and businesses on the web. You need to apply for a shipper account, beyond any doubt your servers are PCI-compliant, execute credit card sanity checks, and compose server-side code to coordinate with a service.

PHP Stripe API turned this exceptionally agonizing task of collecting credit card payments into a matter of copy & paste. It’s basically a JavaScript library that interfaces your web page to Stripe’s web servers. The information is never sent to your servers making it so effective. You don’t have to stress over the server-side settings of your application.

You’ll be able to make a professional-looking credit card Stripe payment form in minutes. Using Stripe integration, you can make one-time payment forms. You might think that this sounds somewhat like Paypal. To clarify the difference we will have a brief comparison of both the platforms to conclude this piece.

What is Stripe?

Stripe PHP is an online and credit card payment method preparing platform for businesses. When a client buys a product online, the funds have to be compelled to be delivered to the seller. Stripe API permits secure and proficient handling of funds via credit card or bank and transfers those funds to the sellers’ account.

The Stripe PHP API permits developers to get to the functionality of Stripe. Stripe is a benefit that permits clients to acknowledge payments online. With the Stripe application, users can keep track of payments, look at past payments, make recurring payments, and keep track of their clients easily.

How does PHP Stripe work?

The Stripe PHP integration payment gives a simple and effective way to accept credit cards directly on your web application. You’ll be able to coordinate effortlessly with the checkout framework in your PHP-based site, which allows the client to pay via credit or charge cards without clearing out your site.

The Stripe PHP library gives access to the Stripe API from applications composed within the PHP language. It incorporates a pre-defined set of classes for API that initialize themselves from the API which makes it compatible with a wide run of versions of the Stripe API.

Improve Your PHP App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

How Does Stripe Integrate with PHP?

First, sign in to your Cloudways account. If you don’t have one, sign up now for free.

Choose a Server

Select your server and custom PHP Stack application. Select the PHP server size as per your website traffic, and location according to your preferred region.

DO installation

Get API Keys for Stripe Integration

To get started, you must have a Stripe account. To integrate Stripe gateway in your application, you need to get your Stripe publishable key and secret key.

Login to your Stripe dashboard and navigate to the Developers » API keys page.

Stripe dashboard

You’ll see the API keys Publishable key and Secret key are listed under the Standard keys section. To show the Secret key, click on the Reveal test key token button.

stripe api keys

Stripe Checkout Form

We have to store the transaction details within the database at the point where we integrate a payment gateway on the site. So let’s make an installments table utilizing the following SQL inquiry.

CREATE TABLE `payments` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `payment_id` varchar(255) NOT NULL,
 `amount` float(10,2) NOT NULL,
 `currency` varchar(255) NOT NULL,
 `payment_status` varchar(255) NOT NULL,
 `captured_at` datetime NOT NULL DEFAULT current_timestamp(),
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, create a checkout form. As I mentioned earlier, Stripe generates card elements for you. We will generate these elements into the checkout form by following the Stripe documentation.

Create index.html file and place the below code in it.



Add some styling to the form using the code below in the style.css file or within the same file.

.StripeElement {
    box-sizing: border-box;
    
    padding: 12px 14px;
    
    height: 50px;
    
    border: 1px solid transparent;
    background-color: white;
    border-radius: 4px;
    
    
    box-shadow: 0 2px 6px 0 #e6ebf1;
    -webkit-transition: box-shadow 150ms ease;
    transition: box-shadow 160ms;
}
  
.StripeElement--focus {
    box-shadow: 0 2px 4px 0 #cff7df;
}
  
.StripeElement--invalid {
    border-color: #fa755a;
}
  
.StripeElement--webkit-autofill {
    background-color: #fefde5 !important;
}

After this, to generate card element and stripeToken, you need to add the following JavaScript code in the card.js file. This JavaScript code also validates the card details.

Now you need to create a Stripe client

StripeClient executes requests to the Stripe API and permits a client to recoup both a asset and call returns as well as a response object that contains data on the HTTP call.

// Create a Stripe client.
var stripe = Stripe('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',
        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` 
. 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. stripeTokenHandler(result.token); } }); }); // Submit the form with the token ID. function stripeTokenHandler(token) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); }

You would want to replace the placeholder PUBLISHABLE_KEY along with your real key within the aforementioned code which appeared to you in the beginning .

Stripe gives diverse plans of card components. Read more around documentation.

When the client submits a form with card details, Stripe produces a token within the background which is able to set ‘token’ as a hidden field. This token will be used to charge a card payment utilizing Stripe SDK.

Stripe Integration with Omnipay in PHP

We are all set with the basic setup. Now, to verify the card payment install the Omnipay Stripe library. Open the terminal in your extended root directory and run the command:

composer require league/omnipay omnipay/stripe

Stripe Integration with Omnipay

Once the library is installed, create a config.php file and initialize the payment object and database connection.

Database Configuration and Stripe API and (config.php)

Within the config.php record, constant variables of the Stripe API and database settings are pre-defined.

Stripe DB Constants

DB_USERNAME - Specify the database username.
DB_PASSWORD - Specify the database password.
DB_HOST - Specify the database host.
DB_NAME - Specify the database name.

Stripe API Constants

STRIPE_API_KEY - Specify the API Secret key.
STRIPE_PUBLISHABLE_KEY - Specify the API Publishable key.
connect_errno) {
    die("Connect failed: ". $db->connect_error);
}
   
$gateway = Omnipay::create('Stripe');
$gateway->setApiKey('SECRET_KEY_HERE');

Replace all the placeholders with the actual details. Once done, write the code as follows.

purchase([
            'amount' => $_POST['amount'],
            'currency' => 'USD',
            'token' => $token,
        ])->send();
      
        if ($response->isSuccessful()) {
            // payment was successful: update database
            $arr_payment_data = $response->getData();
            $payment_id = $arr_payment_data['id'];
            $amount = $_POST['amount'];
  
            // Insert transaction data into the database
            $isPaymentExist = $db->query("SELECT * FROM payments WHERE payment_id = '".$payment_id."'");
      
            if($isPaymentExist->num_rows == 0) { 
                $insert = $db->query("INSERT INTO payments(payment_id, amount, currency, payment_status) VALUES('$payment_id', '$amount', 'USD', 'Captured')");
            }
  
            echo "Payment is successful. Your payment id is: ". $payment_id;
        } else {
            // payment failed: display message to customer
            echo $response->getMessage();
        }
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}

We are now done with the code. Stripe gives dummy card details for testing the sandbox payment.

Create Stripe Payment Gateway Live

Once your integration is complete, the payment process is working, and you choose to go live, you need to replace your secret and publishable key with the live credentials. Follow the given steps to take the Stripe installment portal live.

  • Login to your Personal Stripe account and navigate to the Developers » API keys page.
  • Collect the API keys (Secret Key and Publishable Key) from Live Data.
  • Replace the Test API keys (Secret Key and Publishable Key) by the Live API keys (Secret Key and Publishable Key), in the config.php file.

Stripe vs Paypal

Here is a brief comparison of the services provided by Stripe and PayPal, and how each of them works.
Sripe-vs-Paypal

Conclusion

PHP Stripe is an online-only credit card processor that charges reasonable processing rates and has exceptionally few included costs. The basic Stripe API is good for businesses whose designers can construct a custom online e-commerce experience.

Stripe has official libraries for various programming languages and mobile platforms. Moreover, there are numerous third-party libraries and plugins made by the Stripe community.

Q. Is stripe an SDK ?

A: The Stripe API permits designers to get to the functionality of Stripe. Stripe is a service that permits clients to receive payments online, particularly developers. With the Stripe application, clients can keep track of payments, analyze past payments, make recurring payments, and keep track of clients.



                    
Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!