Create Payments Using OPay Cashier

Throughout this page, you will learn how to create payments using our OPay Cashier plugin. In this page you will learn how to:

  • Collect your client's order information.
  • Trigger OPay Cashier API with your collected order information.
  • Handling OPay Cashier API Response.
  • Redirect your client to OPay Cashier Checkout Page.
  • Handling OPay Cashier Checkout Page Returned Payment Processing Information.

Collect your Client's Order Information

Once your client's order is ready, you will need to present your own payment details form. This form should collect:

  • Client Information: Name, Phone, E-mail, Shipping Address.
  • Order Information: Product, Quantity, Unit Price, Order Amount.

Once you have collected the required information, pass them to your server so your application can trigger OPay Cashier Plugin.

...

OPay Cashier Create Payment

To get started with OPay Cashier, you need to call the create cashier payment API. In case you are still in development phase, you will need to call create cashier payment API using POST method at the following staging endpoint API point URL

                    
                        https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create
                    
                

Once you have a fully tested payment flow and you are ready for production, you should use the following production API endpoint URL instead

                    
                        https://api.opaycheckout.com/api/v1/international/cashier/create
                    
                

Cashier Create Payment API HTTP POST Parameters

Your request should contain:
  1. Header:
    • Bearer PublicKey: Your OPay merchant account Public Key.
    • merchant ID: Your OPay account merchant ID.
  2.                         
                                Authorization: Bearer {PublicKey}
                                MerchantId   : 256612345678901
                            
                        
  3. Json object containing the payment information:
  4.                     
                            {
                                "country": "EG",
                                "reference": "983541354",
                                "amount": {
                                    "total": 400,
                                    "currency": "EGP"
                                },
                                "returnUrl": "https://your-return-url",
                                "callbackUrl": "https://your-call-back-url",
                                "cancelUrl": "https://your-cacel-url",
                                "expireAt":300,
                                "userInfo":{
                                        "userEmail":"test@email.com",
                                        "userId":"userid001",
                                        "userMobile":"+201088889999",
                                        "userName":"David"
                                },
                                "productList":[
                                    {
                                        "productId":"productId",
                                        "name":"name",
                                        "description":"description",
                                        "price":100,
                                        "quantity":2,
                                        "imageUrl":"https://imageUrl.com"
                                    }
                                ],
                                "payMethod":"BankCard"
                            }
                        
                    

Detailed description of the parameters that you need to incorporate into your POST request are given in the table below.

Parameter type required Description
reference String required the unique merchant payment order number.
country String required Country Code. See full list here
amount
total long required Amount(cent unit).
currency String required Currency type.See full list here
callbackUrl String optional If you have sent callbackUrl through API, OPay will send callback notification to this callbackUrl. If you didn't send callbackUrl through API, you need to configure webhook url on the merchant dashboard, and OPay will send callback notification to this webhook url. See callback here
returnUrl String required The URL to which OPay cashier should return your client to after the checkout process.
productList
(Array)
productId String required order product ID.
name String required order product name.
description String required order product description.
price Integer required order product price.
quantity Integer required order product quantity.
imageUrl String optional order product imageUrl.
cancelUrl String optional The URL to which OPay cashier should return your client in case of canceled payment.
userClientIP String optional user ip.
expireAt integer optional Payment expiration time in minutes.(default 30)
payMethod String optional The preferred payment method to be presented to your customer. See available options here. If not set, all supported payment methods will be available to your customer to choose from.
userInfo
userId String optional the customer user id
userName String optional the customer user name
userMobile String optional the customer user mobile
userEmail String optional the customer user email
product
name String optional Product name.
description String optional Product description.

An example call of cashier create payment with an amount of 4EGP is given below.

                        
                            class CashierCreateController
                            {
                                private $publickey;
                                private $merchantId;
                                private $url;

                                public function __construct() {
                                    $this->merchantId = '256621051120756';
                                    $this->publickey = 'OPAYPUB*************54133';
                                    $this->url = 'https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create';
                                }

                                public function test(){
                                    $data = [
                                        'country' => 'EG',
                                        'reference' => '9835413542121',
                                        'amount' => [
                                            "total"=> "400",
                                            "currency"=> 'EGP',
                                        ],
                                        'returnUrl' => 'https://your-return-url',
                                        'callbackUrl'=> 'https://your-call-back-url',
                                        'cancelUrl' => 'https://your-cacel-url',
                                        'expireAt' => 30,
                                        'userInfo' => [
                                            "userEmail"=> 'xxx@xxx.com',
                                            "userId"=> 'userid001',
                                            "userMobile"=> '13056288895',
                                            "userName"=> 'xxx',
                                        ],
                                        'productList' => [
                                            [
                                                "productId"=> 'productId',
                                                "name"=> 'name',
                                                "description"=> 'description',
                                                "price"=> 100,
                                                "quantity"=>2,
                                                "imageUrl"=> 'https://imageUrl.com'
                                            ]
                                        ],
                                        'payMethod'=>'BankCard',
                                    ];
                                    $data2 = (string) json_encode($data,JSON_UNESCAPED_SLASHES);
                                    $header = ['Content-Type:application/json', 'Authorization:Bearer '. $this->publickey, 'MerchantId:'.$this->merchantId];
                                    $response = $this->http_post($this->url, $header, json_encode($data));
                                    $result = $response?$response:null;
                                    return $result;
                                }

                                private function http_post ($url, $header, $data) {
                                    if (!function_exists('curl_init')) {
                                        throw new Exception('php not found curl', 500);
                                    }
                                    $ch = curl_init();
                                    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                                    curl_setopt($ch, CURLOPT_URL, $url);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                                    curl_setopt($ch, CURLOPT_HEADER, false);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                    curl_setopt($ch, CURLOPT_POST, true);
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                                    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                                    $response = curl_exec($ch);
                                    $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                    $error=curl_error($ch);
                                    curl_close($ch);
                                    if (200 != $httpStatusCode) {
                                        print_r("invalid httpstatus:{$httpStatusCode} ,response:$response,detail_error:" . $error, $httpStatusCode);
                                    }
                                    return $response;
                                }
                            }
                        
                    
                            
                                # importing the requests library
                                import requests
                                # CashierAPI Endpoint
                                URL = "https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create"

                                # defining a params dict for the parameters to be sent to the API
                                PaymentData = {
                                    'country' : 'EG',
                                    'reference'    : '12312321324',
                                    'amount': {
                                        "total": '400',
                                        "currency": 'EGP',
                                    },
                                    'payMethod': 'BankCard',
                                    'product': {
                                        "name": 'Iphone X',
                                        "description": 'xxxxxxxxxxxxxxxxx',
                                    },
                                    'returnUrl'  : 'your returnUrl',
                                    'callbackUrl'  : 'your callbackUrl',
                                    'cancelUrl'  : 'your cancelUrl',
                                    'userClientIP' : '1.1.1.1',
                                    'expireAt' : 30,
                                }
                                # Prepare Headers
                                headers = {
                                    'Content-Type' : 'application/json',
                                    'Accept'       : 'application/json',
                                    'Authorization': 'Bearer Public Key',
                                    'MerchantId'   : '256612345678901'
                                }
                                # sending post request and saving the response as response object
                                status_request = requests.post(url = URL, params = json.dumps(PaymentData) , headers=headers)

                                # extracting data in json format
                                status_response = status_request.json()
                            
                        
                            
                                const request = require('request');
                                const formData = {
                                  "amount": {
                                      "currency": "EGP",
                                      "total": 400
                                  },
                                  "callbackUrl": "https://your-call-back-url",
                                  "cancelUrl": "https://your-cacel-url",
                                  "country": "EG",
                                  "expireAt":300,
                                  "payMethod":"BankCard",
                                  "productList":[
                                      {
                                      "description":"description",
                                      "imageUrl":"https://imageUrl.com",
                                      "name":"name",
                                      "price":100,
                                      "productId":"productId",
                                      "quantity":2
                                      }
                                  ],
                                  "reference": "983541354914",
                                  "returnUrl": "https://your-return-url",
                                  "userInfo":{
                                          "userEmail":"xxx@xxx.com",
                                          "userId":"userid001",
                                          "userMobile":"13056288895",
                                          "userName":"xxx"
                                  }
                                };

                                var publickey = "OPAYPUB*************54133"

                                request({
                                    url: 'https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create',
                                    method: 'POST',

                                    headers: {
                                      'Authorization': 'Bearer '+publickey,
                                      'MerchantId': '256621051120756'
                                    },
                                    json: true,
                                    body: formData
                                  }, function (error, response, body) {
                                    console.log('body: ')
                                    console.log(body)
                                  }
                                )

                            
                        
                            
                                curl --location --request POST 'https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create' \
                                --header 'MerchantId: 256621051120756' \
                                --header 'Authorization: Bearer OPAYPUB*************54133' \
                                --header 'Content-Type: application/json' \
                                --data-raw '{
                                    "amount": {
                                        "currency": "EGP",
                                        "total": 400
                                    },
                                    "callbackUrl": "https://your-call-back-url",
                                    "cancelUrl": "https://your-cacel-url",
                                    "country": "EG",
                                    "expireAt":300,
                                    "payMethod":"BankCard",
                                    "productList":[
                                        {
                                        "description":"description",
                                        "imageUrl":"https://imageUrl.com",
                                        "name":"name",
                                        "price":100,
                                        "productId":"productId",
                                        "quantity":2
                                        }
                                    ],
                                    "reference": "983541354912",
                                    "returnUrl": "https://your-return-url",
                                    "userInfo":{
                                            "userEmail":"xxx@xxx.com",
                                            "userId":"userid001",
                                            "userMobile":"13056288895",
                                            "userName":"xxx"
                                    }
                                }'
                            
                        
                        
                            import com.google.gson.Gson;
                            import org.apache.commons.codec.binary.Hex;
                            import javax.crypto.Mac;
                            import javax.crypto.spec.SecretKeySpec;
                            import java.io.BufferedReader;
                            import java.io.InputStreamReader;
                            import java.io.OutputStream;
                            import java.net.HttpURLConnection;
                            import java.net.URL;
                            import java.nio.charset.StandardCharsets;
                            import java.util.ArrayList;
                            import java.util.TreeMap;
                            import java.util.UUID;

                            public class CashierCreate {

                                private static final String publicKey = "OPAYPUB*************54133";

                                private static final String endpoint = "https://sandboxapi.opaycheckout.com";

                                private static final String merchantId = "256621051120756";

                                public static void main(String[] args) throws Exception {
                                    String addr = endpoint + "/api/v1/international/cashier/create";
                                    Gson gson = new Gson();
                                    TreeMap order = new TreeMap<>();
                                    order.put("country","EG");
                                    order.put("reference", UUID.randomUUID().toString());
                                    TreeMap amount = new TreeMap<>();
                                    amount.put("currency","EGP");
                                    amount.put("total",new Integer(400));
                                    order.put("amount",amount);
                                    order.put("returnUrl","https://your-return-url.com");
                                    order.put("callbackUrl","https://your-call-back-url.com");
                                    order.put("cancelUrl","https://your-cacel-url");
                                    order.put("expireAt",new Integer(300));
                                    TreeMap userInfo = new TreeMap<>();
                                    userInfo.put("userEmail","xxx@xxx.com");
                                    userInfo.put("userId","userid001");
                                    userInfo.put("userMobile","13056288895");
                                    userInfo.put("userName","xxx");
                                    order.put("userInfo",userInfo);
                                    ArrayList productList = new ArrayList<>();
                                    TreeMap product = new TreeMap<>();
                                    product.put("productId","productId");
                                    product.put("name","name");
                                    product.put("description","description");
                                    product.put("price",new Integer(100));
                                    product.put("quantity",new Integer(2));
                                    product.put("imageUrl","https://imageUrl.com");
                                    productList.add(product);
                                    order.put("productList",productList);
                                    order.put("payMethod","BankCard");

                                    String requestBody = gson.toJson(order);
                                    System.out.println("--request:");
                                    System.out.println(requestBody);

                                    URL url = new URL(addr);
                                    HttpURLConnection con = (HttpURLConnection)url.openConnection();
                                    con.setRequestMethod("POST");
                                    con.setRequestProperty("Content-Type", "application/json; utf-8");
                                    con.setRequestProperty("Authorization", "Bearer "+publicKey);
                                    con.setRequestProperty("MerchantId", merchantId);
                                    con.setDoOutput(true);
                                    OutputStream os = con.getOutputStream();
                                    byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                                    os.write(input, 0, input.length);
                                    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
                                    StringBuilder response = new StringBuilder();
                                    String responseLine = null;
                                    while ((responseLine = br.readLine()) != null) {
                                        response.append(responseLine.trim());
                                    }

                                    System.out.println("--response:");
                                    System.out.println(response.toString());
                                    //close your stream and connection
                                }

                                public static String hmacSHA512(final String data, final String secureKey) throws Exception{
                                    byte[] bytesKey = secureKey.getBytes();
                                    final SecretKeySpec secretKey = new SecretKeySpec(bytesKey, "HmacSHA512");
                                    Mac mac = Mac.getInstance("HmacSHA512");
                                    mac.init(secretKey);
                                    final byte[] macData = mac.doFinal(data.getBytes());
                                    byte[] hex = new Hex().encode(macData);
                                    return new String(hex, StandardCharsets.UTF_8);
                                }
                            }
                        
                    
                        
                            using System;
                            using System.IO;
                            using System.Linq;
                            using System.Net;
                            using System.Text;
                            using Newtonsoft.Json;
                            namespace OPayRequest
                            {
                                public class Program
                                {
                                    static void Main(string[] args)
                                    {
                                        PostJson("https://sandboxapi.opaycheckout.com/api/v1/international/cashier/create", new opay_request
                                        {
                                            country = 'EG',
                                            reference    = '12312321324',
                                            amount= {
                                                "total"= '400',
                                                "currency"= 'EGP',
                                            },
                                            'payMethod': 'BankCard',
                                            product= {
                                                "name"= 'Iphone X',
                                                "description"= 'xxxxxxxxxxxxxxxxx',
                                            },
                                            returnUrl  = 'your returnUrl',
                                            callbackUrl  = 'your callbackUrl',
                                            cancelUrl  = 'your cancelUrl',
                                            userClientIP = '1.1.1.1',
                                            expireAt = 30,
                                        });
                                    }

                                    private static void PostJson(string uri, opay_request postParameters)
                                    {
                                        string postData = JsonConvert.SerializeObject(postParameters);
                                        byte[] bytes = Encoding.UTF8.GetBytes(postData);
                                        var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri);
                                        httpWebRequest.Method = "POST";
                                        httpWebRequest.ContentLength = bytes.Length;
                                        httpWebRequest.ContentType = "text/json";
                                        using (Stream requestStream = httpWebRequest.GetRequestStream())
                                        {
                                            requestStream.Write(bytes, 0, bytes.Count());
                                        }
                                        var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
                                        if (httpWebResponse.StatusCode != HttpStatusCode.OK)
                                        {
                                            string message = String.Format("GET failed. Received HTTP {0}", httpWebResponse.StatusCode);
                                            throw new ApplicationException(message);
                                        }
                                    }
                                }

                                public class opay_request
                                {
                                    public string reference { get; set; }
                                    public string payMethod { get; set; }
                                    public string returnUrl { get; set; }
                                    public string callbackUrl { get; set; }
                                    public string cancelUrl {get; set;}
                                    public string userClientIP { get; set; }
                                    public string expireAt { get; set; }
                                    public product product;
                                    public amount amount;
                                }
                                public class amount
                                {
                                     public string total { get; set; }
                                     public string currency { get; set; }
                                }
                            public class product
                                {
                                     public string name { get; set; }
                                     public string description { get; set; }
                                }
                            }

                        
                    

OPay Cashier Response

Sample Response

the parameters contained in the response received whenever you call OPay Cashier Create API as a JSON Object.

Sample OPay Cashier Create API Response

                    
                        {
                            "code": "00000",
                            "message": "SUCCESSFUL",
                            "data": {
                                "reference": "9835146212",
                                "orderNo": "211009140896553163",
                                "cashierUrl": "https://sandboxcashier.opaycheckout.com/apiCashier/redirect/payment/checkout?orderToken=TOKEN.546f3b0405b447be8198691999678765",
                                "status": "INITIAL",
                                "amount": {
                                    "total": 400,
                                    "currency": "EGP"
                                },
                                "vat": {
                                    "total": 0,
                                    "currency": "EGP"
                                }
                            }
                        }
                    
                

Response Parameters Description

Parameter type Description example
reference String Unique merchant payment order number. 937102167
orderNo String Unique Opay payment order number. 211009140896593010
cashierUrl String OPay Cashier URl generated for your client's current transaction.

https://sandboxcashier.opaycheckout.com/apiCashier/redirect/payment/checkout?orderToken=TOKEN.546f3b0405b447be8198691999f56788

status enum [INITIAL, PENDING, SUCCESS, FAIL, CLOSE] SUCCESS
amount
total Integer amount(cent unit). 400
currency String currency type.See full list here EGP
vat
total Integer amount(cent unit). 10
currency String currency type.See full list here EGP

Redirect Client to Cashier URL

Once you received the response of the cashier create payment API, your next action is to redirect your client to the cashierUrl received within the API response. Once you redirect your client, the cashier page will be ready for your client to complete the payment.

OPay Cashier Scrreen

If you've left the payMethod key blank in your request, your client will have the options to pay using:

  • MasterCard, VISA, or MEEZA cards.
  • Obtain a reference number and pay at any POS of our OPay retail network.

Otherwise, if you have designated a specific payMethod, only the designated payment method will be available to your client to use.

Payment Processing Information

If your client has completed the payment at the generated cashierUrl, he will be redirected to the returnUrl sent with your request, otherwise, if he decided to cancel the payment, he will be redirected to cancelUrl. You will receive the payment processing information on the callbackUrl provided with your API request. A callback object is sent in JSON and similar to what you would expect in response to a typical API request. Below is the body of a callback.

                        
                        {
                          "payload": {
                            "country": "EG",
                            "fee": "20",
                            "channel": "Web",
                            "displayedFailure": "",
                            "reference": "3cae64cb5f68a7c4008b765b97401a",
                            "updated_at": "2020-09-21T13:18:45Z",
                            "currency": "EGP",
                            "refunded": false,
                            "timestamp": "2020-09-21T13:18:45Z",
                            "amount": "400",
                            "transactionId": "200921144008250432",
                            "token": "200921144008250432",
                            "bussinessType": "Consumption_H5",
                            "payChannel": "BalancePayment",
                            "status": "SUCCESS"
                          },
                          "sha512": "4d001b261faa72096b63fa024299fd860c17b98563d4bb4f72371b932b91c348959f3af98853a37347b09a84ddcf53203d49f77d715f1679d8598f7a54107ef4",
                          "type": "transaction-status"
                        }
                        
                

Callback Parameters Description

Parameter type Description
payload
country String Transaction belongs country.
fee String Transaction fee Amount.
displayedFailure String Transaction reason for failure.
reference String Partner transaction number.
updated_at String Transaction update time.
currency String Transaction currency.
refunded String Is the transaction a refund type (true false).
timestamp String Transaction time.
amount String Transaction Amount.
transactionId String Opay transaction number(orderNo).
payChannel String Payment MethodsSee available options here
status enum [PENDING, SUCCESS, FAIL, CLOSE]
sha512 String Which is essentially a HMac-SHA3-512 signature of the callback payload. Signed using your Secret Key. See here
type enum [transaction-status,refund-status]

Error Handling

After submitting an API call to OPay, you receive a response back to inform you that your request was received and processed. A successful OPay API should return a status code 00, meanwhile, in a situation where any payment processing error occurred, you will receive an error code with a message to describe the reason of the error. A sample error response can be found below.

                    
                        {
                            "code": "02004",
                            "message": "the payment reference already exists."
                        }
                    
                

Depending on the HTTP status code of the response, you should build some logic to handle any errors that a request or the system may return. A list of possible potential error codes that you may receive can be found below. A full list of all possible error codes can be found in the Error Codes section.

Error Code Error Message
02000 authentication failed.
02001 request params not valid.
02003 payMethod not support.
02004 the payment reference(merchant order number) already exists.
02002 merchant not configured with this function.
02007 merchant not available.
50003 service not available, please try again.

What's Next?

User Profile 12 messages

James Jones
Application Developer
Recent Notifications
Another purpose persuade Due in 2 Days
+28%
Would be to people Due in 2 Days
+50%
-27%
The best product Due in 2 Days
+8%