Please turn javascript on and reload the page

Invoice Issue by API

It is the reliable method for integration. Parameters are sent by means of server2server requests with authorization. Method allows you to issue an invoice, successful response contains link to redirect client on Payment Form.

Request → PUT

Parameter Description Type Required
billId Unique invoice identifier in merchant’s system String(200) +
amount.currency invoice amount rounded down to two decimals (Alpha-3 ISO 4217 code) +
amount.value Amount of the invoice rounded down to two decimals Number(6.2) +
phone Phone number of the client to which the invoice is issuing (international format) string
email E-mail of the client where the invoice payment link will be sent string
account Client identifier in merchant’s system string
comment Invoice commentary String(255)
customFields[] Additional invoice data String(255)
expirationDateTime invoice due date. Time should be specified with time zone. string +
    • Authorization: Bearer
    • Accept: application/json
Parameter Type Description
billId String Unique invoice identifier in the merchant’s system
siteId String Merchant’s site identifier in QIWI Kassa
amount.value String The invoice amount. The number is rounded down to two decimals
amount.currency String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
status.value String String representation of the status
status.changedDateTime String Status refresh date. Date format:
customer Object Customer data of the invoice subject
customer.phone String The customer’s phone (if specified in the invoice)
customer.email String The customer’s e-mail (if specified in the invoice)
customer.account String The customer’s identifier in the merchant’s system (if specified in the invoice)
customFields Object Additional invoice data provided by the merchant
comment String Comment to the invoice
creationDateTime String System date of the invoice creation. Date format:
payUrl String Pay form link
expirationDateTime String Expiration date of the pay form link (invoice payment’s due date). Date format:

Checking the Invoice Status

Use this method to get current invoice payment status. We recommend using it after receiving the payment notification.

Request → GET

  • billId – unique invoice identifier generated by the merchant.

    • Authorization: Bearer
    • Accept: application/json
Parameter Type Description
billId String Unique invoice identifier in the merchant’s system
siteId String Merchant’s site identifier in QIWI Kassa
amount Object The invoice amount data
amount.value Number The invoice amount. The number is rounded down to two decimals
amount.currency String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
status Object Invoice status data
status.value String Current
status.changedDateTime String Status refresh date
customFields Object Additional invoice data provided by the merchant
customer Object Customer data of the invoice subject
customer.phone String The customer’s phone (if specified in the invoice)
customer.email String The customer’s e-mail (if specified in the invoice)
customer.account String The customer’s identifier in the merchant’s system (if specified in the invoice)
comment String Comment to the invoice
creationDateTime String System date of the invoice creation. Date format:
payUrl String Pay form link
expirationDateTime String Expiration date of the pay form link (invoice payment’s due date). Date format:

Refund

Method allows you to make a refund for the paid invoice.

Request → PUT

    • Parameters:
    • billId – unique invoice identifier generated by the merchant.
    • refundId – unique refund identifier generated by the merchant.
    • amount.value – refund amount.
    • amount.currency – refund currency.
    • Authorization: Bearer
    • Accept: application/json
    • application/json;charset=utf-8
Parameter Type Description
datetime String When response with error: request processing system date
refundId String Unique refund identifier given by the merchant
amount.value Number The invoice amount. The number is rounded down to two decimals
amount.currency String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
status String
datetime String System date of refund processing. Date format:

Invoice opening options

You can add parameters to URL from field in response to the .

Parameter Description Type
paySource Pre-selected payment method for the client on Payment Form. Possible values: – QIWI Wallet – card payment – mobile account payment – Sovest card payment When specified method is inaccessible, the page automatically selects recommended method for the user. String
allowedPaySources Allow only these payment methods for the client on Payment Form. Possible values: – QIWI Wallet – card payment – mobile account payment – Sovest card payment comma separated string
successUrl The URL to which the client will be redirected in case of successful payment from its QIWI Wallet balance. When payment is by any other means, redirection is not performed. URL must belong to the merchant. URL-encoded string
lifetime Expiration date of the pay form link (invoice payment’s due date). If the invoice is not paid after that date, the invoice assigns EXPIRED final status and it becomes void. Important! Invoice will be automatically expired when 45 days is passed after the invoicing date String

Методы

В библиотеке доступны 3 функции: , и .

В случае успешной оплаты Promise resolve-ится с параметрами с которыми был создан счет, иначе reject-ится с причиной из-за которой оплата была прервана.

В случае ошибки при оплате:

В случае закрытия попапа:

Через 2 секунды после совершения оплаты или ошибки форма оплаты закрывается.

QiwiCheckout.createInvoice({
    publicKey: '5nAq6abtyCz4tcDj89e5w7Y5i524LAFmzrsN6bQTQ3c******',
    amount: 1.23,
    phone: '79123456789',
})
    .then(data => {
        //  data === {
        //    publicKey: '5nAq6abtyCz4tcDj89e5w7Y5i524LAFmzrsN6bQTQ3c******',
        //    amount: 1.23,
        //    phone: '79123456789',
        //  }
    })
    .catch(error => {
        //  error === {
        //      reason: "PAYMENT_FAILED"
        //  }
    })

Открытие инвойса

Метод открывает платежную форму. В параметрах нужно указать:

Параметр Описание Тип Обязательное
payUrl URL инвойса String +
params = {
    payUrl: 'https://oplata.qiwi.com/form?invoiceUid=06df838c-0f86-4be3-aced-a950c244b5b1'
}

QiwiCheckout.openInvoice(params)
    .then(data => {
        // ...
    })
    .catch(error => {
        // ...
    })

Создание инвойса

Метод выставляет новый счет и открывает платежную форму с этим счетом. Доступные параметры:

Параметр Описание Тип Обязательное
publicKey Ключ идентификации мерчанта, полученный в QIWI Кассе String +
amount Сумма, на которую выставляется счет, округленная в меньшую сторону до 2 десятичных знаков Number(6.2) +
phone Номер телефона пользователя, на который выставляется счет (в международном формате) String
email E-mail пользователя, куда будет отправлена ссылка для оплаты счета String
account Идентификатор пользователя в системе мерчанта String
comment Комментарий к счету String(255)
customFields Дополнительные данные счета Object
lifetime Дата, до которой счет будет доступен для оплаты. Если счет не будет оплачен до этой даты, ему присваивается финальный статус EXPIRED и последующая оплата станет невозможна. Number (unix timestamp)
params = {
    publicKey: '5nAq6abtyCz4tcDj89e5w7Y5i524LAFmzrsN6bQTQ3c******',
    amount: 1.23,

    phone: '79123456789',
    email: 'test@test.com',
    account: 'acc789',
    comment: 'Оплата',
    customFields: {
        data: 'data'
    },
    lifetime: '2019-04-04T1540'
}

QiwiCheckout.createInvoice(params)
    .then(data => {
        // ...
    })
    .catch(error => {
        // ...
    })

Открытие my.qiwi.com

Метод открывает my.qiwi.com. В параметрах нужно указать:

Параметр Описание Тип Обязательное
widgetAlias Алиас виджета String +

Transfer to bank account

wallet.toBank({ amount: '0.01', account: '5213********0000', account_type: '1', exp_date: 'MMYY' }, recipient, (err, data) => {
  if(err) {
    /* handle err*/
    }
  console.log(data);
})
  • ammount – Ammount of money
  • account – Receiver card/account number
  • account_type – Type of bank identificator.

    • for Alfa-bank (Альфа-Банк) – 1
    • for OTP Bank (АО ОТП БАНК) – 1
    • for Rosselhozbank (АО РОССЕЛЬХОЗБАНК) – 5
    • for Russian Standard (Русский Стандарт) – 1
    • for VTB (ВТБ ПАО) – 5
    • for Promsvyazbank (Промсвязьбанк) – 7
    • for Sberbank (ПАО Сбербанк) – 5
    • for Renessans Credit (Ренессанс Кредит) – 1
    • for Moscow Credit Bank (ПАО Московский кредитный банк) – 5
  • exp_date – Card expiration date (MMYY), as examlpe: 0218 – february 2018. Only for card transfer.
  • recipient –
    • 464 – Alfa-bank (Альфа-Банка)
    • 466 – Tinkoff Bank (Тинькофф Банк)
    • 804 – OTP Bank (АО ОТП БАНК)
    • 810 – Rosselhozbank (АО РОССЕЛЬХОЗБАНК)
    • 815 – Russian Standard (Русский Стандарт)
    • 816 – VTB (ВТБ ПАО)
    • 821 – Promsvyazbank (Промсвязьбанк)
    • 870 – Sberbank (ПАО Сбербанк)
    • 881 – Renessans Credit (Ренессанс Кредит)
    • 1135 – Moscow Credit Bank (ПАО Московский кредитный банк)

Invoicing Operations Flow

Please turn javascript on and reload the page

  • User submits an order on the merchant’s website.

  • Merchant redirects the user to link to issue an invoice for the order and to make the user pay for it. Or and redirects to the Payment Form.

  • The user chooses the most convenient way to pay for the invoice on the Payment Form. By default, the optimal payment method is showed first.

  • The merchant’s service receives once the invoice is successfully paid by the user. You need to configure notifications on your Personal Page. Notifications contain authorization parameters which merchant needs to verify on its server.

  • If needed, via merchant can:
    • of the invoice,
    • (if the user has not initiated payment yet).
  • When the invoice payment is confirmed, merchant delivers ordered services/goods.

Wire transfer

Выполняет перевод на банковские карты/счета российских банков.

Тип запроса – POST.

URL запроса:

Заголовки запроса:

В заголовке указываются .

Параметр URL запроса:

  • – идентификатор банка. Возможные значения:
    • 466 – Тинькофф Банк
    • 464 – Альфа-Банк
    • 821 – Промсвязьбанк
    • 815 – Русский Стандарт

Тело запроса – JSON. Параметры запроса:

Параметр Тип Описание
id String Клиентский ID транзакции (максимум 20 цифр). Должен быть уникальным для каждой транзакции и увеличиваться с каждой последующей транзакцией. Для выполнения этих требований рекомендуется задавать равным 1000*(Standard Unix time в секундах).
sum Object Объект, содержащий данные о сумме платежа:
amount Decimal Сумма
currency String Валюта (только , рубли)
source String Источник фондирования платежа. Допускается только следующее значение: – рублевый счет QIWI Кошелька отправителя
paymentMethod Object Объект, определяющий обработку платежа процессингом. Содержит следующие параметры:
type String Тип платежа, только
accountId String Идентификатор счета, только .
fields Object Объект с параметрами перевода:
account String Номер карты/счета получателя
exp_date String Срок действия карты, в формате ММГГ (например, ). Только для перевода на карту.
account_type String Тип банковского идентификатора. Допустимые значения:для Тинькофф Банк – карта “1”, договор “3”для Альфа-Банка – карта “1”, счет “2”для Промсвязьбанка – карта “7”, счет “9”для банка Русский Стандарт – карта “1”, счет “2”, договор “3”

Успешный ответ содержит данные о принятом платеже:

Параметр Описание
id ID транзакции (максимум 20 цифр)
sum Копия объекта из исходного запроса.
fields Копия объекта из исходного запроса. Номер карты в ответе маскирован.
source Копия параметра из исходного запроса.
transaction Объект с данными о транзакции в процессинге. Параметры:
id ID транзакции в процессинге
state Объект, содержит текущее состояние транзакции в процессинге. Содержит только параметр со значением (платеж принят)

Error Codes

В случае ошибки API возвращается HTTP-код ошибки.

Код API Описание
401 Все Ошибка авторизации. Неверный токен или истек срок действия токена.
404 История платежей Не найдена транзакция или отсутствуют платежи с указанными признаками
404 Балансы, Профиль пользователя Не найден кошелек
423 История платежей Слишком много запросов, сервис временно недоступен

Authorization data

QIWI Wallet API implements OAuth 2.0 open authorization protocol specification. A user registers or authenticates on https://qiwi.com QIWI Wallet site and requests a token with a certain scopes. Token issue is confirmed by SMS code.

  1. Open https://qiwi.com/api page in your browser. You will need to register or authenticate on QIWI Wallet service.
  2. Click on Выпустить новый токен. Select token scopes in the pop-up window:
    • Запрос информации о профиле кошелька – allows
    • Запрос баланса кошелька – allows
    • Просмотр истории платежей – allows
    • Проведение платежей без SMS – allows making payment requests with no SMS confirmation (regardless the settings https://qiwi.com/settings/options/security.action)
  3. Click Продолжить and confirm a token issue by entering SMS code.
  4. Copy token string and save it securely. Use the token in .

Please turn javascript on and reload the page

Token is valid one month from this issuing. You can block the token before its lifetime ends using this link https://qiwi.com/settings/mine.action.

Transfer by requisites

wallet.toCard(requestOptions, (err, data) => {
  if(err) {
    /* handle err*/
    }
  console.log(data);
})

requestOptions includes:

  • amount – Amount of money
  • account – Receiver account number
  • bankName – Receiver bank name
  • bik – Receiver bank bik
  • city – Receiver city
  • organizationName – Receiver organization name
  • inn – Receiver organization inn
  • kpp – Receiver organization kpp
  • nds – ‘НДС не облагается’ or ‘В т.ч. НДС’
  • purpose – Purpose of payment
  • urgent – 0 or 1. Urgent pay need 10 minutes to complete. Available from 9.00 AM to 8.30 PM (09.00 – 20.30) by Moscow time (GMT+3). Service fee – 25 rubles
  • senderName – Sender name
  • senderMiddleName – Sender middle name
  • senderLastName – Sender last name

Invoice Payment Notifications

Notification is a POST-request (callback). The request’s body contains JSON-serialized invoice data encoded by UTF-8..
Notifications handler server URL is specified in kassa.qiwi.com in Protocol settings section.

    • X-Api-Signature-SHA256: ***
    • Accept: application/json
    • Content-type: application/json

Authorization on Merchant’s Server

Upon receiving inbound notification you need to verify it by digital signature from notification HTTP header . Signature is verified with HMAC algorithm integrity check with SHA256-hash function.

Signature verification algorithm is as follows:

  1. Prepare a string of the following notification’s parameters separated by :

    where is the value of the notification parameter. All values should be treated as strings.

  2. Apply HMAC-SHA256 function:

    where:

    • – function key;
    • – string from step 1.
  3. Compare header’s value with the result of step 2.

String and key of the signature are encoded in UTF-8.

Parameters
Invoice parameters are in the POST-request’s body.

Parameter Description Type
bill Invoice data Object
bill.billId Invoice identifier in the merchant’s system String(200)
bill.siteId Merchant’s site identifier in QIWI Kassa String
bill.amount The invoice amount data Object
amount.value The invoice amount. The number is rounded down to two decimals Number(6.2)
amount.currency Currency identifier of the invoice (Alpha-3 ISO 4217 code) String(3)
bill.status Invoice status data Object
status.value Current String
status.changedDateTime Status refresh date. Date format: String
bill.customFields Additional invoice data provided by the merchant Object
bill.customer Customer data of the invoice subject (if specified in the invoice) Object
customer.phone The customer’s phone (if specified in the invoice) String
customer.email The customer’s e-mail (if specified in the invoice) String
customer.account The customer’s identifier in the merchant’s system (if specified in the invoice) String
bill.comment Comment to the invoice String(255)
bill.creationDateTime System date of the invoice creation. Date format: String
bill.payUrl Pay form link String
bill.expirationDateTime Expiration date of the pay form link (invoice payment’s due date). Date format: String
version Notification service version String

Response → POST

After receiving inbound notification request, you should verify its signature and returns the JSON-response. The processing result code should be returned in response.

Refund Status

Method returns current status of the refund .

Request → GET

    • Parameters:
    • billId – unique invoice identifier generated by the merchant.
    • refundId – unique refund identifier generated by the merchant.
    • Authorization: Bearer
    • Accept: application/json
    • application/json;charset=utf-8

Response ←

  • Accept: application/json

Parameter Type Description
datetime String When response with error: request processing system date
refundId String Unique refund identifier given by the merchant
amount.value Number The invoice amount. The number is rounded down to two decimals
amount.currency String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
status String
datetime String System date of refund processing. Date format:

Invoice Payment Statuses

Status Description Final
WAITING Invoice issued awaiting for payment
PAID Invoice paid +
REJECTED Invoice rejected by customer +
EXPIRED Invoice expired. Invoice not paid +

Refund Statuses

Status Description Final
PARTIAL Partial refund of the invoice amount
FULL Full refund of the invoice amount +

Авторизация

const SECRET_KEY = 'eyJ2ZXJzaW9uIjoicmVzdF92MyIsImRhdGEiOnsibWVyY2hhbnRfaWQiOjUyNjgxMiwiYXBpX3VzZXJfaWQiOjcxNjI2MTk3LCJzZWNyZXQiOiJmZjBiZmJiM2UxYzc0MjY3YjIyZDIzOGYzMDBkNDhlYjhiNTnONPININONPN090MTg5Z**********************';

const qiwiApi = new QiwiBillPaymentsAPI(SECRET_KEY);

Смена на новый:

const NEW_SECRET_KEY = 'kokoOKPzaW9uIjoicmVzdF92MyIsImRhdGEiOnsibWVyY2hhbnRfaWQiOjUyNjgxMiwiYXBpX3VzZXJfaWQiOjcxNjI2MTk3LCJzZWNyZXQiOiJmZjBiZmJiM2UxYzc0MjY3YjIyZDIzOGYzMDBkNDhlYjhiNTk5NmIbhchhbbHBHIBDBI**********************';

qiwiApi.key = NEW_SECRET_KEY;

Checkout Popup

Demo popup

Installation:

The library has two methods: create a new invoice and open an existing one.

Create new invoice

Call function

Parameter Description Type Required
publicKey Merchant public key received in QIWI Kassa String +
amount Amount of the invoice rounded down on two decimals Number(6.2) +
phone Phone number of the client to which the invoice is issuing (international format) String
email E-mail of the client where the invoice payment link will be sent String
account Client identifier in merchant’s system String
comment Invoice commentary String(255)
customFields Additional invoice data Object
lifetime Expiration date of the pay form link (invoice payment’s due date). If the invoice is not paid after that date, the invoice assigns final status and it becomes void.Important! Invoice will be automatically expired when 45 days is passed after the invoicing date URL-encoded string

Operation history

wallet.getOperationHistory(wallet, requestOptions, (err, data) => {
  if(err) {
    /*hanle error*/
  }
  console.log(data);
})

wallet – wallet number without plus (+) and with prefix (79991234567)

requestOptions includes:

  • rows – Amount of payments in response. Integer from 1 to 50. Required.
  • operation – Operation type. ALL – all operations, IN – incoming only, OUT – outgoing only, QIWI_CARD – just payments by QIWI cards (QVC, QVP). Default – ALL
  • sources – Payment source. Array of values. Allowable values: QW_RUB – ruble account of wallet, QW_USD – usd account of wallet, QW_EUR – euro account of wallet, CARD – added and not added to wallet cards, MK – account of mobile operator. If not presented, you will receive info from all sources
  • startDate – Start date (YYYY-MM-ddThh:mm:ssZ). By default equals yesterday date. Use only with endDate
  • endDate – End date (YYYY-MM-ddThh:mm:ssZ). By default equals current date. Use only with startDate
  • nextTxnDate – Transaction date (YYYY-MM-ddThh:mm:ssZ), (see nextTxnDate in response). Use only with nextTxnId
  • nextTxnId – Previous transaction number (see nextTxnId in response). Use only with nextTxnDate
    Maximum interval between startDate and endDate – 90 days.

As example – information about 25 outgoing payments can be get by next way:

wallet.getOperationHistory({rows: 25, operation: "OUT"}, (err, operations) => {
  /* some code */
})

Cancelling the Invoice

Use this method to cancel unpaid invoice.

Request → POST

  • billId – unique invoice identifier generated by the merchant.

    • Authorization: Bearer
    • Accept: application/json
Parameter Type Description
billId String Unique invoice identifier in the merchant’s system
siteId String Merchant’s site identifier in QIWI Kassa
amount Object The invoice amount data
amount.value Number The invoice amount. The number is rounded down to two decimals
amount.currency String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
status Object Invoice status data
status.value String Current
status.changedDateTime String Status refresh date
customFields Object Additional invoice data provided by the merchant
customer Object Customer data of the invoice subject
customer.phone String The customer’s phone (if specified in the invoice)
customer.email String The customer’s e-mail (if specified in the invoice)
customer.account String The customer’s identifier in the merchant’s system (if specified in the invoice)
comment String Comment to the invoice
creationDateTime String System date of the invoice creation. Date format:
payUrl String Pay form link
expirationDateTime String Expiration date of the pay form link (invoice payment’s due date). Date format:

Invoice Issue on Payment Form

It is the simplest way of integration. On opening Payment Form, client receives an invoice at the same time. The invoice data sends in URL explicitly. Client gets a Payment Form web page with multiple payment means. When using this method, one cannot be sure that all invoices are issued by the merchant. mitigates this risk.

REDIRECT →

URL https://oplata.qiwi.com/create

Parameter Description Type Required
publicKey Merchant public key received in QIWI Kassa String +
billId Unique invoice identifier given by the merchant URL-encoded, String(200)
amount Amount of the invoice rounded down on two decimals Number(6.2)
phone Phone number of the client to which the invoice is issuing (international format) URL-encoded string
email E-mail of the client where the invoice payment link will be sent URL-encoded string
account Client identifier URL-encoded string
comment Invoice commentary URL-encoded, String(255)
customFields[] Additional invoice data URL-encoded, String(255)
lifetime Expiration date of the pay form link (invoice payment due date). If the invoice is not paid after that date, the invoice assigns final status and it becomes void.Important! Invoice will be automatically expired when 45 days is passed after the invoicing date URL-encoded string
successUrl The URL to which the client will be redirected in case of successful payment from its QIWI Wallet balance. When payment is by any other means, redirection is not performed. URL must belong to the merchant. URL-encoded string

Опубликовано 04.06.2020 Обновлено 13.06.2020 Пользователем admin

Понравилась статья? Поделиться с друзьями:
Добавить комментарий

4 × три =

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!:

Adblock
detector