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

ParameterDescriptionTypeRequired
billIdUnique invoice identifier in merchant’s systemString(200)+
amount.currencyinvoice amount rounded down to two decimals(Alpha-3 ISO 4217 code)+
amount.valueAmount of the invoice rounded down to two decimalsNumber(6.2)+
phonePhone number of the client to which the invoice is issuing (international format)string
emailE-mail of the client where the invoice payment link will be sentstring
accountClient identifier in merchant’s systemstring
commentInvoice commentaryString(255)
customFields[]Additional invoice dataString(255)
expirationDateTimeinvoice due date. Time should be specified with time zone.string+
    • Authorization: Bearer
    • Accept: application/json
ParameterTypeDescription
billIdStringUnique invoice identifier in the merchant’s system
siteIdStringMerchant’s site identifier in QIWI Kassa
amount.valueStringThe invoice amount. The number is rounded down to two decimals
amount.currencyStringCurrency identifier of the invoice (Alpha-3 ISO 4217 code)
status.valueStringString representation of the status
status.changedDateTimeStringStatus refresh date. Date format:
customerObjectCustomer data of the invoice subject
customer.phoneStringThe customer’s phone (if specified in the invoice)
customer.emailStringThe customer’s e-mail (if specified in the invoice)
customer.accountStringThe customer’s identifier in the merchant’s system (if specified in the invoice)
customFieldsObjectAdditional invoice data provided by the merchant
commentStringComment to the invoice
creationDateTimeStringSystem date of the invoice creation. Date format:
payUrlStringPay form link
expirationDateTimeStringExpiration 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
ParameterTypeDescription
billIdStringUnique invoice identifier in the merchant’s system
siteIdStringMerchant’s site identifier in QIWI Kassa
amountObjectThe invoice amount data
amount.valueNumberThe invoice amount. The number is rounded down to two decimals
amount.currencyStringCurrency identifier of the invoice (Alpha-3 ISO 4217 code)
statusObjectInvoice status data
status.valueStringCurrent
status.changedDateTimeStringStatus refresh date
customFieldsObjectAdditional invoice data provided by the merchant
customerObjectCustomer data of the invoice subject
customer.phoneStringThe customer’s phone (if specified in the invoice)
customer.emailStringThe customer’s e-mail (if specified in the invoice)
customer.accountStringThe customer’s identifier in the merchant’s system (if specified in the invoice)
commentStringComment to the invoice
creationDateTimeStringSystem date of the invoice creation. Date format:
payUrlStringPay form link
expirationDateTimeStringExpiration 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
ParameterTypeDescription
datetimeStringWhen response with error: request processing system date
refundIdStringUnique refund identifier given by the merchant
amount.valueNumberThe invoice amount. The number is rounded down to two decimals
amount.currencyStringCurrency identifier of the invoice (Alpha-3 ISO 4217 code)
statusString
datetimeStringSystem date of refund processing. Date format:

Invoice opening options

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

ParameterDescriptionType
paySourcePre-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
allowedPaySourcesAllow only these payment methods for the client on Payment Form. Possible values: — QIWI Wallet — card payment — mobile account payment — Sovest card paymentcomma separated string
successUrlThe 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
lifetimeExpiration 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 dateString

Методы

В библиотеке доступны 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"
        //  }
    })

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

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

ПараметрОписаниеТипОбязательное
payUrlURL инвойса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
emailE-mail пользователя, куда будет отправлена ссылка для оплаты счетаString
accountИдентификатор пользователя в системе мерчантаString
commentКомментарий к счетуString(255)
customFieldsДополнительные данные счетаObject
lifetimeДата, до которой счет будет доступен для оплаты. Если счет не будет оплачен до этой даты, ему присваивается финальный статус EXPIRED и последующая оплата станет невозможна.Number (unix timestamp)
params = {
    publicKey: '5nAq6abtyCz4tcDj89e5w7Y5i524LAFmzrsN6bQTQ3c******',
    amount: 1.23,

    phone: '79123456789',
    email: '[email protected]',
    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. Параметры запроса:

ПараметрТипОписание
idStringКлиентский ID транзакции (максимум 20 цифр). Должен быть уникальным для каждой транзакции и увеличиваться с каждой последующей транзакцией. Для выполнения этих требований рекомендуется задавать равным 1000*(Standard Unix time в секундах).
sumObjectОбъект, содержащий данные о сумме платежа:
amountDecimalСумма
currencyStringВалюта (только , рубли)
sourceStringИсточник фондирования платежа. Допускается только следующее значение: — рублевый счет QIWI Кошелька отправителя
paymentMethodObjectОбъект, определяющий обработку платежа процессингом. Содержит следующие параметры:
typeStringТип платежа, только
accountIdStringИдентификатор счета, только .
fieldsObjectОбъект с параметрами перевода:
accountStringНомер карты/счета получателя
exp_dateStringСрок действия карты, в формате ММГГ (например, ). Только для перевода на карту.
account_typeStringТип банковского идентификатора. Допустимые значения:для Тинькофф Банк — карта «1», договор «3»для Альфа-Банка — карта «1», счет «2»для Промсвязьбанка — карта «7», счет «9»для банка Русский Стандарт — карта «1», счет «2», договор «3»

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

ПараметрОписание
idID транзакции (максимум 20 цифр)
sumКопия объекта из исходного запроса.
fieldsКопия объекта из исходного запроса. Номер карты в ответе маскирован.
sourceКопия параметра из исходного запроса.
transactionОбъект с данными о транзакции в процессинге. Параметры:
idID транзакции в процессинге
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.

ParameterDescriptionType
billInvoice dataObject
bill.billIdInvoice identifier in the merchant’s systemString(200)
bill.siteIdMerchant’s site identifier in QIWI KassaString
bill.amountThe invoice amount dataObject
amount.valueThe invoice amount. The number is rounded down to two decimalsNumber(6.2)
amount.currencyCurrency identifier of the invoice (Alpha-3 ISO 4217 code)String(3)
bill.statusInvoice status dataObject
status.valueCurrentString
status.changedDateTimeStatus refresh date. Date format:String
bill.customFieldsAdditional invoice data provided by the merchantObject
bill.customerCustomer data of the invoice subject (if specified in the invoice)Object
customer.phoneThe customer’s phone (if specified in the invoice)String
customer.emailThe customer’s e-mail (if specified in the invoice)String
customer.accountThe customer’s identifier in the merchant’s system (if specified in the invoice)String
bill.commentComment to the invoiceString(255)
bill.creationDateTimeSystem date of the invoice creation. Date format:String
bill.payUrlPay form linkString
bill.expirationDateTimeExpiration date of the pay form link (invoice payment’s due date). Date format:String
versionNotification service versionString

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

ParameterTypeDescription
datetimeStringWhen response with error: request processing system date
refundIdStringUnique refund identifier given by the merchant
amount.valueNumberThe invoice amount. The number is rounded down to two decimals
amount.currencyStringCurrency identifier of the invoice (Alpha-3 ISO 4217 code)
statusString
datetimeStringSystem date of refund processing. Date format:

Invoice Payment Statuses

StatusDescriptionFinal
WAITINGInvoice issued awaiting for payment
PAIDInvoice paid+
REJECTEDInvoice rejected by customer+
EXPIREDInvoice expired. Invoice not paid+

Refund Statuses

StatusDescriptionFinal
PARTIALPartial refund of the invoice amount
FULLFull 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

ParameterDescriptionTypeRequired
publicKeyMerchant public key received in QIWI KassaString+
amountAmount of the invoice rounded down on two decimalsNumber(6.2)+
phonePhone number of the client to which the invoice is issuing (international format)String
emailE-mail of the client where the invoice payment link will be sentString
accountClient identifier in merchant’s systemString
commentInvoice commentaryString(255)
customFieldsAdditional invoice dataObject
lifetimeExpiration 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 dateURL-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
ParameterTypeDescription
billIdStringUnique invoice identifier in the merchant’s system
siteIdStringMerchant’s site identifier in QIWI Kassa
amountObjectThe invoice amount data
amount.valueNumberThe invoice amount. The number is rounded down to two decimals
amount.currencyStringCurrency identifier of the invoice (Alpha-3 ISO 4217 code)
statusObjectInvoice status data
status.valueStringCurrent
status.changedDateTimeStringStatus refresh date
customFieldsObjectAdditional invoice data provided by the merchant
customerObjectCustomer data of the invoice subject
customer.phoneStringThe customer’s phone (if specified in the invoice)
customer.emailStringThe customer’s e-mail (if specified in the invoice)
customer.accountStringThe customer’s identifier in the merchant’s system (if specified in the invoice)
commentStringComment to the invoice
creationDateTimeStringSystem date of the invoice creation. Date format:
payUrlStringPay form link
expirationDateTimeStringExpiration 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

ParameterDescriptionTypeRequired
publicKeyMerchant public key received in QIWI KassaString+
billIdUnique invoice identifier given by the merchantURL-encoded, String(200)
amountAmount of the invoice rounded down on two decimalsNumber(6.2)
phonePhone number of the client to which the invoice is issuing (international format)URL-encoded string
emailE-mail of the client where the invoice payment link will be sentURL-encoded string
accountClient identifierURL-encoded string
commentInvoice commentaryURL-encoded, String(255)
customFields[]Additional invoice dataURL-encoded, String(255)
lifetimeExpiration 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 dateURL-encoded string
successUrlThe 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
Понравилась статья? Поделиться с друзьями:
Добавить комментарий

два × 1 =

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

Adblock
detector