All files / src/apis/wallet bills.api.ts

80% Statements 4/5
100% Branches 1/1
25% Functions 1/4
80% Lines 4/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 1234x 4x                                         4x                                                                                                                 1x                                                                                      
import { formatQuerystring } from "../shared";
import { WalletApi } from "./api";
import {
  Bill,
  BillPayResponse,
  BillsGetParameters,
  Currency,
  KeyPair
} from "./wallet.types";
 
/**
 * # Выставление счета на QIWI кошелек
 * [Документация QIWI](https://developer.qiwi.com/ru/qiwi-wallet-personal/#invoices)
 *
 * Для выставления счета на QIWI Кошелек используется протокол
 * [API P2P-счетов](https://developer.qiwi.com/ru/p2p-payments/#create).
 * Для авторизации используется [токен P2P](https://developer.qiwi.com/ru/qiwi-wallet-personal/#p2p-token).
 *
 * @export
 * @class WalletBillsApi
 * @extends {WalletApi}
 */
export class WalletBillsApi extends WalletApi {
  /**
   * ## Выпуск токена P2P
   *
   * Запрос возвращает пару токенов P2P (для выставления счета
   * при вызове платежной формы и через API, соответственно) в
   * полях ответа PublicKey и SecretKey. Для авторизации
   * используется токен API QIWI Кошелька.
   *
   * @param {string} name Название связки ключей
   * @param {string=} [server] URL сервера для отправки уведомлений
   *
   * @return {Promise<KeyPair>} {Promise<KeyPair>}
   * @memberof WalletBillsApi
   *
   * @example
   *
   * const { publicKey, secretKey } = await createP2PKeyPair('my-key-pair');
   */
  async createP2PKeyPair(name: string, server?: string): Promise<KeyPair> {
    /* istanbul ignore next */
    const response = await this.http.post<any>(
      "widgets-api/api/p2p/protected/keys/create",
      {
        keysPairName: name,
        ...(server && { serverNotificationsUrl: server })
      }
    );
 
    /* istanbul ignore next */
    const publicKey: string = response.result?.publicKey ?? response.PublicKey;
    /* istanbul ignore next */
    const secretKey: string = response.result?.secretKey ?? response.SecretKey;
 
    return { publicKey, secretKey };
  }
 
  /**
   * ## Список счетов
   *
   * Метод получения списка неоплаченных счетов вашего кошелька.
   * Список строится в обратном хронологическом порядке. По
   * умолчанию, список разбивается на страницы по 50 элементов в
   * каждой, но вы можете задать другое количество элементов (не
   * более 50). В запросе можно использовать фильтры по времени
   * выставления счета, начальному идентификатору счета.
   *
   * @param {BillsGetParameters} [parameters={}]
   * @return {Promise<Bill[]>}  {Promise<Bill[]>}
   * @memberof WalletBillsApi
   */
  async get(parameters: BillsGetParameters = {}): Promise<Bill[]> {
    /* istanbul ignore next */
    const { bills } = await this.http.get(
      `checkout-api/api/bill/search?${formatQuerystring(parameters)}`
    );
 
    return bills;
  }
 
  pay(bill: Bill): Promise<BillPayResponse>;
  pay(id: Bill["id"], currency: Currency): Promise<BillPayResponse>;
 
  /**
   *
   *
   * @param {(number|Bill)} bill
   * @param {Currency=} [currency]
   * @return {Promise<BillPayResponse>}  {Promise<BillPayResponse>}
   * @memberof WalletBillsApi
   */
  async pay(bill: Bill["id"] | Bill, currency?: Currency): Promise<BillPayResponse> {
    /* istanbul ignore next */
    if (typeof bill === "object") {
      currency = bill.sum.currency;
      bill = bill.id;
    }
 
    /* istanbul ignore next */
    return await this.http.post("checkout-api/invoice/pay/wallet", {
      invoice_uid: bill.toString(),
      currency
    });
  }
 
  /**
   * ## Отмена неоплаченного счета
   *
   * Метод отклоняет неоплаченный счет. При этом счет становится
   * недоступным для оплаты.
   *
   * @param {number} id
   * @return {Promise<void>}  {Promise<void>}
   * @memberof WalletBillsApi
   */
  async reject(id: Bill["id"]): Promise<void> {
    /* istanbul ignore next */
    await this.http.post("checkout-api/api/bill/reject", { id });
  }
}