Stripe payment gateway integration using php and stripe.js

Before going to start we need stripe account with publishable key and
secret key.
Stripe test mode start with prefix “sk_test” and live mode start with prefix “sk_live“.

How to setup recurring payment method:

  1. Create Stripe Customer Method:
try
        {
          $customer= \Stripe\Customer::create([
            'id' =>'cus_1244',
            'name' => 'jou',
            'email' => 'xya.gmail.com',
            'description' => 'Customer for stripe '
       
          ]);
        }
        catch (\Exception $exception) {
          print_r($exception);exit;
        }

2 Create Stripe Plan Method

try
         {
          $stripe_plan=\Stripe\Plan::create([
          'id' => '122',
          'amount' => '222',
          'currency' => 'usd',
          'interval' => 'year', //year or month
          'product' => ['name' => 'yearly plan'],
          ['trial_period_days' => 365//Days
          
        ]);
         }
         catch (\Exception $exception) {
            print_r($exception);exit;
         }

3) Create Stripe Subscription Method

try {
            $tria_end_date=Date('Y-m-d H:i:s', strtotime("+365 days"));
               $stripe_subscription = \Stripe\Subscription::create([
                  // 'id'      =>  'sub12',
                  'customer' => 'cus_1244',
                  'items' => [['plan' => '122']],
                  'trial_end' => strtotime($tria_end_date),
                ]);
             } catch (\Exception $exception) {
               print_r($exception);exit;
             }
KEYVALUE
Publishablepk_test_LBzcjdjdsd6673jdsjdew343ncnnch34h
Secretsk_test_gaYrer3344edsdsoRfnyUZU00qmMfl3lF

Now let’s integrated stripe gateway with php codeigniter

  1. Create a class file in application\libraries\Setting.php

<?php
    class Setting
    {
        public static function config() 
        {
            return [
                'settings' => [
                    'displayErrorDetails' => true, // set to false in production
                    'addContentLengthHeader' => false, 
                    'logger' => [
                        'name' => 'slim-app',
                    ],
                    'stripe' => [
                    // You shouldn't have to touch this
                    'apiVersion' => '2019-03-14',
                    // Update this path if you want to move your public folder
                    'staticDir' => __DIR__ . '/../../public/',
                    // Adapt these to match your account payments settings
                    // https://dashboard.stripe.com/account/payments/settings
                    'paymentMethods' => [
                        'alipay', // aud, cad, eur, gbp, hkd, jpy, nzd, sgd, or usd.
                        'bancontact', // eur (Bancontact must always use Euros)
                        'card', // many (https://stripe.com/docs/currencies#presentment-currencies)
                        'eps', // eur (EPS must always use Euros)
                        'ideal', // eur (iDEAL must always use Euros)
                        'giropay', // eur (Giropay must always use Euros)
                        'multibanco', // eur (Multibanco must always use Euros)
                        // 'sepa_debit', // Restricted. See docs for activation details: 
                        'wechat' // aud, cad, eur, gbp, hkd, jpy, sgd, or usd.
                    ],
                    'publishableKey' => 'pk_test_LBzcjdjdsd6673jdsjdew343ncnnch34h',
                    'secretKey' => 'sk_test_gaYrer3344edsdsoRfnyUZU00qmMfl3lF',
                    'webhookSecret' => '',
                    'accountCountry' => 'US',
                    'shopCurrency' => 'eur',
                    'defaultCountry' => 'US'
                    ]
            
                ],
            ];
        }
    }
?>
  • 2) Create a class file in application\libraries\ Inventory .php
<?php
require FCPATH . 'vendor/autoload.php';

require_once BASEPATH.'core/CodeIgniter.php';
class Inventory
{
  // This would be a lookup in your database
  private static $products = [
    'increment2' => [
      'type' => 'good', 'name'=> 'Increment Magazine', 'attributes' => [ 'issue' ],
      'sku' => [
        'id' => 'increment-03',
        'product' => 'increment',
        'attributes' => [ 'issue' => 'Issue #3 “Development”' ],
        'price' => 399, 'currency' => 'usd',
        'inventory' => [ 'type' => 'infinite' ]
      ]
    ],
    'pins' => [
      'type' => 'good', 'name' => 'Stripe Pins', 'attributes' => [ 'set' ],
      'sku' => [
        'id' => 'pins-collector',
        'product' => 'pins',
        'attributes' => [ 'set' => 'Collector Set' ],
        'price' => 799, 'currency' => 'usd',
        'inventory' => [ 'type' => 'finite', 'quantity' => 500 ]
      ]
    ],
    'shirt' => [
      'type' => 'good', 'name' => 'Stripe Shirt', 'attributes' => ['size', 'gender'],
      'sku' => [
        'id' => 'shirt-small-woman',
        'product' => 'shirt',
        'attributes' => [ 'size' => 'Small Standard', 'gender' => 'Woman' ],
        'price' => 999, 'currency' => 'usd',
        'inventory' =>  [ 'type' => 'infinite' ]
      ]
    ]
  ];

  public static function calculatePaymentAmount($items) {
    $total = 0;
    foreach ($items as $item) {
      $total += self::getSkuPrice($item['parent']) * $item['quantity'];
    }

    return $total;
  }

  public static function listProducts($key) {
      static $cachedProducts = null;
      if ($cachedProducts) {
        return $cachedProducts;
      }
    $response= \Stripe\Stripe::setApiKey($key);
    $ids = array_keys(self::$products);
    $products = \Stripe\Product::all([ "ids" => $ids ]);
    if (count($products->data) === count($ids)) {
      $cachedProducts = self::withSkus($products);
      return $cachedProducts;
    }

    foreach (self::$products as $id => $product) {
      $p = $product;
      $p['id'] = $id;
      unset($p['sku']);
      
      \Stripe\Product::create($p);
      \Stripe\Sku::create($product['sku']);
    }

    $products = \Stripe\Product::all([ "ids" => $ids ]);
    if (count($products->data) === count($ids)) {
      $cachedProducts = self::withSkus($products);
      return $cachedProducts;
    }

    // Stripe should already have thrown an Exception but just in case
    throw new \RuntimeException("Couldn't retrieve nor create the products in Stripe.");
  }

  protected static function withSkus($products) {
    foreach ($products->data as $i => $product) {
      $products->data[$i]->skus = [ 'data' => [
          \Stripe\Sku::retrieve(self::$products[$product->id]['sku']['id'])
      ]];
    }

    return $products;
  }

  public static function getSkuPrice($id) {
    foreach (self::listProducts($key)->data as $product) {
      if ($product->skus->data[0]->id == $id) {
        return $product->skus->data[0]->price;
      }
    }

    throw new \UnexpectedValueException('Unknown sku ID. Argument passed: ' . $id);
  }

  public static function getProduct($id) {
    foreach (self::listProducts()->data as $product) {
      if ($product->id == $id) {
        return $product;
      }
    }

    throw new \UnexpectedValueException('Unknown product ID. Argument passed: ' . $id);
  }
}
  • 3) Create a class file in application\libraries\Shipping.php
<?php
class Shipping
{
  // This would be a lookup in your database
  public static $options = [
    'free' => [ 'label' => 'Free Shipping', 'detail' => 'Delivery within 5 days', 'amount' => 0 ],
    'express' => [ 'label' => 'Express Shipping', 'detail' => 'Next day delivery', 'amount' => 500 ]
  ];

  public static function getShippingOptions() {
    $shippingOptions = [];
    foreach (self::$options as $id => $option) {
      $shippingOptions[] = array_merge([ 'id' => $id ], $option);
    }
    
    return $shippingOptions;
  }

  public static function getShippingCost($id) {
    if (isset(self::$options[$id])) {
      return self::$options[$id]['amount'];
    }

    throw new \UnexpectedValueException('Unknown shipping option ID. Argument passed: ' . $id);
  }
}
?>
  • 4) Create a class file in application\controllers\Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require FCPATH . 'vendor/autoload.php';

require_once BASEPATH.'core/CodeIgniter.php';
class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('welcome_message');
	}
	public function config()
	{
		$this->load->library('Setting');
		$this->load->library('Shipping');
	
		$config=Setting::config();
		// print_r($config['settings']);exit;
		echo json_encode([
			'stripePublishableKey' => $config['settings']['stripe']['publishableKey'],
			'stripeCountry' => $config['settings']['stripe']['accountCountry'],
			'country' => $config['settings']['stripe']['defaultCountry'],
			'currency' => $config['settings']['stripe']['shopCurrency'],
			'paymentMethods' => implode($config['settings']['stripe']['paymentMethods'], ', '),
			'shippingOptions' => Shipping::getShippingOptions()
		  ]);exit;
	}
	public function products()

	{			$this->load->library('Setting');
		$config=Setting::config();
		$key=$config['settings']['stripe']['secretKey'];
		$this->load->library('Inventory');
		echo json_encode(Inventory::listProducts($key));exit;
		
	}
	public function payment_intents()
	{
		$this->load->library('Inventory');
		$this->load->library('Setting');
		$config=Setting::config();
		try {
			$data = json_decode(file_get_contents('php://input'),true); 
		$paymentIntent = \Stripe\PaymentIntent::create([
			'amount' => Inventory::calculatePaymentAmount($data['items']),
			'currency' => $data['currency'],
			'payment_method_types' => $config['settings']['stripe']['paymentMethods']
		  ]);
		  echo json_encode([ 'paymentIntent' => $paymentIntent ]);exit;
		}
		catch (\Exception $e) {
			print_r($e);exit;
		}
	}
}
?>

Add a Comment

Your email address will not be published. Required fields are marked *