All files / src/services p2p.ts

90.48% Statements 76/84
63.64% Branches 21/33
90.48% Functions 19/21
94.67% Lines 71/75

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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345  3x 3x 3x 3x 3x 3x 3x   3x               3x         1x 1x                         1x 1x   1x   1x   1x 1x                           2x 2x 2x   2x   2x           2x                   3x 3x 3x       1x             1x                   1x 1x                                               3x       4x               4x                   6x   1x                         3x 1x                       3x 3x                 3x   3x   3x   3x               4x                           5x             5x   5x                                                                                                     1x 1x   1x 5x   5x 5x 5x   5x 5x 5x     5x     5x       5x   5x   4x 2x     2x   2x 2x   2x                             1x           1x             1x   1x      
/* eslint-disable no-invalid-this */
import { createHmac } from "crypto";
import { MapErrorsAsync } from "sweet-decorators";
import { v4 as uuid } from "uuid";
import { createQS, formatDate } from "./shared";
import { ErrorWithCode } from "../error";
import { Agent, HttpAPI, HttpError } from "../http";
import { USER_AGENT } from "../identity";
import type * as types from "./p2p.types";
import { BillCurrency, BillStatus } from "./p2p.types";
import { AnyResponse } from "./shared.types";
import { RequestHandler } from "express";
 
/**
 * Ошибка, которую выбрасывает P2P API в случае неправильного
 * кода ответа от QIWI
 */
export class P2PPaymentError extends ErrorWithCode<string> {
  /**
   *
   * @param {*} data
   */
  constructor(public data: AnyResponse) {
    super(data.description, data.errorCode);
  }
}
 
/**
 * Проверяет ответ на предмет ошибки.
 * Если вернулась ошибка - кидает её
 *
 * @throws {P2PPaymentError} Ошибка запроса к QIWI P2P
 * @param {T | Promise<T>} error Ответ от сервера
 * @return {Error}
 */
function mapErrors(error: any) {
  Eif (error instanceof HttpError) {
    Iif (!error.body) return error;
 
    const billError = JSON.parse(error.body) as types.BillError;
 
    billError.description += ` (${error.code})`;
 
    Eif ("errorCode" in billError) {
      return new P2PPaymentError(billError);
    }
  }
 
  return error;
}
 
/**
 * @template {CallableFunction} T
 *
 * @param {T} function_
 * @return {T}
 */
function promise<T extends (...parameters: any) => any>(function_: T) {
  const wrapper = (...parameters: any[]): any => {
    try {
      const result = function_(...parameters);
 
      Iif (result instanceof Promise) return result;
 
      return Promise.resolve(result);
    } catch (error) {
      return Promise.reject(error);
    }
  };
 
  return wrapper as (
    ...arguments_: Parameters<T>
  ) => ReturnType<T> extends Promise<any> ? ReturnType<T> : Promise<ReturnType<T>>;
}
 
/**
 * Имплементирует [P2P API QIWI](https://developer.qiwi.com/ru/p2p-payments)
 *
 * @see {@link https://developer.qiwi.com/ru/p2p-payments|Описание}
 */
export class P2P extends HttpAPI {
  public static readonly BillStatus = BillStatus;
  public static readonly Currency = BillCurrency;
 
  public agent?: Agent;
 
  protected readonly API_HEADERS = {
    Accept: "application/json",
    "Content-Type": "application/json;charset=UTF-8",
    Authorization: `Bearer ${this.secretKey}`,
    "User-Agent": USER_AGENT
  };
 
  protected readonly API_URL = "https://api.qiwi.com/partner/bill/v1/bills";
 
  /**
   *
   * Создаёт клиент P2P API используя Публичный и Приватный ключи,
   * полученные на {@link https://qiwi.com/p2p-admin/transfers/api|Странице P2P API QIWI}
   *
   * @param {string} secretKey Публичный ключ
   * @param {string=} publicKey Приватный ключ (необязателен)
   */
  constructor(public secretKey: string, public publicKey: string = "") {
    super();
  }
 
  /**
   * ### Выставление счета
   *
   * **По оплаченным счетам возврат денежных средств не предусмотрен.**
   *
   * Доступно выставление счетов в рублях и тенге.
   * Надежный способ для интеграции. Параметры передаются
   * server2server с использованием авторизации. Метод позволяет
   * выставить счет: при успешном выполнении запроса в ответе
   * вернется параметр `payUrl` - ссылка для редиректа
   * пользователя на форму.
   *
   * {@link https://developer.qiwi.com/ru/p2p-payments/#option|Настройки формы и счета}
   *
   * **Для тестирования и отладки сервиса рекомендуем выставлять и оплачивать счета суммой 1 рубль.**
   *
   * @param {types.BillCreationRequest} data Сформированный запрос на создание счёта
   * @param {string=} id Свой ID счёта. По умолчанию генерируется UUID
   * @return {Promise<types.BillStatusData>}
   */
  @MapErrorsAsync(mapErrors)
  public createBill(
    data: types.BillCreationRequest,
    id = this._generateId()
  ): Promise<types.BillStatusData> {
    const patchedBill = {
      ...data,
      amount: {
        currency: data.amount.currency,
        value: this._normalizeAmount(data.amount.value)
      }
    };
 
    return this.put(id, {}, JSON.stringify(patchedBill));
  }
 
  /**
   * Нормализует сумму до строки с 2 числами после запятой
   *
   * @param {string|number} amount Сумма
   * @return {string}
   */
  private _normalizeAmount(amount: string | number): string {
    if (typeof amount === "number") return amount.toFixed(2);
 
    return this._normalizeAmount(Number.parseFloat(amount));
  }
 
  /**
   * ### Проверка статуса перевода по счету
   *
   * Метод позволяет проверить статус перевода по счету. Рекомендуется
   * его использовать после получения уведомления о переводе.
   *
   * @param {string} billId Уникальный идентификатор счета в вашей системе.
   * @return {Promise<types.BillStatusData>} Объект счёта
   */
  @MapErrorsAsync(mapErrors)
  public billStatus(billId: string): Promise<types.BillStatusData> {
    return this.get(billId);
  }
 
  /**
   * ### Отмена неоплаченного счета
   *
   * Метод позволяет отменить счет, по которому не был выполнен перевод.
   *
   * @param {string} billId Уникальный идентификатор счета в вашей системе.
   * @return {Promise<types.BillStatusData>} Объект счёта
   */
  @MapErrorsAsync(mapErrors)
  public rejectBill(billId: string): Promise<types.BillStatusData> {
    return this.post(`${billId}/reject`);
  }
 
  /**
   *
   * @param {number} days Кол-во дней жизни счёта (может быть не целым числом)
   * @return {string} Дата понятная QIWI
   */
  public static formatLifetime(days = 1): string {
    const date = new Date();
 
    const time = Math.round(date.getTime() + days * 24 * 60 * 60 * 1000);
 
    date.setTime(time);
 
    return formatDate(date);
  }
 
  /**
   * Генерирует UUID
   * @return {string} UUID
   */
  protected _generateId(): string {
    return uuid();
  }
 
  /**
   * Проверяет подпись уведомления о статусе счёта
   *
   * @param {string} signature Подпись
   * @param {types.BillStatusData} body Объект уведомления
   * @return {boolean} Признак валидности
   */
  public checkNotificationSignature(
    signature: string,
    body: types.BillStatusData
  ): boolean {
    const data = [
      body.amount.currency,
      body.amount.value,
      body.billId,
      body.siteId,
      body.status.value
    ].join("|");
    const hash = createHmac("sha256", this.secretKey).update(data).digest("hex");
 
    return signature === hash;
  }
 
  /**
   * `[Экспериментально]` Упрощает интеграцию с `express`
   *
   * ## Это middleware кидает ошибки, позаботьтесь об их обработке
   *
   * @param {Object} [options={}] Параметры обработки запроса
   * @param {boolean} [options.memo=true] Флаг для включения/отключения пропуска повторяющихся запросов, если один из них был успешно обработан
   *
   * @param {RequestHandler<Record<string, string>, any, types.BillStatusData>} actualHandler
   *
   * @return {RequestHandler}
   *
   * ##### Пример:
   * **В начале файла**
   * ```js
   * const p2p = new QIWI.P2P(process.env.QIWI_PRIVATE_KEY);
   * ```
   * *`Вариант 1 - Классический`*
   *
   * ```js
   * app.post('/webhook/qiwi', p2p.notificationMiddleware(), (req, res) => {
   *  req.body // Это `BillStatusData`
   * })
   * ```
   *
   * *`Вариант 2 - Если нужны подсказки типов`*
   *
   * ```js
   * app.post('/webhook/qiwi', p2p.notificationMiddleware({}, (req, res) => {
   *  req.body // Это `BillStatusData`
   * }))
   * ```
   *
   * **Обработка ошибок**
   * ```js
   * app.use((error, request, response, next) => {
   *  console.log(error); // [Error: Notification signature mismatch]
   * })
   * ```
   */
  public notificationMiddleware(
    options: { memo?: boolean } = {},
    actualHandler: RequestHandler<
      Record<string, string>,
      any,
      types.BillStatusData
    > = (_request, _response, next) => next()
  ): RequestHandler {
    const calls = new Set<string>();
    const { memo = true } = options;
 
    return async (request, response, next) => {
      let notification: any = {};
 
      Eif (!request.body) {
        const text = await new Promise<string>((resolve, reject) => {
          let accumulated = "";
 
          request.on("error", (error) => reject(error));
          request.on("data", (data) => (accumulated += String(data)));
          request.on("end", () => resolve(accumulated));
        });
 
        notification = JSON.parse(text) as any;
      }
 
      Iif (typeof request.body === "object") {
        notification = request.body;
      }
 
      const hash = request.headers["x-api-signature-sha256"] as string;
 
      if (memo && calls.has(hash)) return next();
 
      if (!this.checkNotificationSignature(hash, notification.bill)) {
        return next(new Error("Notification signature mismatch"));
      }
 
      request.body = notification.bill;
 
      Iif (!memo) return actualHandler(request, response, next);
      await promise(actualHandler)(request, response, next);
 
      calls.add(hash);
    };
  }
 
  /**
   *  Создаёт ссылку оплаты счёта без запроса к API
   *
   * @param {Omit<types.BillFormParams, "billId" | "publicKey">} parameters GET-параметры ссылки
   * @param {string=} billId Свой ID счёта, по умолчанию случайный UUID
   * @return {string} Ссылка на оплату счёта
   */
  public createBillFormUrl(
    parameters: Omit<types.BillFormParams, "billId" | "publicKey">,
    billId = this._generateId()
  ): string {
    const options: types.BillFormParams = {
      ...parameters,
      amount: this._normalizeAmount(parameters.amount),
      billId,
      publicKey: this.publicKey,
      ...Object.fromEntries(
        Object.entries(parameters.customFields ?? {}).map(([key, value]) => [
          `customFields[${key}]`,
          value
        ])
      )
    };
 
    delete options.customFields;
 
    return `https://oplata.qiwi.com/create?${createQS(options)}`;
  }
}