Implement Stripe Payment Gateway in Codeigniter 3

Throughout this Codeigniter 3 Stripe payment gateway tutorial, we will help you assimilate how to integrate credit card payment gateway in Codeigniter application using Stripe payment gateway.

Codeigniter Stripe Payment Gateway Implementation Example

A payment gateway is the backbone of the eCommerce business. It allows buyers and sellers to create monetary consensus swiftly; with the help of this comprehensive guide, we will help you add and use stripe payment gateway in the Codeigniter application.

Stripe makes the online transactions smooth and easy; you can easily integrate stripe card payment gateway in the Codeigniter app. Not just Codeigniter, but there are many other platforms where Stripe can easily be added. You will require a stripe PHP library, likewise the Stripe API and Secret keys.

Integrate Stripe Payment Gateway in Codeigniter 3 App

These are the bit by bit instructions you have to follow to integrate a stripe card payment gateway into the Codeigniter platform.

  • Step 1: Download Codeigniter App
  • Step 2: Include Stripe PHP Library
  • Step 3: Register Stripe Key and Secret
  • Step 4: Configure Routes
  • Step 5: Create Controller
  • Step 6: Create View
  • Step 7: Start Application

Download Codeigniter App

Invoke the initial step by downloading the Codeigniter 3 app from codeigniter.com:

Plus, unzip the project and rename it if you want. Additionally, make sure to create a controller and view to integrate the stripe card payment gateway in the Codeigniter project.

Download and Include Stripe PHP Library

In this step, head over to https://github.com/stripe/stripe-php and download the stripe-php library.

Unzip the folder.

Rename it to stripe-php.

Right after that keep it intact in the project/app/Libraries folder.

Register Stripe Key and Secret

You need to have a Stripe developer account to get the stripe credentials to connect Codeigniter and Stripe.

Once you created the account, visit Developers > API Keys, after which you will land to the API Keys page; from here, you can get the Publishable key and Secret key.

Open and add the Stripe secret keys in the application/config/config.php file:

#--------------------------------------------------------------------
# Stripe credentials
#--------------------------------------------------------------------

$config['stripe_key'] = 'pk_test_xxxxxxxxxxxxxxxxxxxxxx';
$config['stripe_secret'] = 'sk_test_xxxxxxxxxxxxxxxxxxxxxx'';

Configure Routes

You need to create two routes to handle stripe card payment in codeigniter, hence open and update the suggested code in application/config/routes.php file:

$route['default_controller'] = 'PaymentGatewayController';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['payment-gateway'] = "PaymentGatewayController";
$route['makeStripePayment']['post'] = "PaymentGatewayController/makePayment";

Create Controller

In this step, you have to create a controller file, name it PaymentGatewayController as you notice, we have declared the controller name in the routes. Anyway, create this file inside the application/controllers/ directory.

Afterwards, update the application/controllers/PaymentGatewayController.php file:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
   
class PaymentGatewayController extends CI_Controller {
    
    public function __construct() {
       parent::__construct();

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

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

    public function index()
    {
        $this->load->view('home');
    }
    
    public function makeStripePayment()
    {
        require_once('application/libraries/stripe-php/init.php');
        \Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));

        \Stripe\Charge::create ([
                "amount" => 100 * 100,
                "currency" => "inr",
                "source" => $this->input->post('stripeToken'),
                "description" => "Test payment." 
        ]);
            
        $this->session->set_flashdata('success', 'Payment is successful.');
        redirect('/payment-gateway', 'refresh');
    }
}

Create View

In the last step, you have to create a new view file, name it home.php, and keep it inside the application/views/ folder.

Lastly, add the given below code in application/views/home.php file:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<title> Codeigniter Stripe Card Payment Gateway Integration Example</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('makeStripePayment');?>" 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.</div>
								</div>
							</div>

							<div class="row">
								<div class="col-xs-12">
									<button class="btn btn-primary 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 $stripePg = $(".form-validation");
		$('form.form-validation').bind('submit', function (e) {
			var $stripePg = $(".form-validation"),
				inputSelector = ['input[type=email]', 'input[type=password]',
					'input[type=text]', 'input[type=file]',
					'textarea'
				].join(', '),
				$inputs = $stripePg.find('.required').find(inputSelector),
				$errorMessage = $stripePg.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 (!$stripePg.data('cc-on-file')) {
				e.preventDefault();
				Stripe.setPublishableKey($stripePg.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()
				}, handleStripePayment);
			}

		});

		function handleStripePayment(status, res) {
			if (res.error) {
				$('.error')
					.removeClass('hide')
					.find('.alert')
					.text(res.error.message);
			} else {
				var token = res['id'];
				$stripePg.find('input[type=text]').empty();
				$stripePg.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
				$stripePg.get(0).submit();
			}
		}

	});
</script>

</html>

Start Application

You can eventually start the app for testing purpose, if you are testing it locally, then use any PHP development server, ensure to keep the project folder inside the htdocs directory:

You can test the app using this url:

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

Use the dummy credit card details to process the payments.

Name:           Test
Card number:    4242 4242 4242 4242	
Brand:          Visa
Cvc:            456
Expiry:         12/25	
Date:           2024

Conclusion

Codeigniter Stripe payment gateway example is accomplished; we reckon you have understood how to easily integrate stripe payment gateway in Codeigniter ecosystem with the help of PHP stripe library and Stripe api keys.