Close Bank Debit Agreement API

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

Close Bank Debit Agreement

To test close Bank Debit Agreement, 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/agreement/close

-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/agreement/close

-Request Parameters:

  1. Header: Authorization(API Calls Signature), MerchantId
  2. Authorization    : Bearer {signature}
    MerchantId       : 256612345678901
  3. Json object containing the transaction information:
  4. {
        "agreementId": "2203211****647368855"
    }

HTTP POST parameters

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

ParametertyperequiredDescription
agreementIdStringrequiredAgreement ID.

-An example of Close Agreement request is as follows :

class BankDebitAgreementIDOnlyController
{
    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/agreement/close';
    }

    public function test(){
        $data = [
            'agreementId'=>'220321148180647368855'
          ]
        ;
        $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 = {
  "agreementId": "123321"
};

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/agreement/close',
    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/agreement/close' \
--header 'MerchantId: 281821120675251' \
--header 'Authorization: Bearer 38d469216d845f844dc571e6e2d36359f3b0bd3af011cd5f4cc54f1bd60ab2b652768a85746d8614cdcccb8c8a4d4decb26b2285709ad94fea1b3903e02d429c' \
--header 'Content-Type: application/json' \
--data-raw '{
    "agreementId": "test2021_1643349294500"
}'
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 BankDebitAgreementIDOnly {

    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/agreement/close";
        Gson gson = new Gson();
        TreeMap data = new TreeMap<>();
        data.put("agreementId","123321");

        String requestBody = gson.toJson(data);
        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);
    }
}

Close Bank Debit Agreement Response

-Response Parameters:

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

{
    "code":"00000",
    "message":"SUCCESSFUL",
    "data":{
        "agreementId":"104123398",
        "expiredTime":"1653988447",
        "createTime":"1653988447",
        "agreementStatus":"SUCCESS",
        "userId":"123",
        "bankDetails":{
            "cardNumber":"123****",
            "cardBrand":"card brand",
            "bankName":"eg bank",
            "cardType":"card type",
            "expiryYear":"2022",
            "expiryMonth":"12",
        }
    }
}

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

ParametertypeDescriptionexample
agreementIdStringAgreement Id.123321
expiredTimeStringAgreement expire time1653988447
createTimeStringAgreement create time1653988447
agreementStatusString[INITIAL, EXPIRED, SUCCESS, FAIL, CLOSE]SUCCESS
userIdStringuser id123
bankDetails
cardNumberstringcard number512345*********0008
cardBrandstringcard brandMASTERCARD
bankNamestringbank name***************BANK
cardTypestringcard typeCREDIT
expiryYearstringexpire year2022
expiryMonthstringexpire month12

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": "05057",
    "message": "The agreementId 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?