Razorpay Subscription or subscription in Razorpay Payment Gateway integration is not so easy if you want to implement it in your custom project rather than WordPress, Shopify or any other e-commerce platform.
There are many plugins available for e-commerce platforms, but here we will integrate Razorpay Subscription / Recurring Payment in CodeIgniter.
STEP 1:
Go to Razorpay Dashboard and create a ‘Plan’.
Subscriptions -> Plans
STEP 2:
Create a view file in CodeIgniter view: application/views/subscription.php and paste the given code below in that file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Razorpay Subscription</title> </head> <body> <div id="container"> <div id="FormErr" style="width:100%;"></div><br> <h2>PLAN : 799</h2> <p>(Plan Created with the same Amount on Razorpay Dashboard)</p> <input type="text" id="full_name" placeholder="Type your Full name"> <input type="text" id="pay_email" placeholder="Type your Email"> <input type="text" id="pay_phone" placeholder="Type your Mobile Number"> <textarea id="pay_address" >Type your Address</textarea> <button class="btn-main mybtn1 cmn-btn" id="razor-subscription-pay-now">Subscribe</button> </div> <div class="subscribe-loader">Wait...</div> <span id="render-subscription-pay-info"></span><!-- Required DIV--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ jQuery(document).on('click', '#razor-subscription-pay-now', function () { jQuery('.subscribe-loader').show(); $full_name = $('#full_name').val(); $pay_email = $('#pay_email').val(); $pay_phone = $('#pay_phone').val(); $pay_address = $('#pay_address').val(); jQuery.ajax({ url: '<?php echo base_url(); ?>home/initiateSubscriptions', type: 'post', data: { full_name: $full_name, pay_email: $pay_email, pay_phone: $pay_phone, pay_address: $pay_address }, dataType: 'json', beforeSend: function () { //jQuery('#razor-subscription-pay-now').button('loading'); }, complete: function () { //jQuery('#razor-subscription-pay-now').button('reset'); }, success: function (json) { $('.text-danger').remove(); jQuery('.subscribe-loader').hide(); if (json['error']) { for (i in json['error']) { $('#FormErr').append('<small class="text-danger" style="float:left;">' + json['error'][i] + '</small>'); } } else { jQuery.ajax({ url: '<?php echo base_url(); ?>home/createSubscription', type: 'post', data: { full_name: $full_name, pay_email: $pay_email, pay_phone: $pay_phone, pay_address: $pay_address }, dataType: 'html', success: function (html) { jQuery('span#render-subscription-pay-info').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); }); </script> <style> #FormErr small{width:100%; display:inline-block;} #FormErr small.text-danger{color:red;} .subscribe-loader{background:#fff; position:fixed; top:0; bottom:0; left:0; right:0; display:none; text-align: center;} </style> </body> </html> |
STEP 3:
Create a view file in CodeIgniter Controller: application/controllers/Home.php and paste the given code below in that file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends CI_Controller { public function __construct(){ error_reporting(0); parent::__construct(); $this->load->library(array('form_validation','session','cart')); //$this->load->database(); } public function index(){ $this->load->view('index'); } public function initiateSubscriptions() { $json = array(); $firstName = $this->input->post('full_name'); $email = $this->input->post('pay_email'); $contactNum = $this->input->post('pay_phone'); $address = $this->input->post('pay_address'); if (empty($firstName)) { $json['error']['fullname'] = 'Please enter full name.'; } if (empty(trim($email))) { $json['error']['email'] = 'Please enter valid email.'; } else if (!preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)) { $json['error']['email'] = 'Please enter valid email.'; } if (empty(trim($contactNum))) { $json['error']['contactno'] = 'Please enter valid contact no.'; } else if (strlen($contactNum) < 7 || !is_numeric($contactNum)) { $json['error']['contactno'] = 'Please enter valid contact no.'; } if (empty($address)) { $json['error']['address'] = 'Please enter address'; } if(empty($json['error'])){ $planID = 'plan_JDgG3Q5GGeusiL'; // CReate From Razorpay Dashboard, Subscriptions->Plans // $note = 'CodyPaste Write Anything'; //$offer_id = 'offer_Ky3C9fbr3qg4Ju'; // Not mandatory, but if you have any offer in Razorpay Dashboard, you can mention here. // $subscriptionData = array( 'plan_id' => $planID, 'customer_notify' => 1, 'total_count' => '1000', /*'addons' => array ( 0 => array ( 'item' => array ( 'name' => 'Coupon Discount', 'amount' => '500', 'currency' => 'INR', ), ), ),*/ 'offer_id'=> $offer_id, 'notes' => array( 'name' => $note, ), ); $ch = $this->get_curl_handle_subscriptions($subscriptionData); // Method/Function created below with Razorpay Key and Secret // $result = curl_exec($ch); //print_r($result); die(); $data = json_decode($result); $json['subscription_id'] = $data->id; $json['plan_id'] = $data->plan_id; // store value in session $this->session->set_userdata( array( 'subscription_id' => $data->id, 'plan_id' => $data->plan_id, 'created_at' => $data->created_at, 'charge_at' => $data->charge_at, 'start_at' => $data->start_at, 'offer_id' => $data->offer_id, ) ); } $this->output->set_header('Content-Type: application/json'); echo json_encode($json); } // initialized cURL Request subscription private function get_curl_handle_subscriptions($subscriptionData) { $url = 'https://api.razorpay.com/v1/subscriptions'; $key_id = 'rzp_test_PgK1AWmEYNiWMd'; // Generate from Razorpay Dashboard, Setting -> API Keys $key_secret = '6jP4b9WrnKt5JDyDMmJH7zdE'; // Generate from Razorpay Dashboard, Setting -> API Keys //cURL Request $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, $key_id . ':' . $key_secret); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_POST, 1); $data = $subscriptionData; $params = http_build_query($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); return $ch; } // create subscription first time public function createSubscription() { $fullName = $this->input->post('full_name'); $email = $this->input->post('pay_email'); $contactNum = $this->input->post('pay_phone'); $address = $this->input->post('pay_address'); $totalamount = '100'; $productinfo = 'ORDERID-01'; $surl = base_url().'subscription-thankyou'; $furl = base_url().'subscription-failed'; $orderid = 'ORD-01'; $dataFlesh = array( 'txnid' => time(), 'card_holder_name' => $fullName, 'amount' => $totalamount, 'email' => $email, 'phone' => $contactNum, 'productinfo' => $productinfo, 'surl' => $surl, 'furl' => $furl, 'currency_code' => 'INR', 'order_id' => $orderid, 'lang' => 'en', 'store_name' => 'Cody Paste', 'return_url' => site_url() . 'home/callbacksubscriptions', 'payment_type' => 'create_subscriptions', 'subscription_id' => $this->session->userdata('subscription_id'), // Session craeted at 'initiateSubscriptions()' 'plan_id' => $this->session->userdata('plan_id'), 'created_at' => $this->session->userdata('created_at'), 'charge_at' => $this->session->userdata('charge_at'), 'date_end_plan_at' => strtotime("+10 years", $this->session->userdata('charge_at')), 'start_at' => $this->session->userdata('start_at'), 'package' => 'CodyPaste Subsription', 'price' => '100', 'package_plan_id' => 'plan_JDgG3Q5GGeusiL', 'package_type' => 'Monthly', // it could be 'Days' 'offer_id' => $this->session->userdata('offer_id'), // Session craeted at 'initiateSubscriptions()' ); $this->session->set_userdata('subscription_ci_seesion_key', $dataFlesh); $payInfo = $dataFlesh; $json['payInfo'] = $payInfo; $json['msg'] = 'success'; //$this->output->set_header('Content-Type: application/json'); $this->load->view('Razorpay-Hidden-Form', $json); //--END --> //--======-----After that You can Insert in Database table for creating order from below === --> //---- } // callback method public function callbacksubscriptions() { if (!empty($this->input->post('razorpay_payment_id')) && !empty($this->input->post('merchant_order_id'))) { $success = true; $error = ''; try { // store temprary data $dataFlesh = array( 'txnid' => $this->input->post('merchant_trans_id'), 'card_holder_name' => $this->input->post('card_holder_name_id'), 'productinfo' => $this->input->post('merchant_product_info_id'), 'surl' => $this->input->post('merchant_surl_id'), 'furl' => $this->input->post('merchant_furl_id'), 'order_id' => $this->input->post('merchant_order_id'), 'razorpay_payment_id' => $this->input->post('razorpay_payment_id'), 'merchant_subscription_id' => $this->input->post('merchant_subscription_id'), 'merchant_amount' => $this->input->post('merchant_amount'), 'merchant_plan_id' => $this->input->post('merchant_plan_id'), 'created_at' => time(), ); $this->session->set_flashdata('paymentInfo', $dataFlesh); $this->session->set_userdata('paymentInfoReturn', $dataFlesh); } catch (Exception $e) { $success = false; $error = 'Request to Razorpay Failed'; } if ($success === true) { if (!empty($this->session->userdata('ci_subscription_keys'))) { $this->session->unset_userdata('ci_subscription_keys'); } if (!empty($order_info['order_status_id'])) { redirect($this->input->post('merchant_surl_id')); } else { redirect($this->input->post('merchant_surl_id')); } } else { redirect($this->input->post('merchant_furl_id')); } } else { echo 'An error occured. Contact site administrator, please!'; } } public function subscription_thankyou(){ echo'Thankyou For Subscription<br>'; echo 'Subscription ID: '.$this->session->userdata('subscription_id'); } public function subscription_failed(){ echo'Sorry! Try Again.'; } } |
[ DOWNLOAD ]