OPay Bank Debit API

In this page, you will learn how to bind Bank Debit.

Bind Bank Debit agreement and make payment

To test your Bank Debit Payment, 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. {
        "amount": {
            "currency": "EGP",
            "total": 1000
        },
        "bankDebit": {
            "agreementDuration": "2022-12-31",
            "agreementId": "1647857006899",
            "storeCard": true
        },
        "bankcard": {
            "cardHolderName": "DAVID",
            "cardNumber": "45087********",
            "cvv": "100",
            "enable3DS": true,
            "expiryMonth": "02",
            "expiryYear": "26"
        },
        "callbackUrl": "https://your-call-back-url.com",
        "country": "EG",
        "expireAt": "30",
        "payMethod": "CardDebit",
        "product": {
            "description": "description",
            "name": "name"
        },
        "reference": "104123325",
        "returnUrl": "https://your-return-url.com",
        "userClientIP": "1.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.
amount
totalLongrequiredAmount(cent unit).If the amount is 0, we just bind the agreement and customer card info. If the amount is not 0, we will bind the agreement and customer card info, and complete the payment
currencyStringrequiredCurrency type. e.g. EGP
payMethodStringrequiredBank Debit Payment Method: cardAutoDebit
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.
enable3DSBooleanrequiredValue must be true
bankDebit
JSON Object
agreementIdStringrequiredThe agreement ID in merchant system
agreementDurationStringrequiredThe agreement duration in merchant system, the format is yyyy-MM-dd. The min duration is 1 day, the max duration is 5 years
storeCardBooleanrequiredValue must be true
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
userIdStringrequiredThe 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. [email protected].

-An example of Bank Debit payment request for an amount of 1000 EGP is as follows :

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

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

    public function test(){
        $data = [
            'amount'=>[
                'currency'=>'EGP',
                'total'=>1000
            ],
            'bankDebit'=>[
                'agreementDuration'=>'2022-12-31',
                'agreementId'=>'1647857006899',
                'storeCard'=>true
            ],
            'bankcard'=>[
                'cardHolderName'=>'DAVID',
                'cardNumber'=>'45087********',
                'cvv'=>'100',
                'enable3DS'=>true,
                'expiryMonth'=>'02',
                'expiryYear'=>'26'
            ],
            'callbackUrl'=>'https://your-call-back-url.com',
            'country'=>'EG',
            'expireAt'=>'30',
            'payMethod'=>'CardDebit',
            'product'=>[
                'description'=>'description',
                'name'=>'name'
            ],
            'reference'=>'104123325',
            'returnUrl'=>'https://your-return-url.com',
            'userClientIP'=>'1.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 = {
    "amount": {
        "currency": "EGP",
        "total": 1000
    },
    "bankDebit": {
        "agreementDuration": "2022-12-31",
        "agreementId": "1647857006899",
        "storeCard": true
    },
    "bankcard": {
        "cardHolderName": "DAVID",
        "cardNumber": "45087********",
        "cvv": "100",
        "enable3DS": true,
        "expiryMonth": "02",
        "expiryYear": "26"
    },
    "callbackUrl": "https://your-call-back-url.com",
    "country": "EG",
    "expireAt": "30",
    "payMethod": "CardDebit",
    "product": {
        "description": "description",
        "name": "name"
    },
    "reference": "104123325",
    "returnUrl": "https://your-return-url.com",
    "userClientIP": "1.1.1.1",
    "userInfo": {
        "userEmail": "[email protected]",
        "userId": "666666",
        "userMobile": "201066668888",
        "userName": "David"
    }
};

var privateKey = "OPAYPRV1638774******57474"

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': '281821120675251',
      '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: 281821120675251' \
--header 'Authorization: Bearer f214790af2556401392a2b2e85880ef3970c7c55607f9799445a64f5e250ffc682ae3592ed9d250855be6b28ebe090d6a009892f134e443b7d14bd3400822041' \
--header 'Content-Type: application/json' \
--data-raw '{
    "amount": {
        "currency": "EGP",
        "total": 0
    },
    "bankDebit": {
        "agreementDuration": "2022-05-10",
        "agreementId": "104123346",
        "storeCard": true
    },
    "callbackUrl": "https://your-call-back-url.com",
    "cancelUrl": "https://your-cancel-url.com",
    "collectCardInfo": true,
    "country": "EG",
    "payMethod": "CardDebit",
    "product": {
        "description": "description data",
        "name": "name data"
    },
    "reference": "104123346",
    "returnUrl": "https://your-return-url.com",
    "userInfo": {
        "userId": "testuserid001"
    }
}'
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;
import java.util.UUID;

public class BindBankDebitAgreement {

    private static final String privateKey = "OPAYPRV1638774******57474";

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

    private static final String merchantId = "281821120675251";

    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 amount = new TreeMap<>();
        amount.put("currency","EGP");
        amount.put("total",1000);
        order.put("amount",amount);
        TreeMap bankDebit = new TreeMap<>();
        bankDebit.put("agreementDuration","2022-02-01");
        bankDebit.put("agreementId",UUID.randomUUID().toString());
        bankDebit.put("storeCard",true);
        order.put("bankDebit",bankDebit);
        TreeMap bankcard = new TreeMap<>();
        bankcard.put("cardHolderName","DAVID");
        bankcard.put("cardNumber","45087********");
        bankcard.put("cvv","100");
        bankcard.put("enable3DS",true);
        bankcard.put("expiryMonth","02");
        bankcard.put("expiryYear","26");
        order.put("bankcard", bankcard);
        order.put("callbackUrl","https://your-callback-url.com");
        order.put("country","EG");
        order.put("merchantName","test merchant");
        order.put("payMethod","CardDebit");
        TreeMap product = new TreeMap<>();
        product.put("description","description");
        product.put("name","name");
        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);
    }
}


Bank Debit Payment 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":"104123398",
        "orderNo":"211004140885521681",
        "nextAction":{
            "actionType":"REDIRECT_3DS",
            "redirectUrl":"https://sandboxapi.opaycheckout.com/api/v1/international/transaction/3ds/e9f25ec9bd4139329aaa9ab784775220aed5ca97f9021578df2ab4287e0f8175"
        },
        "status":"PENDING",
        "amount":{
            "total":1000,
            "currency":"EGP"
        },
        "vat":{
            "total":0,
            "currency":"EGP"
        },
        "bankDebit":{
            "agreementId":"1647857006899",
            "agreementDuration":"2022-12-31",
            "storeCard":true
        }
    }
}

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

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
nextAction
JSON Object
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
bankDebit
JSON Object
agreementIdStringThe agreement ID in merchant system1647857006899
agreementDurationStringThe agreement duration in merchant system, the format is yyyy-MM-dd. The min duration is 1 day, the max duration is 5 years2022-12-31
storeCardBooleanValue must be truetrue
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]

To test your Bank Debit Payment, 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. {
        "amount": {
            "currency": "EGP",
            "total": 1000
        },
        "bankDebit": {
            "agreementDuration": "2022-12-31",
            "agreementId": "1647857006899",
            "storeCard": true
        },
        "callbackUrl": "https://your-call-back-url.com",
        "cancelUrl": "https://your-cancel-url.com",
        "collectCardInfo": true,
        "country": "EG",
        "expireAt": "30",
        "payMethod": "CardDebit",
        "product": {
            "description": "description",
            "name": "name"
        },
        "reference": "1647857006899",
        "returnUrl": "https://your-return-url.com",
        "userClientIP": "1.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.
amount
totalLongrequiredAmount(cent unit).If the amount is 0, we just bind the agreement and customer card info. If the amount is not 0, we will bind the agreement and customer card info, and complete the payment
currencyStringrequiredCurrency type. e.g. EGP
payMethodStringrequiredBank Debit Payment Method: cardAutoDebit
collectCardInfoBooleanrequiredValue must be true
bankDebit
JSON Object
agreementIdStringrequiredThe agreement ID in merchant system
agreementDurationStringrequiredThe agreement duration in merchant system, the format is yyyy-MM-dd. The min duration is 1 day, the max duration is 5 years
storeCardBooleanrequiredValue must be true
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.
cancelUrlStringoptionalThis URL is returned to the merchant's page when the consumer clicks the Cancel button
product
nameStringrequiredProduct name
descriptionStringrequiredProduct description
expireAtIntegeroptionalPayment expiration time in minutes.(default 30)
userClientIPStringoptionalIP address of customer's device. IPv4 or IPv6.
userInfo
JSON Object
userIdStringrequiredThe 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 Bank Debit payment request for an amount of 1000 EGP is as follows :

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

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

    public function test(){
        $data = [
            'amount'=>[
                'currency'=>'EGP',
                'total'=>1000
            ],
            'bankDebit'=>[
                'agreementDuration'=>'2022-12-31',
                'agreementId'=>'220321148180647368855',
                'storeCard'=>true
            ],
            'callbackUrl'=>'https://your-call-back-url.com',
            'cancelUrl'=>'https://your-cancel-url.com',
            'collectCardInfo'=>true,
            'country'=>'EG',
            'expireAt'=>'30',
            'payMethod'=>'CardDebit',
            'product'=>[
                'description'=>'description',
                'name'=>'name'
            ],
            'reference'=>'220321148180647368855',
            'returnUrl'=>'https://your-return-url.com',
            'userClientIP'=>'1.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 = {
    "amount": {
        "currency": "EGP",
        "total": 1000
    },
    "bankDebit": {
        "agreementDuration": "2022-12-31",
        "agreementId": "220321148180647368855",
        "storeCard": true
    },
    "callbackUrl": "https://your-call-back-url.com",
    "cancelUrl": "https://your-cancel-url.com",
    "collectCardInfo": true,
    "country": "EG",
    "expireAt": "30",
    "payMethod": "CardDebit",
    "product": {
        "description": "description",
        "name": "name"
    },
    "reference": "220321148180647368855",
    "returnUrl": "https://your-return-url.com",
    "userClientIP": "1.1.1.1",
    "userInfo": {
        "userEmail": "[email protected]",
        "userId": "666666",
        "userMobile": "201066668888",
        "userName": "David"
    }
};

var privateKey = "OPAYPRV16384408******1513"

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': '281821120275234',
      '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: 281821120675251' \
--header 'Authorization: Bearer 2c594257818041f28142be07974f02badf4d65e148552c09b384a0bc69495fd44851e13bdec11bc629e8a7a7c41aa86fb144b0a3e4edb079329548153f24a327' \
--header 'Content-Type: application/json' \
--data-raw '{
    "amount": {
        "currency": "EGP",
        "total": 1000
    },
    "bankDebit": {
        "agreementDuration": "2022-12-31",
        "agreementId": "220321148180647368855",
        "storeCard": true
    },
    "callbackUrl": "https://your-call-back-url.com",
    "cancelUrl": "https://your-cancel-url.com",
    "collectCardInfo": true,
    "country": "EG",
    "expireAt": "30",
    "payMethod": "CardDebit",
    "product": {
        "description": "description",
        "name": "name"
    },
    "reference": "220321148180647368855",
    "returnUrl": "https://your-return-url.com",
    "userClientIP": "1.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.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;
import java.util.UUID;

public class BindBankDebitAgreementNoPCI {

    private static final String privateKey = "OPAYPRV16384408******1513";

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

    private static final String merchantId = "281821120275234";

    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 amount = new TreeMap<>();
        amount.put("currency","EGP");
        amount.put("total",1000);
        order.put("amount",amount);
        TreeMap bankDebit = new TreeMap<>();
        bankDebit.put("agreementDuration","2022-04-01");
        bankDebit.put("agreementId",UUID.randomUUID().toString());
        bankDebit.put("storeCard",true);
        order.put("bankDebit",bankDebit);
        order.put("callbackUrl","https://your-callback-url.com");
        order.put("country","EG");
        order.put("collectCardInfo",true);
        order.put("merchantName","merchantName");
        order.put("payMethod","CardDebit");
        TreeMap product = new TreeMap<>();
        product.put("description","description");
        product.put("name","name");
        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);
    }
}


Bank Debit Payment 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": "104123398",
		"orderNo": "211004140885521681",
		"nextAction": {
			"actionType": "REDIRECT_INPUTCARD",
			"redirectUrl": "https://sandboxapi.opaycheckout.com/api/v1/international/transaction/3ds/e9f25ec9bd4139329aaa9ab784775220aed5ca97f9021578df2ab4287e0f8175"
		},
		"status": "PENDING",
		"amount": {
			"total": 1000,
			"currency": "EGP"
		},
		"vat": {
			"total": 0,
			"currency": "EGP"
		},
		"bankDebit": {
			"agreementId": "220321148180647368855",
			"agreementDuration": "2022-12-31",
			"storeCard": true
		}
	}
}

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

ParametertypeDescriptionexample
referenceStringThe unique merchant payment order number.202111300001
orderNoStringOPay transaction number211130148131809099
nextAction
JSON Object
actionTypeStringNext action type, enum[REDIRECT_INPUTCARD]REDIRECT_INPUTCARD
redirectUrlStringInout card redirect url.https://sandboxapi.opaycheckout.com/api/v1/international/transaction/3ds/e9f25ec9bd4139329aaa9ab784775220aed5ca97f9021578df2ab4287e0f8175
statusStringThis E-Wallet order statusPENDING
amount
JSON Object
totalLongTransaction amount1000 (cent unit)
currencyStringCurrency typeEGP
vat
JSON Object
totalLongValue Added Tax Amount0
currencyStringCurrency typeEGP
bankDebit
JSON Object
agreementIdStringThe agreement ID in merchant system220321148180647368855
agreementDurationStringThe agreement duration in merchant system, the format is yyyy-MM-dd. The min duration is 1 day, the max duration is 5 years2022-12-31
storeCardBooleanValue must be truetrue
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.
02003payMethod not support.
02004the payment reference already exists.
02002merchant not configured with this function.
05057The agreementId does not exist
05058The agreementId already exists
05059The agreementId is invalid!
05060The agreement has expired
05061The agreement status is unavailable
02007merchant not available.
50003service not available, please try again.
5023The %s parameter is required
5024The value of enable3DS must be true

What's Next?