|
- import axios from 'axios'
-
- export class TwoCaptcha {
-
- private readonly CAPTCHA_KEY: string = 'TWO_CAPTCHA_KEY'
- private readonly CAPTCHA_CREATE: string = 'http://2captcha.com/in.php'
- private readonly CAPTCHA_RESULT: string = 'http://2captcha.com/res.php'
- private readonly CAPTCHA_BALANCE: string = 'https://2captcha.com/res.php'
-
- async resolveCaptcha (imageData: string) {
- const captchaId = await this._sendCaptcha(imageData)
- const captchaResolved = await this._getResponseCaptcha(captchaId)
- return captchaResolved
- }
-
- public async temSaldoDisponivel (): Promise<boolean> {
- try {
- const balanceData = {
- key: this.CAPTCHA_KEY,
- action: 'getbalance',
- json: 1
- }
- const { data: { request } } = await axios.get(this.CAPTCHA_BALANCE, { params: balanceData });
-
- if ((request || '').includes('ERROR_')) {
- console.log(`[consultar-saldo-captcha] - ${request}`);
- return false;
- }
-
- return Number(request) > 0;
- } catch (error) {
- console.log(`[consultar-saldo-captcha] - ${error.message}`);
-
- return false;
- }
- }
-
- private async _sendCaptcha (imageData: string): Promise<string> {
- try {
- const captchaResponse = await axios.post(
- this.CAPTCHA_CREATE,
- {
- method: 'base64',
- key: this.CAPTCHA_KEY,
- body: imageData,
- json: 1
- },
- { headers: { 'Content-Type': 'multipart/form-data' } }
- )
-
- let response: string = ''
-
- if (captchaResponse.data && typeof captchaResponse.data === 'object') {
- if (captchaResponse.data.status === 0)
- throw new Error(captchaResponse.data.request)
- response = captchaResponse.data.request
- } else if (
- captchaResponse.data &&
- typeof captchaResponse.data === 'string'
- ) {
- if (captchaResponse.data.indexOf('OK') === -1)
- throw new Error(captchaResponse.data)
- response = captchaResponse.data.split('|')[1]
- }
-
- return response
- } catch (error) {
- return new Promise((resolve, reject) => reject(error))
- }
- }
-
- private async _getResponseCaptcha (captchaId: string): Promise<string> {
- return new Promise((resolve, reject) => {
- const interval = setInterval(async () => {
- try {
- const serverResponse = await axios.get(this.CAPTCHA_RESULT, {
- params: {
- key: this.CAPTCHA_KEY,
- action: 'get',
- id: captchaId,
- json: 1
- }
- })
-
- if (serverResponse.data.request !== 'CAPCHA_NOT_READY') {
- clearInterval(interval)
-
- let response = ''
-
- if (
- serverResponse.data &&
- typeof serverResponse.data === 'object'
- ) {
- if (serverResponse.data.status === 0)
- throw new Error(serverResponse.data.request)
- response = serverResponse.data.request
- } else if (
- serverResponse.data &&
- typeof serverResponse.data === 'string'
- ) {
- if (serverResponse.data.indexOf('OK') === -1)
- throw new Error(serverResponse.data)
- response = serverResponse.data.split('|')[1]
- }
-
- resolve(response)
- }
- } catch (e) {
- reject(e)
- }
- }, 10 * 1000)
- })
- }
- }
|