Google trends Public Holidays Coupon Code Code Compiler

Stripe Payment Gateway Integration using PHP


Jun 11, 2019

In this article, we are going to see about implementing Stripe payment gateway and how to integrate using PHP. There are so many payment gayeway available to integrate payment gateway in an application. For example, PayPal, Stripe, Sage Pay, CCAvenue and there is a long list out there. They provide API for integrating payment gateway to our application. In many countries, Stripe is the widely used for the transactions with credit and debit cards. By using a payment gateway services, we can enable users to do financial transactions with our application. When it comes to integrating a payment gateway with our application, we need to choose a reputed provider.

Create a Stripe account and get API keys

login to the stripe account. Navigate through the Developers -> API keys menu to get the API keys. There is two type of standard API keys named secret key and publishable key.

Download stripe SDk Stripe SDK for php

Create HTML form


<div id="message"><div>
<form id="stripeForm" action="payment.php" method="post">
    <div class="row">
        <label>Card Holder Name</label> 
		<input type="text" id="name"  name="name" >
    </div>
    <div class="row">
        <label>Email</label>
        <input type="text" id="email" name="email">
    </div>
    <div class="field-row">
        <label>Card Number</label> 
		<input type="text" id="card-number" name="card-number">
    </div>
    <div class="row">
        <div class="contact-row column-right">
            <label>Expiry Month / Year</label> 
			<select name="month" id="month">
                <option value="01">01</option>
                <option value="02">02</option>
                <option value="03">03</option>
                <option value="04">04</option>
                <option value="05">05</option>
                <option value="06">06</option>
                <option value="07">07</option>
                <option value="08">08</option>
                <option value="09">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
                <option value="05">05</option>
            </select> <select name="year" id="year">
                <option value="19">2019</option>
                <option value="20">2020</option>
                <option value="21">2021</option>
                <option value="22">2022</option>
                <option value="23">2023</option>
                <option value="24">2024</option>
                <option value="25">2025</option>
                <option value="26">2026</option>
                <option value="27">2027</option>
                <option value="28">2028</option>
                <option value="29">2029</option>
                <option value="30">2030</option>
            </select>
        </div>
        <div class="contact-row cvv-box">
            <label>CVC</label>
            <input type="text" name="cvc" id="cvc">
        </div>
    </div>
	<input type='hidden' name='amount' value='1'> 
    <div>
        <input type="submit" name="pay_now" value="Submit" id="submit-btn" onClick="stripePay(event);">

    </div>
    
</form>

Generate token using javascript


<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script src="vendor/jquery/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
function Validation () {
    var valid = true;
    var name = $('#name').val();
    var email = $('#email').val();
    var cardNumber = $('#card-number').val();
    var month = $('#month').val();
    var year = $('#year').val();
    var cvc = $('#cvc').val();

    $("#message").html("").hide();

    if (name.trim() == "") {
        valid = false;
    }
    if (email.trim() == "") {
    	   valid = false;
    }
    if (cardNumber.trim() == "") {
    	   valid = false;
    }

    if (month.trim() == "") {
    	    valid = false;
    }
    if (year.trim() == "") {
        valid = false;
    }
    if (cvc.trim() == "") {
        valid = false;
    }

    if(valid == false) {
        $("#message").html("All Fields are required").show();
    }

    return valid;
}
//set your publishable key
Stripe.setPublishableKey("pk_test_YGHBJh4774248492");

//callback to handle the response from stripe
function stripeResponseHandler(status, response) {
    if (response.error) {
        //enable the submit button
        $("#submit-btn").show();
        //display the errors on the form
        $("#message").html(response.error.message).show();
    } else {
        //get token id
        var token = response['id'];
        //insert the token into the form
        $("#stripeForm").append("<input type='hidden' name='token_id' value='" + token + "' />");
        //submit form to the server
        $("#stripeForm").submit();
    }
}
function stripePay(e) {
    e.preventDefault();
    var valid = Validation();

    if(valid == true) {
        $("#submit-btn").hide();
        Stripe.createToken({
            number: $('#card-number').val(),
            cvc: $('#cvc').val(),
            exp_month: $('#month').val(),
            exp_year: $('#year').val()
        }, stripeResponseHandler);

        //submit from callback
        return false;
    }
}
</script>

Php Code for payment (payment.php)


require_once('./stripe/autoload.php');
// set your secure key
\Stripe\Stripe::setApiKey(sk_test_78huiGBHbuebcbe);

$token_id = $_REQUEST['token_id'];
$email = $_REQUEST['email'];
$amount = $_REQUEST['amount'];

//create customer
try {
	$customer_stripe = \Stripe\Customer::create(array(
                    "description" => $email,
                    "source" => $token_id));
	} catch (\Stripe\Error\Card $e) {
        $msg = "Card credentials are invalid. Please try a different card.";
        exit();
    } catch (\Stripe\Error\InvalidRequest $e) {
        $msg = "We are sorry but we were not able to process your payment due to an internal error and we have notified the service provider.";
		exit();
    } catch (\Stripe\Error\Authentication $e) {
        $msg = "Network communication failed. Please try again.";
        exit();
    } catch (\Stripe\Error\ApiConnection $e) {
        $msg = "Network communication failed. Please try again.";
        exit();
    } catch (\Stripe\Error\Base $e) {
        $msg = "Payment has failed! Please try again.";
        exit();
    } catch (Exception $e) {
        $msg = "Your payment has failed. Please try again!";
        exit();
    }
	
	if (!empty($customer_stripe->id){
	
	try {
                
			$charge = \Stripe\Charge::create(array(
												   "amount" => (int)($amount * 100), // amount in cents, again
												   "currency" =>USD,
												   "customer" => $customer_stripe->id)
											 );
                
                
            } catch (\Stripe\Error\Card $e) {
                $msg = "Card credentials are invalid. Please try a different card.";
                exit();
                
            } catch (\Stripe\Error\InvalidRequest $e) {
                $msg = "We are sorry but we were not able to process your payment due to an internal error and we have notified the service provider.";
                exit();
            } catch (\Stripe\Error\Authentication $e) {
                $msg = "Network communication failed. Please try again.";
                exit();
            } catch (\Stripe\Error\ApiConnection $e) {
                $msg = "Network communication failed. Please try again.";
                exit();
            } catch (\Stripe\Error\Base $e) {
                $msg = "Payment has failed! Please try again.";
                exit();
            } catch (Exception $e) {
                $msg = "Your payment has failed. Please try again!";
                exit();
            }
	
	}
	
	if($charge->id)
	{
		$msg = 'Payment successful, your transaction id '.$charge->id;
		exit;
	}

Copyright 2024. All rights are reserved