All files / apis/p2p bills.api.ts

13.79% Statements 4/29
0% Branches 0/14
0% Functions 0/12
16% Lines 4/25

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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 2321x 1x           1x                                     1x                                                                                                                                                                                                                                                                                                                                                                                                                          
import { URL } from "url";
import {
  compareHmac,
  formatOffsetDate,
  formatQuerystring,
  generateUUID
} from "../shared";
import { P2pApi } from "./api";
import type {
  BillCreateParameters,
  BillFormParameters as BillFormParameters,
  BillRefundStatusData,
  BillStatusBody,
  BillStatusData,
  PayUrlPatchParameters,
  RefundCreationRequest
} from "./p2p.types";
 
/**
 * # P2P-счета
 * [Документация QIWI](https://developer.qiwi.com/ru/p2p-payments/#p2p-)
 *
 * @export
 * @class P2pBillsApi
 * @extends {P2pApi}
 */
export class P2pBillsApi extends P2pApi {
  /**
   * Добавляет параметры
   *
   * @param {string} payUrl
   * @param {PayUrlPatchParameters=} [options]
   * @return {string} Новый URL для оплаты
   */
  public static patchPayUrl(
    payUrl: string,
    /* istanbul ignore next */
    options: PayUrlPatchParameters = {}
  ): string {
    const url = new URL(payUrl);
 
    Iif (options.paySource) url.searchParams.set("paySource", options.paySource);
    Iif (options.successUrl) url.searchParams.set("successUrl", options.successUrl);
 
    return url.toString();
  }
 
  /**
   * Нормализует сумму до строки с 2 числами после запятой
   *
   * @param {string|number} amount Сумма
   * @return {string}
   */
  protected _normalizeAmount(amount: string | number): string {
    Iif (typeof amount === "number") return amount.toFixed(2);
 
    return this._normalizeAmount(Number.parseFloat(amount));
  }
 
  generateId = () => generateUUID();
 
  /**
   * ### Выставление счета
   *
   * **По оплаченным счетам возврат денежных средств не предусмотрен.**
   *
   * Доступно выставление счетов в рублях и тенге.
   * Надежный способ для интеграции. Параметры передаются
   * server2server с использованием авторизации. Метод позволяет
   * выставить счет: при успешном выполнении запроса в ответе
   * вернется параметр `payUrl` - ссылка для редиректа
   * пользователя на форму.
   *
   * {@link https://developer.qiwi.com/ru/p2p-payments/#option|Настройки формы и счета}
   *
   * **Для тестирования и отладки сервиса рекомендуем выставлять и оплачивать счета суммой 1 рубль.**
   *
   * @param {BillCreateParameters} data
   * @return {Promise<BillStatusData>}  {Promise<BillStatusData>}
   * @memberof P2pBillsApi
   */
  async create(data: BillCreateParameters): Promise<BillStatusData> {
    const {
      paySource,
      successUrl,
      billId = this.generateId(),
      expirationDateTime = formatOffsetDate(15, "min"),
      ...bill
    } = data;
 
    const patchedBill = {
      ...bill,
      expirationDateTime,
      amount: {
        currency: bill.amount.currency,
        value: this._normalizeAmount(bill.amount.value)
      }
    };
 
    const result = await this.http.put<BillStatusData>(billId, patchedBill);
 
    result.payUrl = P2pBillsApi.patchPayUrl(result.payUrl, {
      paySource,
      successUrl
    });
 
    return result;
  }
 
  /**
   * ### Проверка статуса перевода по счету
   *
   * Метод позволяет проверить статус перевода по счету. Рекомендуется
   * его использовать после получения уведомления о переводе.
   *
   * @param {string} billId Уникальный идентификатор счета в вашей системе.
   * @return {Promise<BillStatusData>} Объект счёта
   */
  async getStatus(billId: string): Promise<BillStatusData> {
    return await this.http.get(billId);
  }
 
  /**
   * ### Отмена неоплаченного счета
   *
   * Метод позволяет отменить счет, по которому не был выполнен перевод.
   *
   * @param {string} billId Уникальный идентификатор счета в вашей системе.
   * @return {Promise<BillStatusData>} Объект счёта
   */
  async reject(billId: string): Promise<BillStatusData> {
    return await this.http.post(`${billId}/reject`);
  }
 
  /**
   *
   *
   * @param {string} signature
   * @param {(BillStatusData | BillStatusBody)} body
   * @param {*} [merchantSecret=this.secretKey]
   * @return {*}  {boolean}
   * @memberof P2pBillsApi
   */
  checkNotificationSignature(
    signature: string,
    body: BillStatusData | BillStatusBody,
    merchantSecret = this.secretKey
  ): boolean {
    /* istanbul ignore next */
    if ("bill" in body) body = body.bill;
 
    const data = [
      body.amount.currency,
      body.amount.value,
      body.billId,
      body.siteId,
      body.status.value
    ].join("|");
 
    return compareHmac({
      key: merchantSecret,
      data,
      digest: signature
    });
  }
 
  /**
   *  Создаёт ссылку оплаты счёта без запроса к API
   *
   * @param {BillFormParams} parameters GET-параметры ссылки
   *
   * @return {string} Ссылка на оплату счёта
   */
  createFormUrl(parameters: BillFormParameters): string {
    const options = {
      ...parameters,
      amount: this._normalizeAmount(parameters.amount),
      publicKey: this.publicKey,
      ...Object.fromEntries(
        Object.entries(parameters.customFields ?? {}).map(([key, value]) => [
          `customFields[${key}]`,
          value
        ])
      )
    };
 
    options.billId ??= generateUUID();
 
    delete options.customFields;
 
    return `https://oplata.qiwi.com/create?${formatQuerystring(options)}`;
  }
 
  /**
   *
   * @deprecated API заархивировано
   * @param {string} billId
   * @param {RefundCreationRequest} options
   * @return {Promise<BillRefundStatusData>}  {Promise<BillRefundStatusData>}
   * @memberof P2pBillsApi
   */
  async refund(
    billId: string,
    options: RefundCreationRequest
  ): Promise<BillRefundStatusData> {
    /* istanbul ignore next */
    const { refundId = this.generateId(), amount } = options;
 
    /* istanbul ignore next */
    amount.value = this._normalizeAmount(amount.value);
 
    /* istanbul ignore next */
    return await this.http.put(`${billId}/refunds/${refundId}`);
  }
 
  /**
   *
   * @deprecated API заархивировано
   * @param {string} billId
   * @param {string} refundId
   * @return {Promise<BillRefundStatusData>}  {Promise<BillRefundStatusData>}
   * @memberof P2pBillsApi
   */
  async getRefundStatus(
    billId: string,
    refundId: string
  ): Promise<BillRefundStatusData> {
    /* istanbul ignore next */
    return await this.http.get(`${billId}/refunds/${refundId}`);
  }
}