2560px-Stripe_Logo-252C_revised_2016.svg.png

Create a Subscription in Stripe Payment Gateway In CodeIgniter PhP



Subscriptions are the lifeblood of Stripe Billing! The initial creation of one can be simple, using just the Subscription object, or more thorough, using both Subscription and Subscription Item.

The Stripe Subscription API provides an easy way to integrate recurring payments on the website. If you want to implement the membership subscription system on the web application, subscription payment is required for recurring billing. The Stripe payment gateway helps to integrate recurring payment with Plans and Subscription API. Stripe subscription is a quick and effective way to allow your website members to purchase a membership online using their credit cards.


We will create a stripe subscription in the following steps

1 . Get API keys from Stripe account




Step 1 :  Get API keys from Stripe account
  1. Login to your Stripe account and navigate to the Developers » API keys page.
  2. In the TEST DATA block, you’ll see the API keys (Publishable key and Secret key) are listed under the Standard keys section. To show the Secret key, click on the Reveal test key token button.
  3. Copy secret key and publish key to notepad.

Step 2:  Create a new CodeIgniter project.
  1. Inside Application -> config -> constants.php  make two new constant and paste the secret key and publish key there. 
        define('STRIPE_PUBLISHABLE_KEY', 'pk_test_####');
        define('STRIPE_SECRET_KEY', 'sk_test_####');
  1. Create a controller named Srripe.php   inside the controller folder.
  2. Create a view named  stripe_view.php  inside the view folder.
  3. Create plans.php inside the controller folder 

Step 3:  Download stripe library
  1.   Download library here  DOWNLOAD
  2.   Or download from composer   ” composer require stripe/stripe-php “
  3.   After downloading past the library into folder  application -> third_party/


Step 4:  Creating a controller ( stripe.php)

Paste the following code in stripe.php file inside the controller.

   
public function index()
{

include('plans.php');

$data['metaDescription'] = 'Stripe Manage Subscription Payment using Codeigniter';
$data['metaKeywords'] = 'Stripe Manage Subscription Payment using Codeigniter';
$data['title'] = "Stripe Manage Subscription Payment using Codeigniter - TechArise";
$data['breadcrumbs'] = array('Stripe Manage Subscription Payment using Codeigniter' => '#');
$data['plans'] = $plans;
$this->load->view('stripe_view', $data);
}

public function stripe_checkout_subscription()
{
// Retrieve stripe token and user info from the submitted form data
$token = $this->input->post('stripeToken');
$name = $this->input->post('name');
$email = $this->input->post('email');
include('plans.php');
// Plan info
$planID = $this->input->post('subscr_plan');
$planInfo = $plans[$planID];
$planName = $planInfo['name'];
$planPrice = $planInfo['price'];
$planInterval = $planInfo['interval'];

// Include Stripe PHP library

// Set API key
require_once APPPATH . 'third_party/stripe/init.php';
StripeStripe::setApiKey(STRIPE_SECRET_KEY);
// Add customer to stripe
try {
$customer = StripeCustomer::create([
'source' => $token,
'shipping' => [
'name' => 'Jenny Rosen',
'address' => [
'line1' => '510 Townsend St',
'postal_code' => '98140',
'city' => 'San Francisco',
'state' => 'CA',
'country' => 'US',
],
],
]);
} catch (Exception $e) {
$api_error = $e->getMessage();
}

if (empty($api_error) && $customer) {

// Convert price to cents
$priceCents = round($planPrice * 100);

// Create a plan
try {
$plan = StripePlan::create(array(
"product" => [
"name" => $planName
],
"amount" => $priceCents,
"currency" => $currency,
"interval" => $planInterval,
"interval_count" => 1
));
} catch (Exception $e) {
$api_error = $e->getMessage();
}



if (empty($api_error) && $plan) {
// Creates a new subscription
try {
$subscription = StripeSubscription::create(array(
"customer" => $customer->id,
"items" => array(
array(
"plan" => $plan->id,
),
),
"coupon" => 'free-period',
));
} catch (Exception $e) {
$api_error = $e->getMessage();
}

print_r($subscription);
}
}
}
}





Step 4:  Creating plans (plans.php)

Paste the following code in plans.php file inside the controller.

    array( 
'name' => 'Weekly Subscription',
'price' => 25,
'interval' => 'week'
),
'2' => array(
'name' => 'Monthly Subscription',
'price' => 85,
'interval' => 'month'
),
'3' => array(
'name' => 'Yearly Subscription',
'price' => 950,
'interval' => 'year'
)
);
$currency = "INR";

Step 4:  Creating view (stripe_view.php)

Paste the following code in the stripe_view.php file inside the view folder.



<script src="https://js.stripe.com/v3/"></script>

<div class="panel">
    <form action="<?php echo site_url('stripe/stripe_checkout_subscription') ?>" method="POST" id="paymentFrm">
        <div class="panel-heading">
            <h3 class="panel-title">Plan Subscription with Stripe</h3>
            <!-- Plan Info -->
            <p>
                <b>Select Plan:</b>
                <select name="subscr_plan" id="subscr_plan">
                    <?php foreach($plans as $id=>$plan){ ?>
                        <option value="<?php echo $id; ?>"><?php echo $plan['name'].' [$'.$plan['price'].'/'.$plan['interval'].']'; ?></option>
                    <?php } ?>
                </select>
            </p>
        </div>
        <div class="panel-body">
            <!-- Display errors returned by createToken -->
            <div id="paymentResponse"></div>
            <!-- Payment form -->
            <div class="form-group">
                <label>NAME</label>
                <input type="text" name="name" id="name" class="field" placeholder="Enter name" required="" autofocus="">
            </div>
            <div class="form-group">
                <label>EMAIL</label>
                <input type="email" name="email" id="email" class="field" placeholder="Enter email" required="">
            </div>
            <div class="form-group">
                <label>CARD NUMBER</label>
                <div id="card_number" class="field"></div>
            </div>
            <div class="row">
                <div class="left">
                    <div class="form-group">
                        <label>EXPIRY DATE</label>
                        <div id="card_expiry" class="field"></div>
                    </div>
                </div>
                <div class="right">
                    <div class="form-group">
                        <label>CVC CODE</label>
                        <div id="card_cvc" class="field"></div>
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-success" id="payBtn">Submit Payment</button>
        </div>
    </form>
</div>
<script>
// Create an instance of the Stripe object
// Set your publishable API key
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');

// Create an instance of elements
var elements = stripe.elements();

var style = {
    base: {
        fontWeight: 400,
        fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
        fontSize: '16px',
        lineHeight: '1.4',
        color: '#555',
        backgroundColor: '#fff',
        '::placeholder': {
            color: '#888',
        },
    },
    invalid: {
        color: '#eb1c26',
    }
};

var cardElement = elements.create('cardNumber', {
    style: style
});
cardElement.mount('#card_number');

var exp = elements.create('cardExpiry', {
    'style': style
});
exp.mount('#card_expiry');

var cvc = elements.create('cardCvc', {
    'style': style
});
cvc.mount('#card_cvc');

// Validate input of the card elements
var resultContainer = document.getElementById('paymentResponse');
cardElement.addEventListener('change', function(event) {
    if (event.error) {
        resultContainer.innerHTML = '<p>'+event.error.message+'</p>';
    } else {
        resultContainer.innerHTML = '';
    }
});

// Get payment form element
var form = document.getElementById('paymentFrm');

// Create a token when the form is submitted.
form.addEventListener('submit', function(e) {
    e.preventDefault();
    createToken();
});

// Create single-use token to charge the user
function createToken() {
    stripe.createToken(cardElement).then(function(result) {
        if (result.error) {
            // Inform the user if there was an error
            resultContainer.innerHTML = '<p>'+result.error.message+'</p>';
        } else {
            // Send the token to your server
            stripeTokenHandler(result.token);
        }
    });
}

// Callback to handle the response from stripe
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);
    // Submit the form
    form.submit();
}
</script>


Step 4:  Run the code and use the following card details

To test the Stripe subscription payment API integration, use the following test card numbers, a valid future expiration date, and any random CVC number.

  • 4242424242424242 – Visa
  • 4000056655665556 – Visa (debit)
  • 5555555555554444 – Mastercard
  • 5200828282828210 – Mastercard (debit)
  • 378282246310005 – American Express
  • 6011111111111117 – Discover

Tags: No tags

Leave A Comment

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