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

100% Statements 14/14
100% Branches 0/0
100% Functions 3/3
100% Lines 14/14

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    5x 5x 5x                             5x 5x 5x 5x   8x                   1x                     1x                           1x   1x             1x             1x            
/* istanbul ignore next */
import { url } from "../shared/url";
import { SimpleJsonHttp } from "../shared/http";
import { formatQuerystring } from "../shared/querystring";
import { WalletApi } from "./api";
import type {
  CodeResponse,
  TokenResponse,
  ShortTokenResponse
} from "./wallet.types";
 
/**
 * # Доступ к API QIWI Кошелька
 * [Документация QIWI](https://developer.qiwi.com/ru/qiwi-wallet-personal-advanced/)
 *
 * @export
 * @class WalletOauthApi
 * @extends {WalletApi}
 */
export class WalletOauthApi extends WalletApi {
  static readonly CLIENT_ID = "api_wallet_private";
  static readonly CLIENT_SECRET = "hTFPyt";
  static readonly CLIENT_SOFTWARE = "api";
 
  protected readonly _http = new SimpleJsonHttp();
 
  /**
   *
   *
   * @protected
   * @return {SimpleJsonHttp}
   * @memberof WalletOauthApi
   */
  protected _getHttp(): SimpleJsonHttp {
    this._http.client.options = {
      ...this._options.http.client.options,
      baseURL: url`https://qiwi.com/oauth/`(),
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "application/json"
      },
      stringifyBody: formatQuerystring,
      okStatusCodes: [200]
    };
 
    return this._http;
  }
 
  /**
   * ## Выпуск OAuth-токена
   *
   * Создаёт токен с увеличенным сроком действия (10 лет)
   *
   * [Документация](https://developer.qiwi.com/ru/qiwi-wallet-personal-advanced/?http#intro)
   *
   * @return {Promise<TokenResponse<Wallet>>} Promise<PrettyTokenResponse<Wallet>>
   * @memberof WalletOauthApi
   */
  async createToken(): Promise<ShortTokenResponse> {
    const http = this._getHttp();
 
    const codeResponse = await http.post<CodeResponse>(url`authorize`(), {
      response_type: "code",
      token: this._options.token,
      client_id: WalletOauthApi.CLIENT_ID,
      client_software: WalletOauthApi.CLIENT_SOFTWARE
    });
 
    const tokenResponse = await http.post<TokenResponse>(url`token`(), {
      grant_type: "authorization_code",
      client_id: WalletOauthApi.CLIENT_ID,
      client_secret: WalletOauthApi.CLIENT_SECRET,
      code: codeResponse.code
    });
 
    return {
      token: tokenResponse.access_token,
      expiry: Number.parseInt(tokenResponse.expires_in, 10)
    };
  }
}