How To Use Stripe Card Payments With Ionic (PHP Backend)

In this article we will explore how to integrate Stripe payment checkouts with your Ionic application. As with many other Ionic tutorials on this website, we will assume that you are using a variant of Ionic v.1x and have a PHP-backend or LAMP server to enable backend communication with the Stripe payment API. Please note that it is not currently possible to use Stripe Card payments without a backend (Ionic front-end only) unless you use a third-party service. 

Getting Started

For the purposes of this tutorial, we will be using the following resources, accessed in April 2017:

We will start  by adding the necessary dependencies to our Ionic application. Personally, I found that using Bower to install external packages was far more integrated and easier than NPM with Ionic projects. But, if you have a preference to use NPM (node package manager), you are welcome to do so.

Install the angular-stripe plugin by bendrucker using Bower by navigating to your Ionic project in the command line and then enter the command:

bower install --save-dev angular-stripe

Now head over to the www/index.html file in your Ionic project and add the references to the angular-stripe library as well as the Stripe API. At the time of writing the Stripe API v3 only supports Stripe Elements, so this tutorial will be using v2. Be sure to include to include the references in the correct order of dependency. The head of the index.html should now look something like this:

<head>
...
<!-- Stripe -->
<script src="https://js.stripe.com/v2/"></script>
<script src="lib/angular-stripe/release/angular-stripe.js"></script>

<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
...
</head>

Then inject the angular-stripe dependency in to the application. Do to this, locate the application’s module declaration (usually found in the www/js/app.js file) and add the dependency angular-stripe. The app module declaration should now look similar to this:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'angular-stripe'])

Finally, to complete the configuration, set your unique API key so that the Stripe API can determine which account to send the money to. To do this you’ll need to obtain your Stripe Publishable Key from here. Then, open the app.js file located in the www/js/ directory and add the following code inside the app.config() declaration as follows:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'angular-stripe'])

.config(function($ionicConfigProvider, stripeProvider) {
    stripeProvider.setPublishableKey('your_api_key_here');
})

Note that you will need to inject stripeProvider in to the function argument for the module config as seen above. Remember to replace your API key in the code snippet above, otherwise all calls to Stripe will fail.

That’s configuration out of the way, now lets gather payments details to charge our customers.

Creating a Stripe payment token in our payment controller

In order to make a charge to a credit card, Stripe requires you to first authenticate the payment details by making a request to the API. Your request to the API will return a unique token which then needs to be sent to Stripe via a backend implementation to make the charge.

How you decide to collect payment information is completely up to you. In this example, we will hard-code the payment details, but they can easily be extracted from the user’s profile if your application supports this feature. Alternatively you can create input fields bound to a variable on the $scope using ng-model to allow your user to enter their payment credentials before checking out.

For this tutorial, the values will simply be hard-coded in to our controller.

Open your payment or checkout controller. We will be using an example controller called CheckoutCtrl.

Inject the stripe service and $http service in to the controller as follows:

.controller('CheckoutCtrl', function($scope, $http, stripe) {
    // controller logic goes here
}

The stripe service will give us access to the Stripe API via the angular-stripe plugin, and the $http service will allow us to make a HTTP call to our backend (implemented later) to charge the payment.

To charge a card, we first need to collect the payment details. As mentioned above, these will be hard-coded for this tutorial, but there is no reason why you cannot dynamically retrieve the values entered in to an input filed bound to the scope. In order to do this, we can create a variable in our controllers as follows:

var cardDetails = {
    number: 4242424242424242,
    cvc: 123,
    exp_month: 06,
    exp_year: 19,
    address_zip: 'E12 3HU'
};

Next we will send these details to the Stripe API to create a unique token used to make the charge. This can be done by calling the following method on the stripe service:

stripe.card.createToken(cardDetails)
.then(function (response) {
    console.info('token created for card ending in ', response.card.last4);
},
function (error) {
    console.warn("failed to generate token from Stripe", error);
});

The token we are interested in is located in the returned response.id object, and this is what we will use to make the charge to the credit card in the next section.

Sending data to the PHP backend to make a charge

Before we get to implementing our PHP backend, we can implement the call from Angular. To do this, we can modify the code snippet above to include a HTTP POST Request.

Let’s say that the backend PHP script will be a file located at https://www.technouz.com/demo/stripePayment.php, so this is the URL we will make our HTTP call to. Depending on how complex our system needs to be, we can pass many variants of data objects. To keep this tutorial short(er) and sweet(er) we will only pass the minimum parameters required: the single-use token and the payment amount.

First, we will need to add a payment object to our controller which contains the token and payment amount. Then, we will need to pass it to a $http.post() request which calls our stripePayment.php

The updated code in our controller should now look something like this:

stripe.card.createToken(card)
.then(function (response) {
    console.info('token created for card ending in ', response.card.last4);
      
    var payment = {
        token: response.id,
        price: 10,
    }
    
    return $http.post("https://www.technouz.com/demo/stripePayment.php", payment, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(function(response) {
        console.log('successfully submitted payment for £', payment.price);
    },
    function (error) {
        console.warn("failed to call stripePayment.php", error);
    });
},
function (error) {
    console.warn("failed to generate token from Stripe", error);
});

This code can be placed in a function which is executed when the Checkout or Pay button is clicked. It will first generate a token using stripe.card.createToken() and then immediately make the call to our backend if a token has been successfully generated.

The beauty with tokenized payments by Stripe is that the token can be stored and used to charge the card at a later date. This may be useful if you would rather prefer the card upon dispatch of an item, product or service. However, you must remember that the token is valid for a single use.

Creating a backend to charge the card

The reason I chose to use PHP for the backend in this tutorial is that it is really simple to setup and get running. All you really need is a LAMP server to execute PHP code, and there is no need to set up an entire project. Of course, this may impact the security of your system, but for demo purpose this shouldn’t really pose an issue.

Using the Stripe API PHP docs for guidance we can easily build a PHP script which will take the token and payment amount and charge the card.

We need to start by downloading the Stripe PHP library. This can be done via Composer which is a PHP package management tool, or manually by downloading the source files from here, and including them alongside the stripePayment.php file. To avoid relying on additional tools that readers of this tutorial may not be familiar with, I will manually download the Stripe PHP library and include it in a directory alongside the stripePayment.php file.

The directory at https://www.technouz.com/demo/ now looks like this:

+ demo
    - stripe
    - stripePayment.php

One difference between using Composer and manually including the Stripe PHP library is that to include the Stripe library you have to use require_once('../stripe/init.php'); instead of require_once('vendor/autoload.php');.

The contents of the stripePayment.php backend file we can use for this tutorial will look like this:

<?php
    header('Content-type: application/json');
    header("Access-Control-Allow-Origin: *");

    require_once('../stripe/init.php');

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $postdata = file_get_contents("php://input");
         $request = json_decode($postdata);
         $token = $request->token;
         $price = (intval($request->price))*100;

         $stripe = array(
             "secret_key" => "your_secret_key_here",
             "publishable_key" => "your_publishable_key_here"
         );
         
         \Stripe\Stripe::setApiKey($stripe['secret_key']);
 
         $customer = \Stripe\Customer::create(array(
             'email' => 'ashrafmahmood776@gmail.com',
             'source' => $token
         ));

         $charge = \Stripe\Charge::create(array(
             'customer' => $customer->id,
             'amount' => $price,
             'currency' => 'gbp'
         ));

         json_encode("Success!");
     }
?>

Be sure to replace your secret key and publishable key as found in your Stripe account developer dashboard.

The above code does the following:

  • Sets the content-type to JSON as I find this has the best compatibility with Angular/Ionic
  • Sets Access-Control-Allow-Origin to all domains
  • Imports the Stripe PHP library
  • Decodes the data POSTED to the service from our Angular/Ionic controller and stores them as local PHP variables
  • Creates the relevant Stripe Customer object and then creates a Stripe Charge object which also makes the charge
  • Prints ‘Success!’ if the payment was successful

With the code implemented sever-side, run your Ionic application and execute the code we placed in the controller. If you have placed the code in a function which executes when a button is clicked, then click the button! Check your Console window for a success message. You should now be able to login to your Stripe vendor dashboard to view the test payments. If you used your test Publishable Key, you’ll need to turn on Test Data to view the test payments.

Please note that this tutorial is significantly shorter than the recommended implementation for a live system. For example, in the United Kingdom, card payments should also collect the full billing address for verification and fraud prevention purposes. Making these changes to the code above is very simple, and largely only requires the developer to make use of additional functions and variables provided by the libraries and APIs already used in this project. Please ensure to read the Stripe API Documentation for full details.

Share on Facebook1Tweet about this on TwitterShare on Google+0Share on Reddit4Share on LinkedIn0Email this to someone

Subscribe to Email Updates