How To Integrate Stripe Payment Gateway In Codeigniter Tutorial Example

Codeigniter 4 , Codeigniter

Nicesnippets

344

10-09-2021


How To Integrate Stripe Payment Gateway In Codeigniter Tutorial Example

Hi guys,

Today i will explained How To Integrate Stripe Payment Gateway In Codeigniter. This example is so easy to use in Codeigniter 4.

Codeigniter 3 Stripe payment gateway integration tutorial; In this comprehensive example, you will learn how to implement Stripe Payment Gateway in Codeigniter using the Stripe PHP library and Stripe API key, secret.

Stripe is a notable payment processing for online business; It offers an outstanding infrastructure for payment APIs, which amplifies the transaction of payments for every business type regardless of the company’s size.

So let's start to the example.

Step 1 : Create Codeigniter Project


composer create-project codeigniter4/appstarter

Step 2 : Add Stripe PHP Library

Secondly, you require to download the stripe-php library to access the Stripe API.

Afterward, unzip the folder inside the project/app/Libraries directory, and don’t forget to change the directory’s name to stripe-php.

Step 3 : Get Stripe API key and Secret

In this step, you have to visit the Stripe site, create a new stripe development account to access the Stripe API Key and Secret:

Once you entered in stripe dashboard, then click on the Developers/API Keys from the Standard keys section to get your Publishable key and Secret key.

Subsequently, open application/config/config.php configuration file and add the Stripe API keys at the bottom of the file:

$config['stripe_key'] = 'pk_test_51H7bbSE2RcKvfXD4D';

$config['stripe_secret'] = 'sk_test_51H7bbSE2RcKvfX';

Step 4 : Set Up Controller

Further, you need to generate a new controller that manages the online stripe transaction, hence create a StripePayment file and append the example code in application/controllers/StripePaymentController.php:

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class StripePaymentController extends CI_Controller {

public function __construct()

{

parent::__construct();

$this->load->library("session");

$this->load->helper('url');

}

public function index()

{

$this->load->view('checkout');

}

public function handlePayment()

{

require_once('application/libraries/stripe-php/init.php');

\Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));

\Stripe\Charge::create ([

"amount" => 100 * 120,

"currency" => "inr",

"source" => $this->input->post('stripeToken'),

"description" => "Dummy stripe payment."

]);

$this->session->set_flashdata('success', 'Payment has been successful.');

redirect('/make-stripe-payment', 'refresh');

}

}

Step 5 : Add Routes

Next, create two routes; both will handle HTTP requests GET and POST simultaneously. The first route invokes the view file, similarly another access the handlePayment() method to make the payment with Stripe payment gateway.

Additionally, we also changed the default controller to StripePaymentController for this demo tutorial; else, you can skip it.

Open and update the provided code in application/config/routes.php file:

$route['default_controller'] = 'StripePaymentController';

$route['404_override'] = '';

$route['translate_uri_dashes'] = FALSE;

$route['make-stripe-payment'] = "StripePaymentController";

$route['handleStripePayment']['post'] = "StripePaymentController/handlePayment";

Step 6 : Set Up View

Head over to application/views/ folder, create a new checkout file. Likewise, open and add the suggested code example in application/views/checkout.php file:

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>How To Integrate Stripe Payment Gateway In Codeigniter Tutorial Example - Nicesnippets.com</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"

rel="stylesheet" />

</head>

<body>

<div class="container">

<div class="row">

<div class="col-md-6 col-md-offset-3">

<div class="panel panel-default">

<div class="panel-body">

<?php if($this->session->flashdata('success')){ ?>

<div class="alert alert-success text-center">

<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>

<p><?php echo $this->session->flashdata('success'); ?></p>

</div>

<?php } ?>

<form role="form" action="<?php echo base_url('handleStripePayment');?>" method="post"

class="form-validation" data-cc-on-file="false"

data-stripe-publishable-key="<?php echo $this->config->item('stripe_key') ?>"

id="payment-form">

<div class='form-row row'>

<div class='col-xs-12 form-group required'>

<label class='control-label'>Name on Card</label>

<input class='form-control' size='4' type='text'>

</div>

</div>

<div class='form-row row'>

<div class='col-xs-12 form-group card required'>

<label class='control-label'>Card Number</label>

<input autocomplete='off' class='form-control card-number' size='20' type='text'>

</div>

</div>

<div class='form-row row'>

<div class='col-xs-12 col-md-4 form-group cvc required'>

<label class='control-label'>CVC</label>

<input autocomplete='off' class='form-control card-cvc' placeholder='ex. 311'

size='4' type='text'>

</div>

<div class='col-xs-12 col-md-4 form-group expiration required'>

<label class='control-label'>Expiration Month</label>

<input class='form-control card-expiry-month' placeholder='MM' size='2' type='text'>

</div>

<div class='col-xs-12 col-md-4 form-group expiration required'>

<label class='control-label'>Expiration Year</label>

<input class='form-control card-expiry-year' placeholder='YYYY' size='4'

type='text'>

</div>

</div>

<div class='form-row row'>

<div class='col-md-12 error form-group hide'>

<div class='alert-danger alert'>Error occured while making the payment.</div>

</div>

</div>

<div class="row">

<div class="col-xs-12">

<button class="btn btn-danger btn-lg btn-block" type="submit">Pay ($100)</button>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

<script type="text/javascript">

$(function () {

var $stripeForm = $(".form-validation");

$('form.form-validation').bind('submit', function (e) {

var $stripeForm = $(".form-validation"),

inputSelector = ['input[type=email]', 'input[type=password]',

'input[type=text]', 'input[type=file]',

'textarea'

].join(', '),

$inputs = $stripeForm.find('.required').find(inputSelector),

$errorMessage = $stripeForm.find('div.error'),

valid = true;

$errorMessage.addClass('hide');

$('.has-error').removeClass('has-error');

$inputs.each(function (i, el) {

var $input = $(el);

if ($input.val() === '') {

$input.parent().addClass('has-error');

$errorMessage.removeClass('hide');

e.preventDefault();

}

});

if (!$stripeForm.data('cc-on-file')) {

e.preventDefault();

Stripe.setPublishableKey($stripeForm.data('stripe-publishable-key'));

Stripe.createToken({

number: $('.card-number').val(),

cvc: $('.card-cvc').val(),

exp_month: $('.card-expiry-month').val(),

exp_year: $('.card-expiry-year').val()

}, stripeResponseHandler);

}

});

function stripeResponseHandler(status, res) {

if (res.error) {

$('.error')

.removeClass('hide')

.find('.alert')

.text(res.error.message);

} else {

var token = res['id'];

$stripeForm.find('input[type=text]').empty();

$stripeForm.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");

$stripeForm.get(0).submit();

}

}

});

</script>

</html>

Step 7 : Test Codeigniter Stripe App

Next, you have to run the Codeigniter 3 project, start the PHP development server. You can use MAMP or XAMPP, go to htdocs folder and keep your codeigniter project folder inside of it.

Run the following url on the browser:

http://localhost:8888/ci-stripe/make-stripe-payment

Output

Now you can check your own.

I hope it can help you...


Recommended Posts