Ошибка 401 киви кошелек


15

ответов

Апи ключ неправильно передаешь

офигеть у них ошибки.
для р2р нужен public key с p2p.qiwi.com ? Скопировал только что его оттуда..

screenshot

этот же нужен?

насколько знаю, апи ключи подлиннее будут)

там кнопка скопировать.

tgbot — название

tgbot — название. ключ большой

Потому что это ПУБЛИЧНЫЙ ключ. А нужен апи ключ) который секретный наверно

screenshot

Я метод не тот использовал. Сейчас переписал все по примеру и он дает ссылку, но на страничке оплаты говорит, что данных мало передал для выставления счета

Похожие вопросы

Ошибка при оплате

у меня ошибку выдает при оплате Ошибка обращения к QIWI Kassa
HTTP/1.1 401 Unauthorized Что за хрень и как решать? Купил у вас плагин

Добрый день!

На каком этапе, где возникает ошибка? Пришлите пожалуйста скриншот ошибки?

Когда выбрал оплату КИВИ и нажимаешь оформить заказ он выдает ошибку https://ibb.co/4TJz7c4

Возможно ещё увидеть скрин настроек плагина?

Попробуйте выполнить следующие рекомендации:

  1. Деактивируйте прочие плагины оплаты Qiwi
  2. Выпустите новые ключи в кабинете Qiwi (для справки можно взять статью https://coderun.ru/blog/kak-prinimat-platezhi-na-qiwi-kosheljok-iz-magazina-woocommerce/)

Данная ошибка возникает из за того что не верно заполнено поле «Секретный ключ API» (Не тот ключ, пробелы, переносы строки)

Для выпуска нового ключа вам необходимо перейти в Qiwi кабинет https://qiwi.com/p2p-admin/transfers/api и нажать кнопку «Создание пары ключей авторизации»

Обязательно установите галочку «Использовать эту пару ключей для серверных оповещений» и укажите «адрес уведомлений от банка»

После этого вам будет доступно два ключа, для плагина необходимо использовать «Секретный ключ», —  «Публичный ключ» в этом случае не подоходит для настройки плагина!

Секретный ключ можно получить только при создании новых значений авторизации, дальше будет доступен только публичный в интерфейсе Qiwi

Благодарствую. Оказывается надо было выделять ключ не двойным кликом, а через «Скопировать в буфер», не знал что будет такой глупый нюанс, ведь пробелов и в том и в другом случае небыло.

Если появяться вопросы, обращайтесь!

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

P.s картинка не вкладывается в сообщение

Цитата: 1 от 11.08.2022, 20:10

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

P.s картинка не вкладывается в сообщение

К сожалению такое возможно, транзакции как правило блокируются отправляющей стороной.

Здравствуйте, последний месяц при оплате с карты сбербанк сначала выдает ошибку, при повторной оплате блокирует карту у клиента!

Добрый день!

Это может быть связанно с тем что банк борется с подозрительными транзакциями, лучше это выяснить у банка держателя карты.

$QIWI_SECRET_KEY = env('QIWI_SECRET_KEY') ;
            $billPayments = new BillPayments($QIWI_SECRET_KEY);
            $billPayments->key = $QIWI_SECRET_KEY;
            $billId = $billPayments->generateId();

            $fields = [
                'amount' => round($price + $delivery_price,2),
                'currency' => 'RUB',
                'phone' => $form['phone'],
                'comment' => 'Заказ №"' . $order->id . '"',
                'expirationDateTime' => (new \DateTime(date("Y-m-d H:i:s")))->modify('+7 day')->format('c'),
            ];

            /** @var \Qiwi\Api\BillPayments $billPayments */
            $response = $billPayments->createBill($billId, $fields);

Пытаюсь создать счет на оплату таким образом, абсолютно этот же код работает в простом php файле. Сейчас делаю это в Laravel. Секретный ключ точно есть и передается.

Выдает ошибку «HTTP/1.1 401 Unauthorized» в /vendor/qiwi/bill-payments-php-sdk/src/BillPayments.php:592

Trace ведет на строку 463.

Может ли это быть связано с тем что я сейчас тестирую на другом домене(на том же сервере)?

Pull Payments

Edit on GitHub

QIWI Pull Payments API opens a way to operations with QIWI Wallet invoices from your service. The following operations are supported:

  • creating invoice
  • cancelling unpaid invoice
  • making refund for paid invoice (a user rejects merchant’s good or service)
  • checking operation’s status
  • starting payment on QIWI Checkout

Payment methods

  • Customers may pay for QIWI Wallet invoices
    • on QIWI checkout (oplata.qiwi.com)
    • on qiwi.com web-site
      • from their QIWI Wallet,
      • from mobile phone account or any Visa/MasterCard
    • in QIWI mobile applications (Android/iOS/Windows Phone)
      • from their QIWI Wallet,
      • from mobile phone account or any Visa/MasterCard
    • by cash in QIWI Self-service kiosks.

To use API, complete registration and approvement of the agreement.

Integration methods

You can use the following integration methods with QIWI Wallet Pull Payments API:

  • Online Invoicing Form — Quick and easy solution for invoicing (does not require user redirect to QIWI Checkout). Has limited functions — only invoice issue. You can call the web form in two ways:
    • authorized by API ID and digital signature of the request
    • without authorization (not recommended)
  • Pull REST API — Fully functional RESTful API for all operations with invoices.
Edit on GitHub

Invoicing Operation Flow

Pull API Invoicing

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

  • Merchant service issues invoice.

  • To increase successful payments conversion, merchant is recommended to redirect the user to QIWI Checkout page on QIWI Wallet site, to pay for the invoice. Otherwise, invoice can be paid in any QIWI Wallet interfaces, such as web (qiwi.com), mobile applications and self-service terminals.

  • If the merchant enables notifications, then its service receives a notification from QIWI Wallet system once invoice is paid or cancelled by the user. Authorization on the merchant’s side is required for notifications.

  • In any case, merchant can request current status of the invoice, or cancel invoice (provided that the user has not initiated payment yet).

  • When the invoice payment is confirmed, merchant delivers ordered services/goods.

Developer Tools

  • NODE JS SDK — Node JS package of ready-to-use solutions for server2server integration development to begin accepting payments on your site.

Authorization

Pull REST API requests are authorized through HTTP Basic-authorization with API ID and API password. Header is Authorization string and its value is Basic Base64(API_ID:API_PASSWORD).

user@server:~$ curl "server_URL"
  --header "Authorization: Basic MjMyNDQxMjM6NDUzRmRnZDQ0Mw=="
  • Authorization and form data

    Data can be obtained on kassa.qiwi.com

Parameter Description Type Required
API_ID Provider API identifier for authorization Integer +
API_PASSWORD API password for authorization String +
Shop ID Numeric identifier of the provider’s service Integer +

Issuing Invoice

Creates new invoice to the specified phone number (wallet ID in QIWI Wallet).

Request → PUT

<?php
//Example
//Shop identifier from Merchant details page
$SHOP_ID = "21379721";
//API ID from Merchant details page
$REST_ID = "62573819";
//API password from Merchant details page
$PWD = "**********";
//Invoice ID
$BILL_ID = "99111-ABCD-1-2-1";
$PHONE = "79191234567";

$data = array(
    "user" => "tel:+" . $PHONE,
    "amount" => "1000.00",
    "ccy" => "RUB",
    "comment" => "Good purchase",
    "lifetime" => "2015-01-30T15:35:00",
    "pay_source" => "qw",
    "prv_name" => "Special packages"
);

$ch = curl_init('https://api.qiwi.com/api/v2/prv/'.$SHOP_ID.'/bills/'.$BILL_ID);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $REST_ID.":".$PWD);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
    "Accept: application/json"
));
$results = curl_exec ($ch) or die(curl_error($ch));
echo $results;
echo curl_error($ch);
curl_close ($ch);
//Optional user redirect
$url = 'https://oplata.qiwi.com/order/external/main.action?shop='.$SHOP_ID.'&
transaction='.$BILL_ID.'&successUrl=http%3A%2F%2Fexample.com%2Findex.php%3Froute%3D
payment%2Fqiwi%2Fsuccess&failUrl=http%3A%2F%2Fexample.com%2Findex.php%3Froute%3D
payment%2Fqiwi%2Ffail&pay_source=card';
echo '<br><br><b><a href="'.$url.'">Redirect link to pay for invoice</a></b>';
?>
user@server:~$ curl "https://api.qiwi.com/api/v2/prv/373712/bills/BILL-1"
  -X PUT  --header "Accept: text/json" --header "Authorization: Basic ***"
  -d "user=tel%3A%2B79161234567&amount=10.00&ccy=RUB&comment=test&lifetime=2016-09-25T15:00:00"
  • URL https://api.qiwi.com/api/v2/prv/prv_id/bills/bill_id

      Parameters are in the PUT-request URL pathname:

    • prv_id — merchant’s Shop ID (numeric value, as displayed in «Shop ID» parameter of «Protocols Settings» section of kassa.qiwi.com web site)
    • bill_id — unique invoice identifier generated by the merchant (any non-empty string of up to 200 characters). Uniqueness means that the identifier must not coincide with any of previously issued invoices of the merchant.
  • Parameters

    Parameters are sent in the request body as formdata.

Parameter Description Type Required
user The QIWI Wallet user’s ID, to whom the invoice is issued. It is the user’s phone number with tel: prefix String(20) Y
amount The invoice amount. The number is rounded down with two decimal places Number(6.2) Y
ccy Invoice currency identifier (Alpha-3 ISO 4217 code). Depends on currencies allowed for the merchant. The following values are supported: RUB, EUR, USD, KZT String(3) Y
comment Comment to the invoice String(255) Y
lifetime Date and time up to which the invoice is available for payment, URL-encoded ISO 8601 (YYYY-MM-DDThh:mm:ss), Moscow timezone. If the invoice is not paid by this date it will become void and will be assigned a final status.
Important! Invoice will be automatically expired when 45 days is passed after the invoicing date
dateTime Y
pay_source If the value is mobile the user’s MNO balance will be used as a funding source. If the value is qw, any other funding source is used available in QIWI Wallet system for the user. If parameter isn’t present, value qw is assumed String N
prv_name Merchant’s name String(100) N

The given PHP example implements creation of the invoice and redirection to the QIWI Checkout web page for payment. This example demonstrates using merchant’s authorization parameters, i.e. shop ID, API ID and password for the API ID. Open the PHP tab on the right.

Response ←


HTTP/1.1 200 OK
Content-Type: text/json
{
  "response": {
     "result_code": 0,
     "bill": {
        "bill_id": "BILL-1",
        "amount": "10.00",
        "ccy": "RUB",
        "status": "waiting",
        "error": 0,
        "user": "tel:+79031234567",
        "comment": "My comment"
     }
  }
}
HTTP/1.1 401 Unauthorized
Content-Type: text/json
{
 "response": {
  "result_code": 150,
  "description": "Authorization failed"
  }
}

HTTP/1.1 200 OK
Content-Type: text/xml
<response>
   <result_code>0</result_code>
   <bill>
    <bill_id>BILL-1</bill_id>
    <amount>10.00</amount>
    <originAmount>10.00</originAmount>
    <ccy>RUB</ccy>
    <originCcy>RUB</originCcy>
    <status>rejected<status>
    <error>0</error>
    <user>tel:+79161234567</user>
    <comment>test</comment>
   </bill>
</response>
HTTP/1.1 401 Unauthorized
Content-Type: text/xml
<response>
   <result_code>341</result_code>
   <description>Authorization is failed</description>
</response>

Response format depends on Accept header in the request:

  • Parameters

Parameter Type Description
result_code Integer Error code
description String Error description. Returned when result_code is non-zero.
bill Object Bill data. Returned when result_code is zero (successful operation). Parameters:
bill.bill_id String Unique invoice identifier generated by the merchant
bill.amount String The invoice amount. The number is rounded down with two decimal places.
bill.ccy String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
bill.status String Current invoice status
bill.error Integer Always 0, means successful operation
bill.user String The QIWI Wallet user’s ID, to whom the invoice is issued. It is the user’s phone number with tel: prefix.
bill.comment String Comment to the invoice

Checking Invoice Status

Gets payment status of the invoice.

user@server:~$ curl "https://api.qiwi.com/api/v2/prv/373712/bills/sdf23452435"
  --header "Authorization: Basic ***" --header "Accept: text/json"

Request → GET

  • URL https://api.qiwi.com/api/v2/prv/prv_id/bills/bill_id

      Parameters are in the GET-request URL pathname:

    • prv_id — merchant’s Shop ID (numeric value, as displayed in «Shop ID» parameter of «Protocols Settings» section of kassa.qiwi.com web site)
    • bill_id — invoice identifier

Response ←


HTTP/1.1 200 OK
Content-Type: text/json
{
  "response": {
     "result_code": 0,
     "bill": {
        "bill_id": "BILL-1",
        "amount": "10.00",
        "originAmount": "10.00",
        "ccy": "RUB",
        "originCcy": "RUB",
        "status": "waiting",
        "error": 0,
        "user": "tel:+79031234567",
        "comment": "My comment"
     }
  }
}
HTTP/1.1 401 Unauthorized
Content-Type: text/json
{
 "response": {
  "result_code": 150,
  "description": "Authorization failed"
  }
}

HTTP/1.1 200 OK
Content-Type: text/xml
<response>
   <result_code>0</result_code>
   <bill>
    <bill_id>BILL-1</bill_id>
    <amount>10.00</amount>
    <originAmount>10.00</originAmount>
    <ccy>RUB</ccy>
    <originCcy>RUB</originCcy>
    <status>rejected<status>
    <error>0</error>
    <user>tel:+79161234567</user>
    <comment>test</comment>
   </bill>
</response>
HTTP/1.1 401 Unauthorized
Content-Type: text/xml
<response>
   <result_code>341</result_code>
   <description>Authorization is failed</description>
</response>

Response format depends on Accept header in the request:

  • Parameters

Parameter Type Description
result_code Integer Error code
description String Error description. Returned when result_code is non-zero.
bill Object Bill data. Returned when result_code is zero (successful operation). Parameters:
bill.bill_id String Unique invoice identifier generated by the merchant
bill.amount String The invoice amount. The number is rounded down with two decimal places.
bill.originAmount String The amount taken from the balance when the invoice get paid (see originCcy parameter). The number is rounded down with two decimal places. Returns for invoices when the user initiates payment.
bill.ccy String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
bill.originCcy String Currency identifier of the balance from which the invoice is paid (Alpha-3 ISO 4217 code). Returns for invoices when the user initiates payment.
bill.status String Current invoice status
bill.error Integer Always 0, means successful operation
bill.user String The QIWI Wallet user’s ID, to whom the invoice is issued. It is the user’s phone number with tel: prefix.
bill.comment String Comment to the invoice

Cancelling Unpaid Invoice

Cancels unpaid invoice provided that its lifetime has not expired yet.

user@server:~$ curl -X PATCH
  --header "Authorization: Basic ***"  --header "Accept: text/json"
  "https://api.qiwi.com/api/v2/prv/373712/bills/BILL-1"
  -d "status=rejected"

Request → PATCH

  • URL https://api.qiwi.com/api/v2/prv/prv_id/bills/bill_id

      Parameters are in the PATCH-request URL pathname:

    • prv_id — merchant’s Shop ID (numeric value, as displayed in «Shop ID» parameter of «Protocols Settings» section of kassa.qiwi.com web site)
    • bill_id — invoice identifier
      Parameter is in the request body.

    • statusrejected (cancelling status).

Response ←


HTTP/1.1 200 OK
Content-Type: text/json
{
  "response": {
     "result_code": 0,
     "bill": {
        "bill_id": "BILL-1",
        "amount": "10.00",
        "ccy": "RUB",
        "status": "rejected",
        "error": 0,
        "user": "tel:+79031234567",
        "comment": "My comment"
     }
  }
}
HTTP/1.1 401 Unauthorized
Content-Type: text/json
{
 "response": {
  "result_code": 150,
  "description": "Authorization failed"
  }
}

HTTP/1.1 200 OK
Content-Type: text/xml
<response>
   <result_code>0</result_code>
   <bill>
    <bill_id>BILL-1</bill_id>
    <amount>10.00</amount>
    <ccy>RUB</ccy>
    <status>rejected<status>
    <error>0</error>
    <user>tel:+79161234567</user>
    <comment>test</comment>
   </bill>
</response>
HTTP/1.1 401 Unauthorized
Content-Type: text/xml
<response>
   <result_code>341</result_code>
   <description>Authorization is failed</description>
</response>

Response format depends on Accept header in the request:

  • Parameters

Parameter Type Description
result_code Integer Error code
description String Error description. Returned when result_code is non-zero.
bill Object Bill data. Returned when result_code is zero (successful operation). Parameters:
bill.bill_id String Unique invoice identifier generated by the merchant
bill.amount String The invoice amount. The number is rounded down with two decimal places.
bill.ccy String Currency identifier of the invoice (Alpha-3 ISO 4217 code)
bill.status String Rejected invoice status
bill.error Integer Always 0, means successful operation
bill.user String The QIWI Wallet user’s ID, to whom the invoice is issued. It is the user’s phone number with tel: prefix.
bill.comment String Comment to the invoice

Refunds

Method processes a full or partial refund to user’s QIWI Wallet account, so a reversed transaction with the same currency is created for the initial one.

Merchant can create several refund operations for the same initial invoice provided that:

  • Amount of all refund operations does not exceed initial invoice amount.
  • Different refund IDs used for different refund operations of the same invoice (see below).

Refund Operation Flow

Refund Invoice REST API

  • Merchant sends a request for refund to QIWI Wallet server.
  • To make sure that the payment refund has been successfully processed, merchant can periodically request the invoice refund status until the final status is received.
  • This scenario can be repeated multiple times until the invoice is completely refunded (whole invoice amount has been returned to the user).

Request → PUT

user@server:~$ curl "https://api.qiwi.com/api/v2/prv/373712/bills/BILL-1/refund/REF1"
  -v -w "%{http_code}"
  -X PUT  --header "Accept: text/json"
  --header "Authorization: Basic ***"
  --header "Content-type: application/x-www-form-urlencoded; charset=utf-8"
  -d "amount=5.0"
  • URL https://api.qiwi.com/api/v2/prv/prv_id/bills/bill_id/refund/refund_id

      Parameters are in the URL pathname:

    • prv_id — merchant’s Shop ID (numeric value, as displayed in «Shop ID» parameter of «Protocols Settings» section of kassa.qiwi.com web site)
    • bill_id — identifier of the invoice to be refunded
    • refund_id — the refund identifier, a number specific to a series of refunds for the invoice {bill_id} (string of 1 to 9 symbols – any 0-9 digits and upper/lower Latin letters)
      Parameter is in the request body:

    • amount — the refund amount. It should be less or equal to the amount of the original invoice specified in bill_id. The positive number that is rounded down with two decimal places.

Response ←


HTTP/1.1 200 OK
Content-Type: text/json
{
   "response": {
      "result_code": 0,
      "refund": {
         "refund_id": "REF1",
         "amount": "5.00",
         "status": "success",
         "error": 0
      }
   }
}
HTTP/1.1 401 Unauthorized
Content-Type: text/json
{
 "response": {
  "result_code": 150,
  "description": "Authorization failed"
  }
}

HTTP/1.1 200 OK
Content-Type: text/xml
<response>
  <result_code>0</result_code>
  <refund>
   <refund_id>REF1</refund_id>
   <amount>5.0</amount>
   <status>success<status>
   <error>0</error>
  </refund>
</response>
HTTP/1.1 401 Unauthorized
Content-Type: text/xml
<response>
   <result_code>341</result_code>
   <description>Authorization is failed</description>
</response>
  • Parameters

Parameter Type Description
result_code Integer Error code
description String Error description. Returned when result_code is non-zero.
refund Object Refund data. Returned when result_code is zero (successful operation). Parameters:
refund.refund_id String The refund identifier, unique number in a series of refunds processed for a particular invoice
refund.amount String The actual amount of the refund. The positive number that is rounded down with two decimal places.
refund.status String Current refund status
refund.error Integer Error code.
Important! When the amount of refund exceeds the initial invoice amount or the amount left after the previous refunds, error code 242 is returned.

Check Refund Status

Method returns current status of the refund.

Request → GET

user@server:~$ curl "https://api.qiwi.com/api/v2/prv/373712/bills/BILL-1/refund/REF1"
  -v -w "%{http_code}"
  --header "Accept: text/json" --header "Authorization: Basic ***"
  • URL https://api.qiwi.com/api/v2/prv/prv_id/bills/bill_id/refund/refund_id

      Parameters are in the URL pathname:

    • prv_id — merchant’s Shop ID (numeric value, as displayed in Shop ID parameter of Protocols details section of kassa.qiwi.com web site)
    • bill_id — invoice identifier
    • refund_id — refund identifier, a number specific to a series of refunds for the invoice {bill_id} (string of 1 to 9 symbols – any 0-9 digits and upper/lower Latin letters)

Response ←


HTTP/1.1 200 OK
Content-Type: text/json
{
   "response": {
      "result_code": 0,
      "refund": {
         "refund_id": "REF1",
         "amount": "5.00",
         "status": "success",
         "error": 0
      }
   }
}
HTTP/1.1 401 Unauthorized
Content-Type: text/json
{
 "response": {
  "result_code": 150,
  "description": "Authorization failed"
  }
}

HTTP/1.1 200 OK
Content-Type: text/xml
<response>
  <result_code>0</result_code>
  <refund>
   <refund_id>REF1</refund_id>
   <amount>5.0</amount>
   <status>success<status>
   <error>0</error>
  </refund>
</response>

HTTP/1.1 401 Unauthorized
Content-Type: text/xml
<response>
   <result_code>341</result_code>
   <description>Authorization is failed</description>
</response>
  • Parameters

Parameter Type Description
result_code Integer Error code
description String Error description. Returned when result_code is non-zero.
refund Object Refund data. Returned when result_code is zero (successful operation). Parameters:
refund.refund_id String The refund identifier, unique number in a series of refunds processed for a particular invoice
refund.amount String The actual amount of the refund. The positive number that is rounded down with two decimal places.
refund.status String Current refund status
refund.error Integer Error code. Important! When the amount of refund exceeds the initial invoice amount or the amount left after the previous refunds, error code 242 is returned.

Operation Statuses

Invoice Status

Status Description Final
waiting Invoice issued, pending payment N
paid Invoice has been paid Y
rejected Invoice has been rejected Y
unpaid Payment processing error. Invoice has not been paid Y
expired Invoice expired. Invoice has not been paid Y

Refund Status

Status Description Final
processing Payment refund is pending N
success Payment refund is successful Y
fail Payment refund is unsuccessful Y

Error Codes

Code Description Fatal
0 Success Unrelated
5 Incorrect data in the request parameters Y
13 Server is busy, try again later N
78 Operation is forbidden Y
150 Authorization error (e.g. invalid login/password) Y
152 Protocol is not enabled or protocol is disabled N
155 This merchant’s identifier (API ID) is blocked Y
210 Invoice not found Y
215 Invoice with this bill_id already exists Y
241 Invoice amount is less than allowed Y
242 Invoice amount is greater than allowed. Also returns to refund request when the amount of refund exceeds the initial invoice amount or the amount left after the previous refunds Y
298 User not registered Y
300 Technical error N
303 Wrong phone number Y
316 Authorization from the blocked merchant N
319 No rights for the operation N
339 IP-addresses blocked Y
341 Required parameter is incorrectly specified or absent in the request Y
700 Monthly limit on operations is exceeded Y
774 QIWI Wallet user account temporarily blocked Y
934 Region is not supported  
1001 Currency is not allowed for the merchant Y
1003 No convert rate for these currencies N
1018 Country is not supported  
1019 Unable to determine wireless operator for MNO balance payment Y
1419 Bill was already payed Y

Online Invoicing Web Form

Edit on GitHub

Client receives a web form with selection of appropriate payment methods for the invoice.

Web form calling is performed without merchant’s authorization. Client can input a phone number and an amount for invoicing on the web form directly.

Operations flow

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

  • Merchant calls invoicing web form. When calling is without a phone number, a user enters the number on the web form directly.

  • When invoicing was successful, the user is immediately redirected to QIWI Checkout page.

  • If merchant enables notifications, then QIWI Wallet sends to the merchant’s server a notification on the invoice status once invoice is paid or cancelled by the user. Authorization on the merchant’s side is required for notifications.

  • Merchant delivers ordered services/goods when the invoice payment is confirmed.

Request → REDIRECT

  • URL https://bill.qiwi.com/order/external/create.action

GET /order/external/create.action?txn_id=10000&from=11223&summ=1.11&currency=643 HTTP/1.1
Host: bill.qiwi.com
  • Parameters

    Invoice parameters are specified in the web form URL.

Parameter Description Type Required
from Merchant identifier (Shop ID). Identifier is specified in «HTTP-protocol» part of «Settings» section of merchant’s account on kassa.qiwi.com. Integer +
currency Invoice currency identifier (in Alpha-3 ISO 4217 code). Any currency may be used if specified in agreement with QIWI Wallet. String(3) +
to QIWI Wallet client phone number to make the invoice. If not specified, client should enter the phone on the web invoice form. String(20)
summ Amount of the invoice. Positive number rounded to two fractional digits. Point as a separator. If not specified, client should enter the amount on the web invoice form. Number(6.2)
txn_id Unique invoice number in online merchant store. It is used to identify specific invoice of the merchant. String(30), Latin letters and digits (without space)
comm Merchant commentary to the invoice. If not specified and to parameter is absent, client may enter the comment with phone number at once on the web form. String(255)
lifetime Invoice expiry date (YYYY-MM-DDTHHMM format). When time is expired, invoice cannot be paid and it would be cancelled. Important! Invoice will be automatically expired when 28 days is passed after the invoicing date.  
successUrl The URL to which the user will be redirected in case of successful creation of QIWI Wallet transaction. May be parameter or anchor. URL must be within merchant’s site. Redirection is performed when user pays by QIWI Wallet account’s balance only. URL-encoded string
failUrl The user is redirected to the specified URL when QIWI Wallet transaction creation is unsuccessful. May be parameter or anchor. URL must be within merchant’s site. Redirection is performed when user pays by QIWI Wallet account’s balance only. URL-encoded string
pay_source Default payment method to show first for the client on QIWI Checkout. Possible values:
qw – QIWI Wallet account;
mobile – client’s cell phone account;
card – a credit/debit card;
wm – WebMoney wallet if linked to QIWI Wallet account;
ssk – payment by cash in a QIWI Terminal.
When specified method is inaccessible, the page contains notice about it and the client can choose another method.
String (predefined)

Checkout

Edit on GitHub

Merchant may offer the user to pay the invoice immediately by redirecting to the QIWI Wallet Checkout page via the HTTP GET-request.

GET /form?shop=2042&transaction=1234567&successUrl=http%3A%2F%example.com%2Fsuccess%3Fa%3D1%26b%3D2&failUrl=http%3A%2F%example.com%2Ffail%3Fa%3D1%26b%3D2&pay_source=qw HTTP/1.1
Host: oplata.qiwi.com

Request → REDIRECT

  • URL https://oplata.qiwi.com/form

  • Parameters

Parameter Type Description Required
shop string Merchant’s ID in QIWI Wallet system, corresponds to prv_id parameter used to create the bill. Y
transaction string Invoice ID generated by the merchant, corresponds to bill_id parameter used to create the bill. Y
embedded boolean The checkout page appears more compact and can be embedded conveniently within the merchant’s site. Default value is false N
successUrl URL-encoded string The URL to which the payer will be redirected in case of successful creation of QIWI Wallet transaction. URL must be within merchant’s site. Redirection is performed when user pays by QIWI Wallet account’s balance only N
failUrl URL-encoded string The URL to which the payer will be redirected when creation of QIWI Wallet transaction is unsuccessful. URL must be within merchant’s site. Redirection is performed when user pays by QIWI Wallet account’s balance only N
pay_source string Default payment method to show first on the page for the user. Allowed values:
qw – QIWI Wallet account;
mobile – client’s cell phone account;
card – a credit/debit card;
wm – linked WebMoney wallet;
ssk – payment by cash in a QIWI Terminal.
When specified method is inaccessible for the user, the page shows a notice about it and the client can choose another method.
N

Redirection to Merchant Site

Redirect when transaction is successfully created

GET /success?a=1&b=2&order=1234567 HTTP/1.1
Host: example.com

Redirect when creation of transaction is unsuccessful

GET /fail?a=1&b=2&order=1234567 HTTP/1.1
Host: example.com

The URL for redirection supplements order parameter with its value as the original merchant’s invoice ID. Using this parameter, the merchant can render the final page depending on the order details.

Notifications

Edit on GitHub

Notification is a POST-request (callback). The request’s body contains all relevant data of the invoice serialized as HTTP-request parameters and encoded by UTF-8 plus parameter command=bill.

Request → POST

Example of notification request

user@server:~$ curl "https://example.com/qiwi-notify.php"
  -v -w "%{http_code}"
  -X POST --header "Accept: text/xml"
  --header "Content-Type: application/x-www-form-urlencoded; charset=utf-8"
  --Authorization: "Basic MjA0Mjp0ZXN0Cg=="
  -d "bill_id=BILL-1%26status=paid%26amount=1.00%26user=tel%3A%2B79031811737%26prv_name=TEST%26ccy=RUB%26comment=test%26command=bill"
  • URL

  • Parameters

    Invoice parameters are in the request’s body.

Parameter Description Type Required
bill_id Merchant invoice number String Y
status Current invoice status String Y
amount The invoice amount. The number is rounded down with two decimal places Number(6.2) Y
user The QIWI Wallet user’s ID, to whom the invoice is issued. It is the user’s phone number with tel: prefix String Y
prv_name Merchant’s site name specified on kassa.qiwi.com in «Settings» section String Y
ccy Invoice currency identifier (Alpha-3 ISO 4217 code) String(3) Y
comment Comment to the invoice String(255) Y
command Always bill by default String Y

Response ←

Example of XML response to notification

HTTP/1.1 200 OK
Content-Type: text/xml

<?xml version="1.0"?>
<result>
<result_code>0</result_code>
</result>

Response must be in XML format.

  • Parameters

XML Tag Description
result Grouping tag. Describes notification processing result.
result_code Notification result code (positive integer). We recommend that the result codes returned by the merchant be in accordance with Notification codes table.

Authorization on Merchant’s Server

Merchant’s server should use basic-authorization or authorization by signature. Merchant may also use client SSL certificate verification (self-signed certificates may be used as well). QIWI Wallet server certificate should be verified in HTTPS requests.

Basic authorization

Example of notification with Basic auth

POST /qiwi-notify.php HTTP/1.1
Accept: text/xml
Content-type: application/x-www-form-urlencoded
Authorization: Basic ***
Host: example.com

command=bill&bill_id=BILL-1&status=paid&error=0&amount=1.00&user=tel%3A%2B79031811737&prv_name=Retail_Store&ccy=RUB&comment=test

The login is taken from Shop ID parameter. To obtain password, click on Change notification password button in Protocols details — REST-protocol section of QIWI partners web site.

  • Details

Authorization by signature

Example of notification with Signature

POST /qiwi-notify.php HTTP/1.1
Accept: text/xml
Content-type: application/x-www-form-urlencoded
X-Api-Signature: J4WNfNZd***V5mv2w=
Host: example.com

command=bill&bill_id=LocalTest17&status=paid&error=0&amount=0.01&user=tel%3A%2B78000005122&prv_name=Test&ccy=RUB&comment=Some+Descriptor

Example of notification processing with signature check

<?php

function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

//Signature generation by key and string
function checkSign($key, $req){
    $sign_hash = hash_hmac("sha1", $req, $key);
    $sign_tr = hexToStr($sign_hash);
    $sign = base64_encode($sign_tr);
    return $sign;
}

//Sort POST-request parameters and return values
function getReqParams(){
    $reqparams = "";
    ksort($_POST);
    foreach ($_POST as $param => $valuep) {
        $reqparams = "$reqparams|$valuep";
    }
    return substr($reqparams,1);
}

//Take signature from the request
function getSign(){
    $HEADERS = getallheaders();
    foreach ($HEADERS as $header => $value) {
       if ($header == 'X-Api-Signature') {
            $SIGN_REQ = $value;
       }
    }
    return $SIGN_REQ;
}

// Sort parameters
$Request = getReqParams();
// Notification password
$NOTIFY_PWD = "***";
// Get sign
$reqres = checkSign($NOTIFY_PWD, $Request);

// Get sign from the request
$SIGN_REQ = getSign();

if ($reqres == $SIGN_REQ) {
    $error = 0;
}
else $error = 151;

//Response
header('Content-Type: text/xml');
$xmlres = <<<XML
<?xml version="1.0"?>
<result>
<result_code>$error</result_code>
</result>
XML;
echo $xmlres;
?>

The HTTP header X-Api-Signature with signature is added to the POST-request. Signature is calculated as HMAC algorithm with SHA1-hash function.

  • Parameters’ separator is |.
  • Signed are all the parameters in the original invoice request.
  • Parameters are in alphabetical order and UTF-8 byte-encoded.
  • Secret key for signature is the password for notification basic-authorization.

Signature verification algorithm is as follows:

  1. Prepare a string of all parameters values from the notification POST-request sorted in alphabetical order and separated by |:

    {parameter1}|{parameter2}|…

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

  2. Transform obtained string and password for the notification basic-authorization into bytes encoded in UTF-8.
  3. Apply HMAC-SHA1 function:

    hash = HMAС(SHA1, Notification_password_bytes, Invoice_parameters_bytes)
    Where:

    • Notification_password_bytes – secret key (bytecoded notification password);
    • Invoice_parameters_bytes – bytecoded POST-request body;
    • hash – hash-function result.
  4. Transform HMAC-hash value into bytes with UTF-8 and Base64-encode it.
  5. Compare X-Api-Signature header’s value with the result of step 4.

PHP Implementation Example

The given PHP example implements notification authorization by signature verification. Open the PHP tab on the right.

Notification Codes

Code Description
0 Success
5 The format of the request parameters is incorrect
13 Database connection error
150 Incorrect password
151 Signature authorization failed
300 Server connection error

Шаг 1. Выпуск приватного ключа

Шаг 1. Выпуск приватного ключаОчень важно понимать, что для P2P нужен приватный ключ, а не токен!

Переходим по ссылке и нажимаем «Создать пару ключей и настроить»

Вводим любое название для пары.
Ставим галочку «Использовать эту пару ключей для серверных уведомлений об изменении статусов счетов» (Не обязательно, но с ней платеж будет проверяться без нажатия клиентом на кнопку «Проверить оплату»)
В полу для уведомлений, вставляем: https://api.bot-t.com/payment/qiwi

Шаг 2. Копирование ключа

Шаг 2. Копирование ключаДалее копируем секретный ключ. Лучше всего это сделать нажав на кнопку, чтобы случайно не упустить символы в ключе!

Возможные проблемы:

1) HTTP/1.1 401 Unauthorized
Решение:
Вы ввели неверный секретный ключ или вовсе токен
2) HTTP/1.1 404 Not Found
Решение:
Номер телефона указан неверно или кошелек не существует

Создать бота:
бесплатно и без знаний программирования BOT-T.COM

Понравилась статья? Поделить с друзьями:
  • Ошибка 401 меркурий 115 ф
  • Ошибка 401 мазда демио
  • Ошибка 401 летай тв как исправить
  • Ошибка 4009 ман тга
  • Ошибка 4009 wargaming