Get Invoice Statistics

The powerful analytics feature obtained at OPay merchant dashboard can be also be obtained easily within any application you are developing. Use our get invoice statistics API to get the required information that will let you design your own analytics screen. Just provide your time range, and OPay will respond with all invoices information during your selected time range. You will get an informative response with your paid, unpaid, cancelled, and expired invoices.

Get Invoice Statistics

To obtain your invoices statistics, you need to request using the POST method in our sandbox environment.
-Here is the request URL:

https://sandboxapi.opaycheckout.com/api/v1/international/invoice/getInvoicesStatistics

-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/invoice/getInvoicesStatistics

-Request Parameters:

  1. Header: Authorization(API Calls Signature), MerchantId
  2. Authorization    : Bearer {signature}
    MerchantId       : 256612345678901
  3. Json object containing the request information:
  4. {
         "startCreateTime": 1635333272,
         "endCreateTime": 1635336812,
    }

HTTP POST Parameters

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

ParametertyperequiredDescription
startCreateTimeLongrequiredThe start time of invoice creation. Timestamp. Unit: second. e.g.1635333272
endCreateTimeLongrequiredThe end time of invoice creation. Timestamp. Unit: second. e.g.1635333272

-An example of invoice statistics request is as follows :

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

    public function __construct() {
        $this->merchantId = '256612345678901';
        $this->secretkey = 'OPAYPRV16357783346230.07653446106051542';
        $this->url = 'https://sandboxapi.opaycheckout.com/api/v1/international/invoice/getInvoicesStatistics';
    }

    public function test(){
        $data = [
            'endCreateTime'=>1698373138,
            'startCreateTime'=>1618353138
        ];
        $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 = {
  "endCreateTime":1698373138,
  "startCreateTime":1618353138
};

var privateKey = "OPAYPRV16357783346230.07653446106051542"

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/invoice/getInvoicesStatistics',
    method: 'POST',

    headers: {
      'MerchantId': '256612345678901',
      '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/invoice/getInvoicesStatistics' \
--header 'MerchantId: 256612345678901' \
--header 'Authorization: Bearer 747fa19bc95d75bfe513302d709dfca5e79ddb11bb3aac2df5eb3388a3bdafbe9880bebdf01ee3e4dc710d2b8ba87431a73cfea4b6e4f24705f72e462f021ebf' \
--header 'Content-Type: application/json' \
--data-raw '{
    "startCreateTime":1618353138,
    "endCreateTime":1698373138
}'
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 GetInvoicesStatistics {
    /** */
    private static final String privateKey = "OPAYPRV16357783346230.07653446106051542";
    /** */
    private static final String endpoint = "https://sandboxapi.opaycheckout.com";
    /** */
    private static final String merchantId = "256612345678901";

    public static void main(String[] args) throws Exception {
        String addr = endpoint + "/api/v1/international/invoice/getInvoicesStatistics";
        Gson gson = new Gson();
        TreeMap order = new TreeMap<>();
        order.put("startCreateTime",1618353138);
        order.put("endCreateTime",1698373138);

        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.

Invoice Statistics Response

-Response Parameters:

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

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data": {
        "unpaidInvoiceList": [
            {
                "totalAmount": {
                    "total": 31001300,
                    "currency": "EGP"
                },
                "totalCount": 15,
                "country": "EG"
            }
        ],
        "paidInvoiceList": [
            {
                "totalAmount": {
                    "total": 31039621,
                    "currency": "EGP"
                },
                "totalCount": 8,
                "country": "EG"
            }
        ],
        "expiredInvoiceList": [
            {
                "totalAmount": {
                    "total": 728,
                    "currency": "EGP"
                },
                "totalCount": 1,
                "country": "EG"
            }
        ],
        "canceledInvoiceList": [
            {
                "totalAmount": {
                    "total": 802,
                    "currency": "EGP"
                },
                "totalCount": 1,
                "country": "EG"
            }
        ]
    }
}

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

ParametertypeDescriptionexample
codeStringTransaction response code.00000
messageStringTransaction response information.SUCCESSFUL
unpaidInvoiceList

Json Array

totalAmount

Json Object

totalLongInvoice Amount.10000 (cents)
currencyStringCurrency type.EGP
totalCountIntegerTotal count of unpaid invoices.15
countryStringCountry code.EG
paidInvoiceList

Json Array

totalAmount

Json Object

totalLongInvoice Amount.10000 (cents)
currencyStringCurrency type.EGP
totalCountIntegerTotal count of paid invoices.15
countryStringCountry code.EG
expiredInvoiceList

Json Array

totalAmount

Json Object

totalLongInvoice Amount.10000 (cents)
currencyStringCurrency type.EGP
totalCountIntegerTotal count of expired invoices.15
countryStringCountry code.EG
canceledInvoiceList

Json Array

totalAmount

Json Object

totalLongInvoice Amount.10000 (cents)
currencyStringCurrency type.EGP
totalCountIntegerTotal count of canceled invoices.15
countryStringCountry code.EG

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": "20000",
    "message": "Duplicate merchant order number",
    "data": null
}

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
Invalid characters in mobile number.
Invalid characters in mobile number.
Mobile number format should be like this +201088889999
Merchant Product ID does not exist, please create it in merchant dashboard first.
Please merge the same products.
Products is required.
Invoice amount can not be 0

What's Next?

You can create e-invoice.
You can gat the status of your invoice through the invoice details query API.
You can cancel any of your unpaid invoices.