OPay Authorize and Capture Payment API

In this page, you will learn how to use Authorize and Capture Payment API, you can make authorize payment first, then you can capture the authorized payment later

  • Collect your client's payment Information.
  • Trigger Authorize The Payment API and query order status
  • Trigger Capture The Authorized Payment
  • After payment successfully, redirect your client to successful page

1.Authorize The Payment

To test your Authorize The Payment API, you need to request using the POST method in our sandbox environment.
-Here is the request URL:

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

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

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

-Request Parameters:

  1. Header: Authorization(API Calls Signature), MerchantId
  2. Authorization    : Bearer {signature}
    MerchantId       : 256612345678901
  3. Json object containing the transaction information:
  4. {
        "authoriseAmount": {
            "currency": "EGP",
            "total": 4000
        },
        "bankcard": {
            "cardHolderName": "David",
            "cardNumber": "5123450000000008",
            "cvv": "100",
            "enable3DS": true,
            "expiryMonth": "01",
            "expiryYear": "39"
        },
        "callbackUrl": "https://your-call-back-url.com",
        "country": "EG",
        "manualCapture":true,
        "payMethod": "BankCard",
        "product": {
            "description": "this is a test product",
            "name": "test product1"
        },
        "reference": reference,
        "returnUrl": "https://your-return-url.com",
        "userClientIP": "2.1.1.1",
        "userInfo": {
            "userEmail": "[email protected]",
            "userId": "666666",
            "userMobile": "201066668888",
            "userName": "David"
      }
    }

HTTP POST parameters

-Here is a detailed description for the parameters you need to complete the POST request:

ParametertyperequiredDescription
countryStringrequiredCountry Code. See full list here
referenceStringrequiredThe unique merchant payment order number.
authoriseAmount
totalLongrequiredAmount(cent unit).
currencyStringrequiredCurrency type. e.g. EGP
manualCaptureBooleanrequiredValue must be true. It means that make authorize payment
payMethodStringrequiredBankCard
bankcard
JSON Object
cardNumberStringrequiredCard number.See test card
cardHolderNameStringrequiredCard holder name
expiryMonthStringrequiredCard expiry month[01,02 ... 11,12]
expiryYearStringrequiredCard expiry year[21,22,23...]
cvvStringrequiredcvv
enable3DSBooleanrequiredIf the value is true, it means authorize payment with 3DS.If the value is false, it means authorize payment with Non-3DS.
callbackUrlStringoptionalIf 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
returnUrlStringrequiredThe URL to which OPay API should return the payment processing response.
product
nameStringrequiredProduct name
descriptionStringrequiredProduct description
expireAtIntegeroptionalPayment expiration time in minutes.(default 30)
userClientIPStringoptionalIP address of customer's device. IPv4 or IPv6.
userInfo
JSON Object
userIdStringoptionalThe unique customer user id in merchant system
userNameStringoptionalThe customer name in merchant system
userMobileStringoptionalThe customer mobile number in merchant system.e.g. 201066668888.
userEmailStringoptionalThe customer email in merchant system. e.g. customer

-An example of Authorize The Payment request for is as follows :

class AuthController
{
    private $secretkey;
    private $merchantId;
    private $url;

    public function __construct() {
        $this->merchantId = '256621050820270';
        $this->secretkey = 'OPAYPRV1620441*******95';
        $this->url = 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/create';
    }

    public function test(){
        $data = [
          "authoriseAmount"=> [
              "currency"=> "EGP",
              "total"=> 4000
          ],
          "bankcard"=> [
              "cardHolderName"=> "David",
              "cardNumber"=> "5441110000000005",
              "cvv"=> "100",
              "enable3DS"=> false,
              "expiryMonth"=> "01",
              "expiryYear"=> "39"
          ],
          "callbackUrl"=> "https://your-call-back-url.com",
          "country"=> "EG",
          "manualCapture"=> true,
          "payMethod"=> "BankCard",
          "product"=> [
              "description"=> "this is a test product",
              "name"=> "test product1"
          ],
          "reference"=> "reference12345678",
          "returnUrl"=> "https://your-return-url.com",
          "userClientIP"=> "2.1.1.1",
          "userInfo"=> [
              "userEmail"=> "[email protected]",
              "userId"=> "666666",
              "userMobile"=> "201066668888",
              "userName"=> "David"
        ]
      ]
        ;
        $data2 = (string) json_encode($data,JSON_UNESCAPED_SLASHES);
        $auth = $this->auth($data2);
        $header = ['Content-Type:application/json', 'Authorization:Bearer '. $auth, '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;
    }
    public function auth ( $data ) {
        $secretKey = $this->secretkey;
        $auth = hash_hmac('sha512', $data, $secretKey);
        return $auth;
    }

}
const request = require('request');
var sha512 = require('js-sha512');
const formData ={
  "authoriseAmount": {
      "currency": "EGP",
      "total": 4000
  },
  "bankcard": {
      "cardHolderName": "David",
      "cardNumber": "5441110000000005",
      "cvv": "100",
      "enable3DS": true,
      "expiryMonth": "01",
      "expiryYear": "39"
  },
  "callbackUrl": "https://your-call-back-url.com",
  "country": "EG",
  "manualCapture":true,
  "payMethod": "BankCard",
  "product": {
      "description": "this is a test product",
      "name": "test product1"
  },
  "reference": "reference12345",
  "returnUrl": "https://your-return-url.com",
  "userClientIP": "2.1.1.1",
  "userInfo": {
      "userEmail": "[email protected]",
      "userId": "666666",
      "userMobile": "201066668888",
      "userName": "David"
}
}

;

var privateKey = "OPAYPRV1620441*******95"

var hash = sha512.hmac.create(privateKey);
hash.update(JSON.stringify(formData));
hmacsignature = hash.hex();
console.log(hmacsignature)
request({
    url: 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/create',
    method: 'POST',
    headers: {
      'MerchantId': '256621050820270',
      'Authorization': 'Bearer '+hmacsignature
    },
    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/payment/create' \
--header 'MerchantId: 256621050820270' \
--header 'Authorization: Bearer 0cbc1ef4d5a3dc3bb9f35ab72190575dcf7dd25a3152358be43bc67a605b1ff1b1a30551bd717636f5de1716bdafb45367bdd77500e625bcc71ef6c77248949c' \
--header 'Content-Type: application/json' \
--data-raw '{
    "authoriseAmount": {
        "currency": "EGP",
        "total": 4000
    },
    "bankcard": {
        "cardHolderName": "David",
        "cardNumber": "5441110000000005",
        "cvv": "100",
        "enable3DS": true,
        "expiryMonth": "01",
        "expiryYear": "39"
    },
    "callbackUrl": "https://your-call-back-url.com",
    "country": "EG",
    "manualCapture": true,
    "payMethod": "BankCard",
    "product": {
        "description": "this is a test product",
        "name": "test product1"
    },
    "reference": "qur-20221649411709522",
    "returnUrl": "https://your-return-url.com",
    "userClientIP": "2.1.1.1",
    "userInfo": {
        "userEmail": "[email protected]",
        "userId": "666666",
        "userMobile": "201066668888",
        "userName": "David"
    }
}'
import com.google.gson.Gson;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.TreeMap;
import java.util.UUID;

public class OpayAuth {

    private static final String privateKey = "OPAYPRV1620441*******95";

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

    private static final String merchantId = "256621050820270";

    public static void main(String[] args) throws Exception {
        String addr = endpoint + "/api/v1/international/payment/create";
        Gson gson = new Gson();
        TreeMap order = new TreeMap<>();
        TreeMap authoriseAmount = new TreeMap<>();
        authoriseAmount.put("currency","EGP");
        authoriseAmount.put("total",new Integer(400));
        order.put("authoriseAmount",authoriseAmount);
        TreeMap bankcard = new TreeMap<>();
        bankcard.put("cardHolderName","DAVID");
        bankcard.put("cardNumber","5441110000000005");
        bankcard.put("cvv","100");
        bankcard.put("enable3DS",Boolean.TRUE);
        bankcard.put("expiryMonth","01");
        bankcard.put("expiryYear","39");
        order.put("bankcard",bankcard);
        order.put("callbackUrl","https://your-call-back-url.com");
        order.put("country","EG");
        order.put("manualCapture",Boolean.TRUE);
        order.put("payMethod","BankCard");
        TreeMap product = new TreeMap<>();
        product.put("name","your product name");
        product.put("description","your product description");
        order.put("product",product);
        order.put("reference", UUID.randomUUID().toString());
        order.put("returnUrl","https://your-return-url.com");
        TreeMap userInfo = new TreeMap<>();
        userInfo.put("userEmail","[email protected]");
        userInfo.put("userId","666666");
        userInfo.put("userMobile","201066668888");
        userInfo.put("userName","David");
        order.put("userInfo",userInfo);

        String requestBody = gson.toJson(order);
        System.out.println("--request:");
        System.out.println(requestBody);
        String oPaySignature = hmacSHA512(requestBody, privateKey);
        System.out.println("--signature:");
        System.out.println(oPaySignature);

        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 "+oPaySignature);
        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);
    }
}

Header must contain the "Signature" , "MerchantId"

Signature is calculated using SHA-512 HMAC signed with your Private Key. See API Calls Signature section for more details.

Authorize The Payment Response


-Response Parameters:

the parameters contained in the response received whenever you call payment API as a JSON Object.

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data": {
        "reference": "qur-20221649754054379",
        "orderNo": "220412145660943547924",
        "nextAction": {
            "actionType": "REDIRECT_3DS",
            "redirectUrl": "https://sandboxapi.opaycheckout.com/api/v1/international/transaction/3ds/8025301bd81d4dfb99fa2750787843de"
        },
        "status": "PENDING",
        "amount": {
            "total": 0,
            "currency": "EGP"
        },
        "vat": {
            "total": 0,
            "currency": "EGP"
        },
        "isAuthorised": false,
        "isCaptured": false,
        "isVoided": false
    }
}

-Here is a detailed description for the parameters received in the response:

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
nextAction
actionTypeStringNext action type, enum[REDIRECT_3DS]REDIRECT_3DS
redirectUrlString3ds redirect url.https://sandboxapi.opaycheckout.com/api/v1/international/transaction/3ds/e9f25ec9bd4139329aaa9ab784775220aed5ca97f9021578df2ab4287e0f8175
statusStringOrder statusPENDING
amount
JSON Object
totalLongTransaction amount1000 (cent unit)
currencyStringCurrency typeEGP
vat
JSON Object
totalLongValue Added Tax Amount0
currencyStringCurrency typeEGP
isAuthorisedBooleanIf the payment order has been authorised, there will be an isAuthorised parameter in the response, its value is true or false.true or false
isCapturedBooleanIf the payment order has been captured, there will be an isCaptured parameter in the response, its value is true or false.true or false
isVoidedBooleanIf the payment order has been voided, there will be an isVoided parameter in the response, its value is true or false.true or false
failureCodeStringFail error code.Payment fail error code, not blank when status [FAIL/CLOSE]
failureReasonStringFail error message.Payment fail error message, not blank when status [FAIL/CLOSE]

-Response Parameters:

the parameters contained in the response received whenever you call payment API as a JSON Object.

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data": {
        "reference": "20221649421910911",
        "orderNo": "220408145660942711535",
        "status": "PENDING",
        "amount": {
            "total": 0,
            "currency": "EGP"
        },
        "vat": {
            "total": 0,
            "currency": "EGP"
        },
        "isAuthorised": true,
        "isCaptured": false,
        "isVoided": false
    }
}

-Here is a detailed description for the parameters received in the response:

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
statusStringOrder statusPENDING
amount
JSON Object
totalLongTransaction amount1000 (cent unit)
currencyStringCurrency typeEGP
vat
JSON Object
totalLongValue Added Tax Amount0
currencyStringCurrency typeEGP
isAuthorisedBooleanIf the payment order has been authorised, there will be an isAuthorised parameter in the response, its value is true or false.true or false
isCapturedBooleanIf the payment order has been captured, there will be an isCaptured parameter in the response, its value is true or false.true or false
isVoidedBooleanIf the payment order has been voided, there will be an isVoided parameter in the response, its value is true or false.true or false
failureCodeStringFail error code.Payment fail error code, not blank when status [FAIL/CLOSE]
failureReasonStringFail error message.Payment fail error message, not blank when status [FAIL/CLOSE]

2.Capture The Authorized Payment API

To test your Capture The Authorized Payment API, you need to request using the POST method in our sandbox environment.
-Here is the request URL:

https://sandboxapi.opaycheckout.com/api/v1/international/payment/capture

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

https://api.opaycheckout.com/api/v1/international/payment/capture

-Request Parameters:

  1. Header: Authorization(API Calls Signature), MerchantId
  2. Authorization    : Bearer {signature}
    MerchantId       : 256612345678901
  3. Json object containing the transaction information:
  4. {
        "amount": {
            "currency": "EGP",
            "total": 3000
        },
        "orderNo":"220408145660942641228"
    }

HTTP POST parameters

-Here is a detailed description for the parameters you need to complete the POST request:

ParametertyperequiredDescription
amount
totalLongrequiredAmount(cent unit).
currencyStringrequiredCurrency type. e.g. EGP
countryStringoptionalCountry Code.
orderNoStringrequired (if no reference provide)Order id.
referenceStringrequired (if no orderNo provide)Payment reference Id.

-An example of Capture The Authorized Payment request is as follows :

class CaptureController
{
    private $secretkey;
    private $merchantId;
    private $url;

    public function __construct() {
        $this->merchantId = '256621050820270';
        $this->secretkey = 'OPAYPRV1620441*******95';
        $this->url = 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/capture';
    }

    public function test(){
        $data = [
            "amount"=> [
                "currency"=> "EGP",
                "total"=> 3000
            ],
            "orderNo"=> "220408145660965871390"
        ]
        ;
        $data2 = (string) json_encode($data,JSON_UNESCAPED_SLASHES);
        $auth = $this->auth($data2);
        $header = ['Content-Type:application/json', 'Authorization:Bearer '. $auth, '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;
    }
    public function auth ( $data ) {
        $secretKey = $this->secretkey;
        $auth = hash_hmac('sha512', $data, $secretKey);
        return $auth;
    }

}
const request = require('request');
var sha512 = require('js-sha512');
const formData ={
  "amount": {
      "currency": "EGP",
      "total": 3000
  },
  "orderNo":"220408145660965875638"
};

var privateKey = "OPAYPRV1620441*******95"

var hash = sha512.hmac.create(privateKey);
hash.update(JSON.stringify(formData));
hmacsignature = hash.hex();
console.log(hmacsignature)
request({
    url: 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/capture',
    method: 'POST',
    headers: {
      'MerchantId': '256621050820270',
      'Authorization': 'Bearer '+hmacsignature
    },
    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/payment/capture' \
--header 'MerchantId: 256621050820270' \
--header 'Authorization: Bearer 6bd2e7e1136d103c04ee86d61bf9f5c620397528788ea61593a712ae8c8d8a1b4e2a3eb4122271291b9573ee114aad3a70973a997cb5a79f7705d7179de0730d' \
--header 'Content-Type: application/json' \
--data-raw '{
    "amount": {
        "currency": "EGP",
        "total": 3000
    },
    "orderNo": "220408145660942690289"
}'
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.TreeMap;

public class Capture {

    private static final String privateKey = "OPAYPRV1620441*******95";

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

    private static final String merchantId = "256621050820270";

    public static void main(String[] args) throws Exception {
        String addr = endpoint + "/api/v1/international/payment/capture";
        Gson gson = new Gson();
        TreeMap order = new TreeMap<>();
        TreeMap amount = new TreeMap<>();
        amount.put("currency","EGP");
        amount.put("total",new Integer(400));
        order.put("amount",amount);
        order.put("orderNo","220408145660942668836");

        String requestBody = gson.toJson(order);
        System.out.println("--request:");
        System.out.println(requestBody);
        String oPaySignature = hmacSHA512(requestBody, privateKey);
        System.out.println("--signature:");
        System.out.println(oPaySignature);

        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 "+oPaySignature);
        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);
    }
}

Header must contain the "Signature" , "MerchantId"

Signature is calculated using SHA-512 HMAC signed with your Private Key. See API Calls Signature section for more details.

Capture the Authorized Payment Response

-Response Parameters:

the parameters contained in the response received whenever you call the Pickup Goods payment API as a JSON Object.

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data": {
        "reference": "20221649411709522",
        "orderNo": "220408145660942690289",
        "status": "SUCCESS",
        "amount": {
            "total": 3000,
            "currency": "EGP"
        },
        "authoriseAmount": {
            "total": 4000,
            "currency": "EGP"
        },
        "isVoided": false,
        "isAuthorised": true,
        "isCaptured": true
    }
}

-Here is a detailed description for the parameters received in the response:

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
statusStringOrder statusPENDING
amount
JSON Object
totalLongTransaction amount1000 (cent unit)
currencyStringCurrency typeEGP
authoriseAmount
JSON Object
totalLongAuthorize amount1000 (cent unit)
currencyStringCurrency typeEGP
isAuthorisedBooleanIf the payment order has been authorised, there will be an isAuthorised parameter in the response, its value is true or false.true or false
isCapturedBooleanIf the payment order has been captured, there will be an isCaptured parameter in the response, its value is true or false.true or false
isVoidedBooleanIf the payment order has been voided, there will be an isVoided parameter in the response, its value is true or false.true or false
failureCodeStringFail error code.Payment fail error code, not blank when status [FAIL/CLOSE]
failureReasonStringFail error message.Payment fail error message, not blank when status [FAIL/CLOSE]

3.Void Payment Authentication API

To test your Void Payment Authentication API, you need to request using the POST method in our sandbox environment.
-Here is the request URL:

https://sandboxapi.opaycheckout.com/api/v1/international/payment/authorise/void

Once you are ready for production, you should use the following production API endpoint URL instead

https://api.opaycheckout.com/api/v1/international/payment/authorise/void
  1. Header: Authorization(API Calls Signature), MerchantId
  2. Authorization    : Bearer {signature}
    MerchantId       : 256612345678901
  3. Json object containing the transaction information:
  4. {
        "orderNo":"220408145660942643145"
    }

HTTP POST Parameters

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

ParametertyperequiredDescription
countryStringoptionalCountry Code.
orderNoStringrequired (if no reference provide)Order id.
referenceStringrequired (if no orderNo provide)Payment reference Id.

-An example of Void Payment Authentication for is as follows :

class voidPaymentController
{
    private $secretkey;
    private $merchantId;
    private $url;

    public function __construct() {
        $this->merchantId = '256621050820270';
        $this->secretkey = 'OPAYPRV1620441*******95';
        $this->url = 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/authorise/void';
    }

    public function test(){
        $data = [
            "orderNo"=> "220408145660965872894"
        ]
        ;
        $data2 = (string) json_encode($data,JSON_UNESCAPED_SLASHES);
        $auth = $this->auth($data2);
        $header = ['Content-Type:application/json', 'Authorization:Bearer '. $auth, '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;
    }
    public function auth ( $data ) {
        $secretKey = $this->secretkey;
        $auth = hash_hmac('sha512', $data, $secretKey);
        return $auth;
    }

}
const request = require('request');
var sha512 = require('js-sha512');
const formData ={
  "orderNo":"220408145660942685455"
}
;

var privateKey = "OPAYPRV1620441*******95"

var hash = sha512.hmac.create(privateKey);
hash.update(JSON.stringify(formData));
hmacsignature = hash.hex();
console.log(hmacsignature)
request({
    url: 'https://sandboxapi.opaycheckout.com/api/v1/international/payment/authorise/void',
    method: 'POST',
    headers: {
      'MerchantId': '256621050820270',
      'Authorization': 'Bearer '+hmacsignature
    },
    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/payment/authorise/void' \
--header 'MerchantId: 256621050820270' \
--header 'Authorization: Bearer 4f2fffc58bba71347e4a8abff5aa72d2ccf316f624dc2e733f84ee8038e360e2f66ba2d925bd69e8b57e14248ed9a18abfca9a70d6c9a662111c31c90c757e20' \
--header 'Content-Type: application/json' \
--data-raw '{
    "orderNo": "220408145660942692043"
}'
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.TreeMap;

public class Void {

    private static final String privateKey = "OPAYPRV1620441*******95";

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

    private static final String merchantId = "256621050820270";

    public static void main(String[] args) throws Exception {
        String addr = endpoint + "/api/v1/international/payment/authorise/void";
        Gson gson = new Gson();
        TreeMap order = new TreeMap<>();
        order.put("orderNo","220408145660965865143");

        String requestBody = gson.toJson(order);
        System.out.println("--request:");
        System.out.println(requestBody);
        String oPaySignature = hmacSHA512(requestBody, privateKey);
        System.out.println("--signature:");
        System.out.println(oPaySignature);

        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 "+oPaySignature);
        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);
    }
}

Header must contain the "Signature" , "MerchantId"

Signature is calculated using SHA-512 HMAC signed with your Private Key. See API Calls Signature section for more details.

Void Payment Authentication Response

-Response Parameters:

the parameters contained in the response received whenever you call the payment API as a JSON Object.

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data": {
        "reference": "qur-20221649412108762",
        "orderNo": "220408145660942692043",
        "status": "FAIL",
        "amount": {
            "total": 0,
            "currency": "EGP"
        },
        "authoriseAmount": {
            "total": 4000,
            "currency": "EGP"
        },
        "isVoided": true,
        "isAuthorised": true,
        "isCaptured": false
    }
}

-Here is a detailed description for the parameters received in the response:

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
statusStringOrder statusPENDING
amount
JSON Object
totalLongTransaction amount1000 (cent unit)
currencyStringCurrency typeEGP
authoriseAmount
JSON Object
totalLongAuthorize amount1000 (cent unit)
currencyStringCurrency typeEGP
isAuthorisedBooleanIf the payment order has been authorised, there will be an isAuthorised parameter in the response, its value is true or false.true or false
isCapturedBooleanIf the payment order has been captured, there will be an isCaptured parameter in the response, its value is true or false.true or false
isVoidedBooleanIf the payment order has been voided, there will be an isVoided parameter in the response, its value is true or false.true or false
failureCodeStringFail error code.Payment fail error code, not blank when status [FAIL/CLOSE]
failureReasonStringFail error message.Payment fail error message, not blank when status [FAIL/CLOSE]

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 CodeError Message
02000authentication failed.
02001request parameters not valid.
02002merchant not configured with this function.
02003payMethod not support.
02004the payment reference already exists.
02007merchant not available.
50003service not available, please try again.
05023The %s parameter is required
05056The value of enable3DS must be true

What's Next?