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

100% Statements 41/41
100% Branches 21/21
83.33% Functions 10/12
100% Lines 34/34

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 2635x 5x 5x 5x 5x 5x                                         5x                       6x   6x 6x   6x                           2x                         7x   1x     5x                                                             4x   4x   4x 4x 1x       4x                   4x         4x         4x                         1x                       3x                                 5x   5x                                               2x   2x 2x 1x       2x                 2x                                                                                  
import { URL } from "../shared/url-globals";
import { generateUUID } from "../shared/uuid";
import { url } from "../shared/url";
import { formatOffsetAltLifetimeDate, formatOffsetDate } from "../shared/time";
import { compareQiwiHmac } from "../shared/hmac";
import { P2pApi } from "./api";
import type {
  BillCreateParameters,
  BillFormParameters as BillFormParameters,
  BillPaySourceAny,
  BillRefundStatusData,
  BillStatusBody,
  BillStatusData,
  BillStatusNotificationBody,
  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,
    options: PayUrlPatchParameters = {}
  ): string {
    const url = new URL(payUrl);
 
    if (options.paySource) url.searchParams.set("paySource", options.paySource);
    if (options.successUrl) url.searchParams.set("successUrl", options.successUrl);
 
    return url.toString();
  }
 
  /**
   *
   *
   * @private
   * @param {(BillPaySourceAny | BillPaySourceAny[])} paySourcesFilter
   * @return {string} string
   * @memberof P2pBillsApi
   */
  private _resolvePaySourcesFilter(
    paySourcesFilter: BillPaySourceAny | BillPaySourceAny[]
  ): string {
    return Array.isArray(paySourcesFilter)
      ? paySourcesFilter.join(",")
      : String(paySourcesFilter);
  }
 
  /**
   * Нормализует сумму до строки с 2 числами после запятой
   *
   * @private
   * @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));
  }
 
  generateId = () => generateUUID();
 
  /**
   * ### Выставление счета
   *
   * **По оплаченным счетам возврат денежных средств не предусмотрен.**
   *
   * Доступно выставление счетов в рублях и тенге.
   * Надежный способ для интеграции. Параметры передаются
   * server2server с использованием авторизации. Метод позволяет
   * выставить счет: при успешном выполнении запроса в ответе
   * вернется параметр `payUrl` - ссылка для редиректа
   * пользователя на форму.
   *
   * [Настройки формы и счета](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(),
      themeCode,
      expirationDateTime = formatOffsetDate(15, "min"),
      paySourcesFilter,
      ...bill
    } = data;
 
    const customFields = bill.customFields ?? {};
 
    if (themeCode) customFields.themeCode = themeCode;
    if (paySourcesFilter) {
      customFields.paySourcesFilter =
        this._resolvePaySourcesFilter(paySourcesFilter);
    }
 
    const patchedBill = {
      ...bill,
      expirationDateTime,
      customFields,
      amount: {
        currency: bill.amount.currency,
        value: this._normalizeAmount(bill.amount.value)
      }
    };
 
    const result = await this.http.put<BillStatusData>(
      url`${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(url`${billId}`());
  }
 
  /**
   * ### Отмена неоплаченного счета
   *
   * Метод позволяет отменить счет, по которому не был выполнен перевод.
   *
   * @param {string} billId Уникальный идентификатор счета в вашей системе.
   * @return {Promise<BillStatusData>} Объект счёта
   */
  async reject(billId: string): Promise<BillStatusData> {
    return await this.http.post(url`${billId}/reject`());
  }
 
  /**
   *
   *
   * @param {string} signature
   * @param {(BillStatusNotificationBody | BillStatusBody | BillStatusBody)} body
   * @param {*} [merchantSecret=this.secretKey]
   * @return {*} boolean
   * @memberof P2pBillsApi
   */
  checkNotificationSignature(
    signature: string,
    body: BillStatusNotificationBody | BillStatusBody,
    merchantSecret = this.secretKey
  ): boolean {
    if ("bill" in body) body = body.bill;
 
    return compareQiwiHmac(merchantSecret, signature, [
      body.amount.currency,
      body.amount.value.toString(),
      body.billId,
      body.siteId,
      body.status.value
    ]);
  }
 
  /**
   *  Создаёт ссылку оплаты счёта без запроса к API
   *
   * @param {BillFormParams} parameters GET-параметры ссылки
   *
   * @return {string} Ссылка на оплату счёта
   */
  createFormUrl(parameters: BillFormParameters): string {
    const {
      lifetime = formatOffsetAltLifetimeDate(15, "min"),
      themeCode,
      customFields = {},
      billId = this.generateId(),
      paySourcesFilter,
      ...bill
    } = parameters;
 
    if (themeCode) customFields.themeCode = themeCode;
    if (paySourcesFilter) {
      customFields.paySourcesFilter =
        this._resolvePaySourcesFilter(paySourcesFilter);
    }
 
    const options = {
      ...bill,
      billId,
      lifetime,
      amount: this._normalizeAmount(parameters.amount),
      publicKey: this.publicKey,
      customFields
    };
 
    return url`https://oplata.qiwi.com/create`(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(url`${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(url`${billId}/refunds/${refundId}`());
  }
}