1.1.1. MAPI – mPOS API

MAPI Overview

mPOS is a device that is able to read plastic card data (like magnetic stripe tracks) and transmit this data to the Payneteasy mPOS API in an encrypted form.
mPOS API currently consists of two payment operations (Sale, Preauthorization) which correspond to Sale Transactions and Preauth Transactions, respectively, and a few other auxiliary operations.

Mobile App integration flow

Payneteasy contact manager creates dedicated account on sandbox environment and provides integrator with test ENDPOINTID, merchant_control_key and test mPOS devices with pre-installed encryption key for processing transaction on the sandbox. mPOS devices (which has a serial number) is handed to integrator (by courier) along with SDK for communication. Integrator team implements communication MAPI commands (Sale, Preauth, Add Signature) and MobileApp-to-mPOS communication tailoring their needs. While implementation Integrator has to choose from two types of MAC (message authentication code) approaches:

  • HMAC-SHA1 (preferred)
  • RSA-SHA1 (more heavyweight, but more secured)
All secondary transactions (Reversal, Capture and so on) are made using the regular Merchant API or UI. mPOS API (MAPI) All MAPI URLs reside under
https://gate.payneteasy.com/paynet/mapi/v1/
for integration purposes use staging environment sandbox.payneteasy.com instead of production gate.payneteasy.com

Sale Operation

Sale transactions are initiated by mPOS through HTTPS POST request by using URL in the following format:
https://gate.payneteasy.com/paynet/mapi/v1/sale/ENDPOINTID
for integration purposes use staging environment sandbox.payneteasy.com instead of production gate.payneteasy.com

The End point ID is an entry point for incoming Merchant’s transactions and is actually the only Payneteasy object which is exposed via API.

General Sale Process Flow

Application initiates a transaction by sending HTTPS POST request to the specified URL Payneteasy server immediately returns the response back to Application. The response contains paynet-order-id. For detailed request and response format see mPOS Sale Request Parameters Table.

Application shows the Customer message like Your order is being processed. Please, wait…. Application starts polling Payneteasy server for transaction status using paynet-order-id obtained at previous step. Status polling request and response are described in Order status asynchronous call

Sale transaction diagram

The Application should use Payneteasy API as described in General Sale Process Flow.

Merchant -> "Payneteasy": Sale request
activate "Payneteasy"
"Payneteasy" --> Merchant: Order ID

"Payneteasy" -> Acquirer: Process sale
activate Acquirer

Merchant -> "Payneteasy": Get status by Order ID

Acquirer --> "Payneteasy": Processing result
deactivate Acquirer

"Payneteasy" --> Merchant: Final status
deactivate "Payneteasy"

Sale request Customer checks out the order and Application sends Sale request to Payneteasy server with specified parameters described in Sale Request Parameters.
Order Id Payneteasy server sends back the response with orderid. Application shows the customer a message like Your order is being processed. Please, wait… and starts polling for status with given orderid as described in Order status asynchronous call.
Process Sale Payneteasy server forwards Sale request to bank acquirer asynchronously. The bank starts processing the transaction.
Get status by Order Id Application is polling for status with given orderid as described in Order status asynchronous call.
Sale approved or declined The bank responds to Payneteasy server with approve or decline for requested Sale
Return Status – approved or declined Payneteasy server returns status to Application through Order status asynchronous call.

Process Sale transaction

mPOS Sale Request Parameters

In order to initiate a Sale transaction via mPOS, Application sends an HTTPS POST request with the parameters specified in mPOS Sale Request Parameters Table below

mPOS Sale Request Parameter Length/Type Comment Necessity*
client_orderid 128/String Merchant order identifier Mandatory
order_desc 64k/String Brief order description Mandatory
first_name 50/String Customer’s first name Optional
last_name 50/String Customer’s last name Optional
ssn 32/Numeric Last four digits of the customer’s social security number Optional
birthday 8/Numeric Customer’s date of birth, in the format MMDDYY Optional
address1 50/String Customer’s address line 1 Mandatory
city 50/String Customer’s city Mandatory
state 2-3/String Customer’s state . Please see Reference for a list of valid state codes. Mandatory for USA, Canada and Australia Optional
zip_code 10/String Customer’s ZIP code Mandatory
country 2/String Customer’s country(two-letter country code). Please see Reference for a list of valid country codes Mandatory
phone 15/String Customer’s full international phone number, including country code Optional
cell_phone 15/String Customer’s full international cell phone number, including country code Optional
email 50/String Customer’s email address Mandatory
amount 10/Numeric Amount to be charged. The amount has to be specified in the highest units with . delimiter. For instance, 10.5 for USD means 10 US Dollars and 50 Cents Mandatory
currency 3/String Currency the transaction is charged in (three-letter currency code). Sample values are: USD for US Dollar EUR for European Euro Mandatory
cvv2 3-4/Numeric Customer’s CVV2 code. CVV2 (Card Verification Value) is a three- or four-digit number AFTER the credit card number in the signature area of the card. It used if acquirer provides only E-Commerce connection Optional
ipaddress 45/String Customer’s IP address, included for fraud screening purposes Mandatory
purpose 128/String Destination to where the payment goes. It is useful for the merchants who let their clients to transfer money from a credit card to some type of client’s account, e.g. game or mobile phone account. Sample values are: +7123456789; gamer0001@ereality.com etc. This value will be used by fraud monitoring system Optional
server_callback_url 1024/String URL the transaction result will be sent to. Merchant may use this URL for custom processing of the transaction completion, e.g. to collect sales data in Merchant’s database. See more details at Merchant Callbacks Optional
encrypted-type 32/String Type of the encryption. This depends on mPOS model Mandatory
encrypted-data String Card tracks data encrypted using encrypted-type encryption and encoded using HEX encoding. For more info contact support Mandatory
* leading and trailing whitespace in input parameters will be omitted

Please note the following characters must be escaped in the parameter values: & + \.

Sale Request Example

client_orderid=123098
&cvv2=XXX
&amount=114.94
&ipaddress=115.135.52.242
&state=
&currency=USD
&phone=+6072344354
&zip_code=81200
&order_desc=Super product 1
&email=francislusaikun@yahoo.com
&country=MY
&city=Johor Bahru
&address1=11Jalan Lurah 6 Kg. Kempas Baru
&redirect_url=http://MERCHANT_SITE/payment_update/123098/
&encrypted-type=algo-name
&encrypted-data=D0902DD0B02120D09220D090D184D180D0B8D0BAD0B520D180D0B5D0BAD0B820D0B2D0BED18220D18
                2D0B0D0BAD0BED0B920D188D0B8D180D0B8D0BDD18B210AD0902DD0B02120D09220D090D184D180D0
                B8D0BAD0B520D0B3D0BED180D18B20D0B2D0BED18220D182D0B0D0BAD0BED0B920D0B2D18BD188D0B
                8D0BDD18B210AD0902DD0B02C20D0BAD180D0BED0BAD0BED0B4D0B8D0BBD18B2DD0B1D0B5D0B3D0B5
                D0BCD0BED182D18B2C0AD0902DD0B02C20D0BED0B1D0B5D0B7D18CD18FD0BDD18B2DD0BAD0B0D188D
                0B0D0BBD0BED182D18B2C0AD0902DD0B02C20D0B820D0B7D0B5D0BBD191D0BDD18BD0B920D0BFD0BE
                D0BFD183D0B3D0B0D0B921

Sale Response

Sale Response Parameter Description
type The type of response. May be async-response, validation-error, error. If type equals validation-error or error, error-message and error-code parameters contain error details
status See Status List for details
paynet-order-id Order id assigned to the order by Payneteasy
merchant-order-id Merchant order id
serial-number Unique number assigned by Payneteasy server to particular request from the Merchant
error-message If status is error this parameter contains the reason for decline or error details
error-code The error code is case of error status

Sale Response Example

type=async-response
&serial-number=00000000-0000-0000-0000-0000000624e8
&merchant-order-id=59e1e3ca-5d44-11e1-b3d6-002522b853b4
&paynet-order-id=94935

Server callback result

Upon completion by the System of request processing it returns the result on the specified server_callback_url with the following parameters described in Sale, Return Callback Parameters The checksum is used to ensure that the callback is initiated for a particular Merchant, and not for anybody else claiming to be such Merchant. This SHA-1 checksum, the control parameter, is created by concatenation of the parameters values in the following order:

  • status
  • orderid
  • client_orderid
  • merchant_control

A complete string example may look as follows:

approvedS279G323P4T1209294c258d6536ababe653E8E45B5-7682-42D8-6ECC-FB794F6B11B1

Encrypt the string using SHA-1 algorithm. The resultant string yields the control parameter. For the above-mentioned example the control will take the following value:

e04bd50531f45f9fc76917ac78a82f3efaf0049c

All parameters are sent via GET method.

Server callback result example

status=declined
&error-message=Decline, refer to card issuer
&error-code=107
&paynet-order-id=S279G323P4T1209294
&merchant-order-id=c258d6536ababe65

Request authorization through OAuth signature

To make sure that it’s the Merchant (and not somebody else) is who really authors requests, requests must be signed. OAuth 1.0a signature is used as a well-established and supported in the client libraries for this purpose on MAPI requests. Please note that it’s the only part of OAuth that we use in our API: signatures; our API does not actually support a full-blown OAuth. Both RSA-SHA1 and HMAC-SHA1 methods may be used to generate signatures.

Request signing with RSA-SHA1 signature method

This signature method is only available if mPOS was registered with RSA public key. No shared secret is needed. Merchant just uses his private key to sign requests. Reader serial number is used as an API token. Here is an example of how to make a signed request in Java with help of scribe library:

import com.payneteasy.tlv.HexUtil;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.*;
import org.scribe.oauth.OAuth10aServiceImpl;
import org.scribe.oauth.OAuthService;
import org.scribe.services.HMACSha1SignatureService;
import org.scribe.services.SignatureService;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class App
{
    public String doPost(String url, Map<String, String> parameters) throws ConnectionIOException, ConnectionTimeoutException
    {
        OAuthConfig config = new OAuthConfig(apiToken, merchantControlKey, OAuthConstants.OUT_OF_BAND, SignatureType.Header, null,null);
        OAuthService service = new OAuth10aServiceImpl(new HmacSha1Mapi(), config);
        OAuthRequest request = new OAuthRequest(Verb.POST, url);
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            request.addBodyParameter(entry.getKey(), entry.getValue());
        }
        // empty token for 'two-legged'
        Token token = new Token("", "");
        service.signRequest(token, request);
        Response response = request.send();
        return response.getBody();
        //System.out.println(response.getBody());
    }

    private static class HmacSha1Mapi extends DefaultApi10a {
        @Override
        public String getRequestTokenEndpoint() {
            return null; // not used
        }

        @Override
        public String getAccessTokenEndpoint() {
            return null; //not used
        }

        @Override
        public String getAuthorizationUrl(Token requestToken) {
            return null; // not used
        }

        @Override
        public SignatureService getSignatureService() {
            return new HMACSha1SignatureService();
        }
    }

Request signing with HMAC-SHA1 signature method

This signature method is always available even for mPOS registered without a public key. Merchant control key is used as a secret key. Reader serial number is used as an API token. Here is an example of how to make a signed request in Java with help of scribe library:

public String doPost(String url, Map<String, String>parameters) throws ConnectionIOException, ConnectionTimeoutException {
        OAuthConfig config = new OAuthConfig(apiToken, merchantControlKey, OAuthConstants.OUT_OF_BAND,
                SignatureType.Header, null,null);
        OAuthService service = new OAuth10aServiceImpl(new HmacSha1Mapi(), config);
        OAuthRequest request = new OAuthRequest(Verb.POST,url);
        for (Map.Entry < String,String >;entry :parameters.entrySet()){
            request.addBodyParameter(entry.getKey(), entry.getValue());
        } // empty token for 'two-legged'
        OAuth Token token = new Token("", "");
        service.signRequest(token, request);
        Response response = request.send();
        return response.getBody();
    }

    private static class Mapi extends DefaultApi {
        @Override
        public String getRequestTokenEndpoint() {
            return null; // not used
        } @Override public String getAccessTokenEndpoint() {
            return null; //not used
        }

        @Override
        public String getAuthorizationUrl(Token requestToken) {
            return null; // not used
        }
        @Override
        public SignatureService getSignatureService() {
            return new HMACSha1SignatureService();
        }
    }

Order status

Application must use Order status API call to get the customer’s order transaction status. After any type of transaction is sent to Payneteasy server and order id is returned, Application should poll for transaction status. When transaction is processed on Payneteasy server side it returns it’s status back to Application and at this moment the Application is ready to show the customer transaction result, whether it’s approved or declined.

Status API URL

Status API calls are initiated through HTTPS POST request by using URL in the following format:
https://gate.payneteasy.com/paynet/api/v2/status/ENDPOINTID
for integration purposes use staging environment sandbox.payneteasy.com instead of production gate.payneteasy.com

The End point ID is an entry point for incoming Merchant’s transactions and is actually the only Payneteasy object which is exposed via API.

Order status call parameters

Status call Parameter Description
login Merchant login name
client_orderid Merchant order identifier of the transaction for which the status is requested
orderid Order id assigned to the order by Payneteasy
control Checksum used to ensure that it is Payneteasy (and not a fraudster) that initiates the callback for a particular Merchant. This is SHA-1 checksum of the concatenation login + client-order-id + paynet-order-id + merchant-control. See Order status API call authorization through control parameter for more details about generating control checksum

Order Status Response

Status Response Parameter Description
type The type of response. May be status-response
status See Status List for details
paynet-order-id Order id assigned to the order by Payneteasy
merchant-order-id Merchant order id
phone Customer phone
amount Initial transaction amount
serial-number Unique number assigned by Payneteasy server to particular request from the Merchant
last-four-digits Last four digits of customer credit card number
bin Bank BIN of customer credit card number
card-type Type of customer credit card (VISA, MASTERCARD, etc)
gate-partial-reversal Processing gate support partial reversal (enabled or disabled)
gate-partial-capture Processing gate support partial capture (enabled or disabled)
transaction-type Transaction type (sale, reversal, capture, preauth)
processor-rrn Bank Receiver Registration Number
processor-tx-id Acquirer transaction identifier
receipt-id Electronic link to receipt https://gate.payneteasy.com/paynet/view-receipt/ENDPOINTID/receipt-id/
cardholder-name Cardholder name
card-exp-month Card expiration month
card-exp-year Card expiration year
card-hash-id Unique card identifier to use for loyalty programs or fraud checks
email Customer e-mail
bank-name Bank name by customer card BIN
terminal-id Acquirer terminal identifier to show in receipt
paynet-processing-date Acquirer transaction processing date
approval-code Bank approval code
order-stage The current stage of the transaction processing. See Order Stage for details
loyalty-balance The current bonuses balance of the loyalty program for current operation. if available
loyalty-message The message from the loyalty program. if available
loyalty-bonus The bonus value of the loyalty program for current operation. if available
loyalty-program The name of the loyalty program for current operation. if available
descriptor Bank identifier of the payment recipient
error-message If status in declined, error, filtered this parameter contains the reason for decline
error-code The error code is case status in declined, error, filtered
verified-3d-status See 3-D Secure Status List for details
verified-rsc-status See Random Sum Check Status List for details
transaction-date Date of final status assignment for transaction.

Order Status Response Example

type=status-response
&serial-number=00000000-0000-0000-0000-0000005b5ecf
&merchant-order-id=006349-000117
&processor-tx-id=PNTEST-158258
&paynet-order-id=158258
&status=approved
&amount=1.00
&descriptor=WORLD+ORDER+AG
&gate-partial-reversal=enabled
&gate-partial-capture=enabled
&transaction-type=sale
&receipt-id=e876012c-d94e-3462-8e2e-a1bb4cb30633
&name=PKMVC%2FUNEMBOSSED
&cardholder-name=PKMVC%2FUNEMBOSSED
&card-exp-month=10
&card-exp-year=2015
&email=no-email
&processor-rrn=509275795375
&approval-code=378906
&order-stage=sale_approved
&last-four-digits=0985
&bin=462783
&card-type=VISA
&bank-name=MOSCOMPRIVATBANK+%28MOSCOW+COMMERCIAL+BANK%29
&terminal-id=12345678
&paynet-processing-date=2015-04-02+20%3A36%3A20+MSK
&card-hash-id=1575636
&verified-3d-status=AUTHENTICATED
&verified-rsc-status=AUTHENTICATED
&transaction-date=2023-01-10+12%3A46%3A28+MSK

Status request authorization through control parameter

The checksum is used to ensure that it is Merchant (and not a fraudster) that sends the request to Payneteasy. This SHA-1 checksum, the parameter control, is created by concatenating of the values of the parameters in the following order:

  • login
  • client_orderid
  • orderid
  • merchant_control

For example assume the following values are corresponds the parameters above:

Parameter Name< Parameter Value
login cool_merchant
client_orderid 5624444333322221111110
orderid 9625
merchant_control r45a019070772d1c4c2b503bbdc0fa22

The complete string example may look as follows:

cool_merchant56244443333222211111109625r45a019070772d1c4c2b503bbdc0fa22

Encrypt the string using SHA-1 algorithm. The resultant string yields the control parameter which is required for authorizing the callback. For the example control above will take the following value:

c52cfb609f20a3677eb280cc4709278ea8f7024c

Order status Debug

endpointid input your ENDPOINTID
login
client_orderid input your Invoice Number
orderid
merchant_control input your Control Key
by-request-sn

String to sign
Signature
              
            
 

Preauth Operation

Preauth transactions are initiated by mPOS through HTTPS POST request by using URL in the following format:
https://gate.payneteasy.com/paynet/mapi/v1/preauth/ENDPOINTID
for integration purposes use staging environment sandbox.payneteasy.com instead of production gate.payneteasy.com

Flow and parameters are similar to Sale transaction.

Add Signature

Signature in this operation is a vector picture attached to an order.
HTTPS POST request is sent to URL in the following format:
https://gate.payneteasy.com/paynet/mapi/v1/add-signature/{endPointId}/{orderId}/{shaHex}
For integration purposes use staging environment sandbox.payneteasy.com instead of production gate.payneteasy.com.
Request is signed with oauth1.0a using HMAC-SHA1. Secret key (HMAC) for signature is made of merchant login and control key.
Picture data is sent via raw POST body. The {shaHex} is SHA-1 digest from the picture data encoded as HEX.

Picture is being sent as a JSON object (as presented below):

{"width": 580, "height": 601, "glyphs": [
    [
        [19, 135, 0],
        [20, 139, 83],
        [20, 143, 92],
        [22, 150, 102],
        [24, 159, 110],
        [26, 172, 120]
    ],
    [
        [27, 157, 0],
        [29, 156, 526]
    ]
]}

Each point contains X, Y coordinates of signature line and the time spent from the starting point (to reproduce animation).

Закрытие дня

Описание закрытия дня

Деньги переводятся на расчетный счет торговца после закрытия дня. При неуспешном завершении процедуры закрытия дня или если процедура закрытия вовсе не инициируется торговцем, операция клиринга не производится, таким образом деньги не зачисляются на расчетный счет торговца.

Если по какой-либо причине не удается провести закрытие дня, используя «Удаленное закрытие дня», необходимо провести операцию закрытия дня вручную через личный кабинет или обратиться за помощью в службу поддержки.

Данная операция доступна не для всех эквайеров, за информацией обращайтесь в службу поддержки.

Для закрытия дня доступны следующие способы:

Принудительное закрытие дня

Автоматическое закрытие дня

Автоматическое закрытие дня по заранее установленному времени

Удаленное закрытие дня

Принудительное закрытие дня

Для принудительного закрытия дня менеджеру или его сотруднику в личном кабинете системы надо перейти в настройки шлюза, для которого требуется закрыть день.

pic1 close_day

pic2 close_day

На странице шлюза нажмите кнопку “Закрыть день” и подтвердите закрытие дня на всплывающем окне. На странице начнет отображаться окно “Закрытие дня для ‘имя шлюза’”, дождитесь завершения операции.

pic3 close_day

После успешного закрытия дня на странице шлюза будет отображена информация о дате закрытия и сумме транзакций с момента последнего закрытия дня для данного шлюза до текущего закрытия дня.

pic4 close_day

Warning

Во время закрытия дня шлюз блокируется и транзакции по нему проходить не будут.

Автоматическое закрытие дня

Для автоматического закрытия дня менеджеру или его сотруднику в личном кабинете системы надо перейти в настройки шлюза, для которого требуется закрывать день автоматически.

pic1 close_day

pic2 close_day

На странице шлюза нажмите кнопку “Редактировать”, поставьте галочку напротив пункта “Автоматическое закрытия дня” и нажмите “Сохранить”.

pic5 close_day
При автоматическом закрытии дня оптимальное время закрытия выбирается системой автоматически (ближе к концу рабочего дня по МСК).

Warning

Во время автоматического закрытия дня шлюз блокируется и транзакции по нему проходить не будут.

После успешного автоматического закрытия дня на странице шлюза будет отображена информация о дате закрытия и сумме транзакций с момента последнего закрытия дня для данного шлюза до текущего закрытия дня.

pic4 close_day

Автоматическое закрытие дня по заранее установленному времени

Для автоматического закрытия дня по заданному времени менеджеру или его сотруднику в личном кабинете системы надо перейти в настройки шлюза, для которого требуется закрывать день автоматически в установленное время.
pic1 close_day

pic2 close_day
На странице шлюза нажмите кнопку “Редактировать”, поставьте галочку напротив пункта “Закрывать день автоматически”, появится пункт “Время закрытия дня”, нужно выставить время закрытия дня, затем нажать “Сохранить”.
Обратите внимание, что пункт “Автоматическое закрытия дня” должен быть выключен, иначе время закрытия дня будет выбрано автоматически системой.
pic6 close_day

Закрытие дня будет выполняться в заданное время, после успешного закрытия дня на странице шлюза будет отображена информация о дате закрытия и сумме транзакций с момента последнего закрытия дня для данного шлюза до текущего закрытия дня.

pic6 close_day

Warning

Во время автоматического закрытия дня по заданному времени шлюз блокируется и транзакции по нему проходить не будут.

Удаленное закрытие дня

Удаленное закрытие дня позволяет закрыть день сразу на всех шлюзах определенного терминала. Для этого необходимо для ВСЕХ шлюзов ассоциированных с терминалом установить в настройках “Удаленное закрытие дня”.
Для удаленного закрытия дня менеджеру или его сотруднику в личном кабинете системы надо перейти в настройки шлюза, для которого требуется включить удаленное закрытие дня.
pic1 close_day

pic2 close_day
На странице шлюза нажмите кнопку “Редактировать”, поставьте галочку напротив пункта “Удаленное закрытие дня”, при необходимости, задайте число дней через которое будет срабатывать автоматическое закрытие дня, начиная с последнего успешного удаленного закрытия дня - пункт “Максимальная задержка закрытия дня (дн.)”, автоматически устанавливается 3 дня, затем нажмите “Сохранить”.
pic8 close_day

Warning

Во время удаленного закрытия дня шлюзы блокируются и транзакции по ним проходить не будут.

Для инициации Удаленного закрытия дня необходимо отправить HTTP запрос следующего вида:
POST https://${hostname}/paynet/api/v2/close-day/{endpointId}
Аутентификация пользователя происходит по OAuth 1.0, описание: OAuth

Тело запроса

В теле запроса укажите данные со следующей структурой:
{
  "day_close_request_id": {string},
  "sale_approved_count": {string},
  "sale_approved_sum": {string},
  "reversal_approved_count": {string},
  "reversal_approved_sum": {string}
}
Имя свойства Тип(длина) Описание
Обязательные параметры
day_close_request_id string(8-32) Уникальный идентификатор запроса. Может содержать буквы и цифры
Необязательные параметры
sale_approved_count string Число подтвержденных sale транзакций
sale_approved_sum string Сумма по подтвержденным sale транзакциям
reversal_approved_count string Число подтвержденных reversal транзакций
reversal_approved_sum string Сумма по подтвержденным reversal транзакциям

Тело ответа

Пользователь генерирует идентификатор запроса и посылает запрос на закрытие дня. Если этот идентификатор используется впервые - начинается инициализация закрытия дня для гейта(ов), ассоциированного(ых) с переданным идентификатором терминала. Пользователю возвращается асинхронный ответ со статусом ‘starting’.
Пример структуры ответа следующий:
{
  "response": {
    "status": "starting",
    "gates": [ {
      "gateId": 193,
      "isDayClosing": true,
      "epntId": 1
      }, {
      "gateId": 82,
      "isDayClosing": true,
      "epntId": 1
      }, {
      "gateId": 317,
      "isDayClosing": true,
      "epntId": 1
    }
    ]
  },
  "theRequestSerialNumber": "00000000-0000-0000-0000-00000000001c"
}
Имя свойства Тип Описание
status string Статус операции закрытия дня
gateId long Идентификатор шлюза по которому происходит закрытие дня
isDayClosing boolean Флаг закрытия дня, при значении true - шлюз заблокирован
epntId long Свойство, присваемое банком терминалу при его настройке в системе банка
theRequestSerialNumber string Серийный номер запроса закрытия дня
Запрос с идентификатором day_close_request_id, уже использованным ранее, выполняет функцию статус-запроса. После первичного (инициирующего запроса) пользователь может продолжать посылать запросы по тому же адресу с тем же самым идентификатором запроса. В данном случае, этот идентификатор всегда будет ассоциирован с процедурой закрытия дня, которую он инициировал. Пока операция по закрытию дня в процессе выполнения - пользователю будет возвращаться асинхронный ответ со статусом ‘processing’.
Пример структуры ответа следущий:
{
  "response": {
    "status": "processing",
    "gates": [ {
      "gateId": 193,
      "isDayClosing": true,
      "epntId": 1
      }, {
      "gateId": 82,
      "isDayClosing": true,
      "epntId": 1
      }, {
      "gateId": 317,
      "isDayClosing": true,
      "epntId": 1
    }
    ]
  },
  "theRequestSerialNumber": "00000000-0000-0000-0000-00000000001e"
}
Имя свойства Тип Описание
status string Статус операции закрытия дня
gateId long Идентификатор шлюза по которому происходит закрытие дня
isDayClosing boolean Флаг закрытия дня, при значении true - шлюз заблокирован
epntId long Свойство, присваемое банком терминалу при его настройке в системе банка
theRequestSerialNumber string Серийный номер запроса закрытия дня
Информация о закрытом дне появится в ответе от сервера по мере ее поступления от процессоров (в случае одновременного закрытия нескольких гейтов). После закрытия дня гейта(ов) статус ответа примет значение ‘finished’, вне зависимости от того, завершилось ли закрытие дня на всех гейтах успешно, или часть гейтов (или все) закрылись с ошибкой.

Warning

Если во время удаленного закрытия дня шлюз(ы) останутся в заблокированном состоянии (в теле ответа при “status”: “finished” для шлюза - “isDayClosing”: true), воспользуйтесь инструментом снятия блокировки в личном кабинете системы, который описан далее в этом разделе.

Пример структуры ответа следующий:
{
  "response": {
    "status": "finished",
        "gates": [ {
              "gateId": 193,
              "isDayClosing": false,
              "gateCloseDate": "Mon Dec 10 14:44:21 MSK 2018",
              "epntId": 1,
              "saleApprovedCount": "2334",
              "saleAmount": "87328428482.00",
              "reversalApprovedCount": "123",
              "reversalAmount": "12393423.00",
              "code39": "000",
              "RRN": "2034829434"
              }, {
              "gateId": 82,
              "isDayClosing": false,
              "gateCloseDate": "Mon Dec 10 14:44:21 MSK 2018",
              "epntId": 1,
              "saleApprovedCount": "2334",
              "saleAmount": "87328428482.00",
              "reversalApprovedCount": "123",
              "reversalAmount": "12393423.00",
              "code39": "000",
              "RRN": "2034829434"
              }, {
              "gateId": 317,
              "isDayClosing": false,
              "gateCloseDate": "Mon Dec 10 14:44:21 MSK 2018",
              "epntId": 1,
              "saleApprovedCount": "2334",
              "saleAmount": "87328428482.00",
              "reversalApprovedCount": "123",
              "reversalAmount": "12393423.00",
              "code39": "000",
              "RRN": "2034829434"
        }
        ]
      },
      "theRequestSerialNumber": "00000000-0000-0000-0000-00000000002c"
}
Имя свойства Тип Описание
status string Статус операции закрытия дня
gateId long Идентификатор шлюза по которому происходит закрытие дня
isDayClosing boolean Флаг закрытия дня, при значении true - шлюз заблокирован
gateCloseDate string Дата закрытия дня шлюза
epntId long Свойство, присваемое банком терминалу при его настройке в системе банка
saleApprovedCount string Число подтвержденных sale транзакций
saleAmount string Сумма по подтвержденным sale транзакциям
reversalApprovedCount string Число подтвержденных reversal транзакций
reversalAmount string Сумма по подтвержденным reversal транзакциям
code39 string Результат закрытия, ответ банка на вызов процедуры закрытия гейта
RRN string Номер закрытия дня сгруппированный по ID терминала
theRequestSerialNumber string Серийный номер запроса закрытия дня
Если во время выполнения процедуры закрытия дня пользователь посылает повторный запрос на закрытие дня с новым идентификатором запроса - сервер вернет ответ со статусом ‘error’ и с описанием ошибки. Использовать повторно идентификатор этого запроса для дальнейшего инициирования закрытия дня бессмысленно, т.к. статус ошибки - это финальный статус и идентификатор запроса всегда будет ассоциирован с этим запросом.
Пример структуры ответа следующий:
{
      "response": {
        "status": "error",
        "errorCode": "99",
        "errorMessage": "gate is closing already"
      },
      "theRequestSerialNumber": "00000000-0000-0000-0000-000000000020"
}
Имя свойства Тип Описание
status string Статус операции закрытия дня
errorCode string Код ошибки
errorMessage string Описание ошибки
theRequestSerialNumber string Серийный номер запроса закрытия дня
Если пользователь инициирует запрос с новым идентификатором запроса на терминал, по которому уже было закрытие дня, и часть ассоциированных с терминалом гейтов закрылись с ошибкой (и находятся в закрытом состоянии) - сервер пришлет ответ со статусом ‘error’ и соответствующим описанием ошибки.

Warning

Для разрешения этой проблемы проведите операцию закрытия дня вручную в личном кабинете системы.

Инструмент снятия блокировки для шлюза

Если во время проведения удаленного закрытия дня, один или несколько шлюзов остались в заблокированном состоянии (в теле ответа при “status”: “finished” для шлюза - “isDayClosing”: true), Вы можете снять блокировку в личном кабинете системы и, при необходимости, закрыть день вручную.

Для снятия блокировки на шлюзе менеджеру или его сотруднику в личном кабинете системы надо перейти в настройки шлюза, для которого требуется снять блокировку.

pic1 close_day

pic2 close_day

На странице шлюза нажмите кнопку “Locks”, для вызова инструмента снятия блокировки.

pic9 close_day

pic10 close_day

В меню “Current locks” отображена текущая информация о блокировке шлюза:

  • Lock session ID - идентификатор сессии блокировки.
  • Start day closing date - дата начала закрытия дня.
  • Bank terminal lock status - блокировка терминала для проведения траназкций (Blocked/Free).
  • Initial gate job status - статус задачи по инициализации шлюза.
  • Close day job status - статус задачи по закрытию шлюза.
  • Is day closing - шлюз в стадии закрытия, т.е. находится ли в заблокированном состоянии (Y/N). Y - шлюз заблокирован, N - блокировки нет.

Доступны следующие команды снятия блокировки:

  • CLEAR_TRANSACTION_LOCK - сбросить сессию из-за которой произошла блокировка.
  • CLEAR_INIT_ATTEMPT - сбросить статус задачи по инициализации шлюза.
  • CLEAR_CLOSING_DAY_ATTEMPTS - сбросить статус задачи по закрытию шлюза.
  • CLEAR_CLOSING_DAY_FLAG - сбросить задачу по закрытию шлюза, снять блокировку.

Отметьте галочкой нужный пункт меню и нажмите кнопку “Update”.

После выполнения команды сброса, повторно откройте инструмент снятия блокировки и проверьте, что в меню “Current locks” изменился статус сбрасываемого параметра. Например, если шлюз был заблокирован, то после снятия блокировки параметр “Is day closing” = N.

Инструмент отладки для удаленного закрытия дня

Чтобы воспроизвести вызов API, введите все данные из исходного запроса, включая маркеры проверки подлинности. Не забудьте установить nonce и timestamp значения, которые Вы использовали. Запрос, подписанный с помощью OAuth, должен совпадать со значением в инструменте отладки ниже, вне зависимости от используемой библиотеки и языка программирования. Если подписи отличаются, значит в Вашем коде подписи OAuth есть ошибка.
HTTP method
URL
parameters
version
consumer key
consumer secret
timestamp
nonce
signature method

normalized parameters
signature base string
signature
authorization header