How to Integrate Stripe Payment Gateway in Codeigniter

Last updated on by Digamber

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.

In this Codeigniter Stripe example, we need a Stripe PHP library. It is a PHP library that gives an amazing Stripe API set to help you integrate Stripe in the Codeigniter application. Later implementing Stripe in Codeigniter, you can add credit card details and use the stripe payment gateway in Codeigniter to make the facile transactions.

Codeigniter Stripe Payment Gateway Integration Example

  • Step 1: Create Codeigniter Project
  • Step 2: Add Stripe PHP Library
  • Step 3: Get Stripe API key and Secret
  • Step 4: Set Up Controller
  • Step 5: Add Routes
  • Step 6: Set Up View
  • Step 7: Test Codeigniter Stripe App

Create Codeigniter Project

First, ensure you have composer installed on your system; then, you can use the suggested command to create the Codeigniter starter app.

composer create-project codeigniter4/appstarter

Move inside the CI project:

composer cd appstarter

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.

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:

#--------------------------------------------------------------------
# Stripe
#--------------------------------------------------------------------

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

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');
    }
}

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";

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>Implement Stripe Payment Gateway in Codeigniter</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>

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

Here is the test credit card detail that you can use to test the stripe payment gateway in codeigniter:

NameNumberBrandCVCExpiryDate
Test4242 4242 4242 4242Visa45612/252025

Integrate Stripe Payment Gateway in Codeigniter

Conclusion

Codeigniter Stripe payment gateway tutorial is over; in this tutorial, we learned how to subscribe to stripe payment gateway in Codeigniter using the PHP stripe library. We have also known to access stripe API to make the payment using the credit card details. I reckon you loved the whole discourse and will share it with others.