Developers

Integrate mobile payments and monetize with Mocopay

Our developer center provides all the details for a simple and smooth integration so you could easily add mobile payments with Mocopay.

Integration instructions

After performing mandatory preconditions to integrate Mocopay into your website, you need to do following:

  • Ensure JQuery reference inside your project (minimal version 1.11).
  • Add payment initialization button. For doing this step you can choose simple (recommended) or advanced initialization integration model which are both explained below.
  • Handle callback redirect from Mocopay and optionally listen for payment notifications to get final payment status before you give content to the user.

Simple payment initialization

This is the most simple mode of using Mocopay WEB library. Before you start, you need to have following:

  • payment.all.min.js script which is available in web library package distributed by Mocopay and you have to put it on your web server
  • product code and Api URL which you receive in control box on final step of service creation
  • predefined signature which you can copy/paste from the initPayment example in last step of service creation in control box

To initialize the snippet you need to place the following code just before the closing HTML body tag:

<script src="dist/js/payment.all.min.js"></script>

To render the payment button somewhere inside your page create a simple HTML div element with all required parameters, final result should look like this:

<div class="spgw-widget" data-spgw-url="http://path/to/payment-gateway/" data-spgw-pid="YourProductID" data-spgw-mode="direct" data-spgw-reference-id="WhatEverYouWantID" data-spgw-signature="PRE-GENERATED-SIGNATURE"><img src="http://www.mocopay.com/app/uploads/2015/03/mocopay_green_medium.png" alt="Pay By Mocopay" border="0" /></div>

DIV element that forms the payment button needs to have spgw-widget class and also following mandatory parameters:

  • data-spgw-url path to the payment gateway,
  • data-spgw-pid parameter which is product code received when your service is created in control box,
  • data-spgw-mode parameter with value direct is specified when you are using pregenerated signature
  • data-spgw-reference-id which is optional free form parameter, forwarded to you in callback URL and also in all payment notifications,
  • data-spgw-signature parameter, which holds mandatory security signature (in this case simpliest form is available and pregenerated in control box for each payment product).

To add extra flavor to your payment buttons, you can choose any of available Mocopay buttons images. Select the one that suits your page style the best!

Advanced payment initialization

In advanced mode of using Mocopay WEB library you can send additional parameters with payment initialization request. It is useful to send those extra parameters since they enable optimized payment process (e.g. if you send end users prefered language, Mocopay payment form will adopt its text acording to it). In advanced integration is also recommended to use PHP Client with proxy which will help you to handle callbacks and notifications and route all requests to the payment gateway. Before you start, you need to have following:

  • payment.all.min.js script  and PHP client which are available in web library package distributed by Mocopay and you have to put it on your web server
  • product code and Api Url which you receive in control box on final step of service creation
  • Api Key and Api Secret which you also receive in control box on final step of service creation and which you will use for calculating mandatory signature string.

To initialize the snippet you need to place the following code just before the closing HTML body tag:

<script src="dist/js/payment.all.min.js"></script>

In advanced integration it is recommended to include PHP client because PHP Client with proxy script will help you to generate signature and make HTTP request to the payment gateway. The proxy script can easily be setup following this simple tutorial:

  1. You need to download Mocopay WEB library from control box  and add this library into your web site
  2. You need to create PHP file and then add below code into it where url parameter is url to the payment gateway, api_key and api_secret values you need to replace with values which you have received when your service is created in control box.
<?php
require_once 'dist/php/vendor/autoload.php';
// First we need a payment client
$pgw = new Samurai\Payment\Client(array(
'url' => 'http://paymentapi.nth.ch/v1/payment/',
'api_key' => 'API_KEY',
'api_secret' => 'API_SECRET'
));
/ The simply pass the client to the proxy and boot it up
// Script will detect all sent parameters defined via data- attributes
$proxy = new Samurai\Payment\ProxyMode($client);
if ($response = $proxy->doAction()) {
$proxy->respond($response);
}

DIV element that forms the payment button needs to have spgw-widget class and also following mandatory parameters:

  • data-spgw-url parameter to the proxy endpoint
  • data-spgw-pid parameter which is product code received when your service is created in control box,
  • data-spgw-reference-id which is optional free form parameter, forwarded to you in callback URL and also in all payment notifications,

To add extra flavor to your payment buttons, you can choose any of available Mocopay buttons images. Select the one that suits your page style the best!

In advanced usage is possible to add optional parameters to the button with the goal to optimize payment flow and to improve your conversions by giving us more information about the user ( NOTE: when using additional parameters you need to calculate signature with all parameters mandatory and extra parameters, those extra parameters are:

Parameter Description

data-spgw-callback-url

Callback URL where user will be returned after purchase. Default value can be set in control box, you can override it here if necessary.

data-spgw-mcc

Mobile country code of the user

data-spgw-mnc

Mobile network code of the user

data-spgw-user-id

Buyer identifier set by customer (custom value that uniquely identify this user in your system)

data-spgw-phone

Buyer mobile phone number (if available to a customer)

data-spgw-client-ip

Buyer IP address

data-spgw-lang

Preferred language code (ISO 639-1)

data-spgw-notify-url

Notification URL for payment notifications, overrides default one configured in control box

data-spgw-image-url

Product image URL used for payment forms, overrides the one set in control box

data-spgw-mode

Parameter could have two values: proxy and direct. If proxy is selected then data-spgw-url should point to your proxy. If direct is selected then you must provide the data-spgw-signature parameter

data-spgw-redirect-callback

Callback URL wher user will be returned after purchase. Default value can be set in control box, you can override it here if necessary.

data-spgw-country

Country ISO 2 code

data-spgw-modal

Set to 1 or 0 to enable opening the payment URL inside a modal dialog (default 1)

data-spgw-modal-min-width

Minimal width of modal window in pixels (default 300)

data-spgw-modal-min-height

Minimal height of modal window in pixels (default 500)

data-spgw-modal-max-width

Maximum width of modal window in pixels (default 600)

data-spgw-modal-max-height

Maximum height of modal window in pixels (default 500)

data-spgw-modal-fullscreen

If true, modal window will always be 100% width and height of screen (default false)

data-spgw-modal-fade-speed

Transition duration for modal in milliseconds (default 300)

data-spgw-modal-overlay

Modal window fullscreen semitransparent background( all valid css background properties accepted, default rgba(0,0,0,0.5))

data-spgw-modal-background

Modal window background( all valid css background properties accepted, default #FFF)

data-spgw-modal-box-shadow

Modal window box shadow( all valid css box-shadow properties accepted, default 0px 1px 5px #000)

data-spgw-modal-loader

Show loading gif on modal window transitions( default true )

data-spgw-modal-loader-url

Custom loading gif path( default is the mocopay hosted mocopay loading gif http://v1.c1-cd1.net/a685be2aa1b54abe8d981e23b776bee3/Mocopay.1/Images/ring.gif)

data-spgw-modal-loader-size

Custom loading gif size in pixels( all valid css background-size properties accepted, default is 95px 95px ) The practice is to provide a loading gif that is double the size of the loader size defined, so it would look good on retina screens.

data-spgw-debug

Puts our script in debug mode, logging some usefull information in browser console. (default false)

So a more advanced code example would look like this:

<div class="spgw-widget" data-spgw-url="http://path/to/proxy-endpoint/" data-spgw-pid="PP40951367" data-spgw-reference-id="MyUniqueId" data-spgw-callback-url="http://path/to/callback/" data-spgw-mcc="210" data-spgw-mnc="01" data-spgw-country="HR" data-spgw-notify-url="&amp;quot;http://path/to/notify/"><img src="http://www.mocopay.com/app/uploads/2015/03/mocopay_green_medium.png" alt="Pay 2.00" border="0" /></div>

Handling callback redirect and finalizing payment

When payment is finalized user is returned to yours callback URL given in control box configuration or above with payment initialization as additional parameter. In any case you can trace the result of the payment by reading parameters which are delivered to you in callback URL request.

Redirection parameters:

Parameter Description

requestId

Payment initialization request ID.

sid

Payment session ID.

sessionId

Payment session ID.

referenceId

referenceId sent by service provider in initPayment request

status

Status of executed payment session (status list is available in payment notifications chapter).

 

Example of redirection to custom callbackUrl when payment is complete sucessfully:

HTTP/1.1 302 Found
Location: http://www.client.com/app1?requestId=9bf849fd215542088fa5c98b99a185a2&sid=8903cf28aa3940f0b31d699fea5aa7ff&sessionId=8903cf28aa3940f0b31d699fea5aa7ff&referenceId=testuser&status=PaymentComplete

In addition to reading callback URL parameters it is recommended to handle payment notifications sent by Mocopay to yours backend server, especially to get final payment notification since user can close payment forms before actual payment finishes (e.g. premium SMS message is being delivered to his phone). 

It is highly recommended to use PHP client which will help you to handle callbacks and notifications. For handling callbacks with PHP client you need to create PHP file and add below code into it

require_once 'dist/php/vendor/autoload.php';
 // First we need a payment client

$client = new Samurai\Payment\Client(array(
     'url' => 'http://paymentapi.nth.ch/v1/payment/',
     'api_key' => 'API_KEY',
     'api_secret' => 'API_SECRET'
));
$handleRedirect = new Samurai\Payment\Handle\CallbackRedirect($client);

// Check if redirect parameter are valid
if ($handleRedirect->isValid()) {
// Verify session
if ($session = $handleRedirect->verifySession()) {
// Use session object to retrieve all informations you want to (All parameters are described on http://www.mocopay.com/developers/payment-notifications-web-sdk/)

if($session->getStatus()->isPaymentComplete()) {
// With referenceId you could match your user or/and product or whatever else you want
$referenceId = $session->getReferenceId();
echo "Payment Successful for " . $referenceId;
// Do your stuff
} else {
echo $session->getStatus()->getMessage();
}
} else {
// payment verification failed
}
} else {
// Redirect handling not implemented on proper action or callback redirect GET parameters are invalid
}

 For handling notifications with PHP client you need to create PHP file and add below code into it

require_once 'dist/php/vendor/autoload.php';
// First we need a payment client

$client = new Samurai\Payment\Client([
     'url' => 'http://paymentapi.nth.ch/v1/payment/',
     'api_key' => 'API_KEY',
     'api_secret' => 'API_SECRET'
]);

// Initialize notifications handler
$notification = new Samurai\Payment\Handle\Notification($client);

if ($notification->isValid()) {
echo "Notification with status message:" . $notification->getStatus()->getMessage();

if ($notification->isSessionNotification()) {
   echo "This is session notification";
   $session = $notification->verifySession();
   
   if ($session) {
     // Do your own stuff here
    
      $status = $session->getStatus();

      if ($status->isPaymentComplete()) {
      // Payment is complete
         $phone = $session->getEndUser()->getPhone();
         $pid = $notification->getPid();
         $amount = $notification->getChargedAmount();
         $paymentTIme = $notification->getTimePayment();
         // For all parameters check http://www.mocopay.com/developers/payment-notifications-web-sdk/
       } elseif ($status->isPaymentPartial()) {
        // Payment is partial, please handle this case carefully
       } else {
         // Payment is with some other status, show message from Payment Gateway
         // Additionally you could check which status it is: e.g $notification->getStatus()->isError(), ...
         echo $status->getMessage();
       }
    } else {
    // payment Session not verified
    }
} else {
   echo "This is transaction notification";
   // Do same thing here if you want handle transaction notification
   $transaction = $notification->verifyTransaction();

   if ($transaction) {
      // Transaction valid
    } else {
      // payment transaction not valid
   }
 }
} else {
    echo 'Current HTTP request is not valid notification from Payment Gateway.';
}