Passed
Push — master ( ec2c00...5a182f )
by Владислав
46s queued 10s
created

RuCaptchaReCaptchaV3   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 2
lcom 1
cbo 2
dl 0
loc 175
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 167 1
A recognize() 0 4 1
1
<?php
2
3
namespace jumper423\decaptcha\services;
4
5
/**
6
 * Class RuCaptchaReCaptchaV3.
7
 */
8
class RuCaptchaReCaptchaV3 extends RuCaptcha
9
{
10
    public function init()
11
    {
12
        parent::init();
13
14
        unset(
15
            $this->paramsNames[static::ACTION_FIELD_FILE],
16
            $this->paramsNames[static::ACTION_FIELD_NUMERIC],
17
            $this->paramsNames[static::ACTION_FIELD_MIN_LEN],
18
            $this->paramsNames[static::ACTION_FIELD_MAX_LEN],
19
            $this->paramsNames[static::ACTION_FIELD_QUESTION],
20
            $this->paramsNames[static::ACTION_FIELD_PHRASE],
21
            $this->paramsNames[static::ACTION_FIELD_CALC],
22
            $this->paramsNames[static::ACTION_FIELD_REGSENSE],
23
            $this->paramsNames[static::ACTION_FIELD_LANGUAGE],
24
            $this->paramsNames[static::ACTION_FIELD_LANG],
25
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_FILE],
26
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_REGSENSE],
27
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_NUMERIC],
28
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_MIN_LEN],
29
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_MAX_LEN],
30
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_PHRASE],
31
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_CALC],
32
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_QUESTION],
33
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_LANGUAGE],
34
            $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_LANG]
35
        );
36
37
        $this->paramsNames[static::ACTION_FIELD_GOOGLEKEY] = 'googlekey';
38
        $this->paramsNames[static::ACTION_FIELD_PROXY] = 'proxy';
39
        $this->paramsNames[static::ACTION_FIELD_PROXYTYPE] = 'proxytype';
40
        $this->paramsNames[static::ACTION_FIELD_PAGEURL] = 'pageurl';
41
        $this->paramsNames[static::ACTION_FIELD_ACTION] = 'action';
42
        $this->paramsNames[static::ACTION_FIELD_MIN_SCORE] = 'min_score';
43
44
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_METHOD][static::PARAM_SLUG_DEFAULT] = 'userrecaptcha';
45
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_VERSION] = [
46
            static::PARAM_SLUG_REQUIRE => true,
47
            static::PARAM_SLUG_TYPE    => static::PARAM_FIELD_TYPE_STRING,
48
            static::PARAM_SLUG_DEFAULT => 'v3',
49
            static::PARAM_SLUG_NOTWIKI => true,
50
        ];
51
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_GOOGLEKEY] = [
52
            static::PARAM_SLUG_REQUIRE => true,
53
            static::PARAM_SLUG_TYPE    => static::PARAM_FIELD_TYPE_STRING,
54
        ];
55
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_PAGEURL] = [
56
            static::PARAM_SLUG_REQUIRE => true,
57
            static::PARAM_SLUG_TYPE    => static::PARAM_FIELD_TYPE_STRING,
58
        ];
59
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_ACTION] = [
60
            static::PARAM_SLUG_REQUIRE  => false,
61
            static::PARAM_SLUG_DEFAULT  => 'verify',
62
            static::PARAM_SLUG_TYPE     => static::PARAM_FIELD_TYPE_STRING,
63
        ];
64
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_MIN_SCORE] = [
65
            static::PARAM_SLUG_DEFAULT  => 0.4,
66
            static::PARAM_SLUG_TYPE     => static::PARAM_FIELD_TYPE_FLOAT,
67
        ];
68
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_PROXY] = [
69
            static::PARAM_SLUG_TYPE    => static::PARAM_FIELD_TYPE_STRING,
70
        ];
71
        $this->actions[static::ACTION_RECOGNIZE][static::ACTION_FIELDS][static::ACTION_FIELD_PROXYTYPE] = [
72
            static::PARAM_SLUG_TYPE    => static::PARAM_FIELD_TYPE_STRING,
73
        ];
74
75
        $this->wiki->setText(['service', 'name'], [
76
            'ru' => 'RuCaptcha ReCaptcha v3',
77
            'en' => 'RuCaptcha ReCaptcha v3',
78
        ]);
79
        $this->wiki->setText(['recognize', 'price'], [
80
            'ru' => '1000 решений стоят 160 рублей.',
81
            'en' => '1000 for $2,99',
82
        ]);
83
        $this->wiki->setText(['recognize', 'desc'], [
84
            'ru' => '1) В первую очередь нужно убедиться, что на сайте действительно используется ReCaptcha V3.
85
86
Основные признаки V3:
87
не видна пользователю, не требует кликать по картинкам;
88
скрипт api.js загружается с параметром render=sitekey, например:
89
https://www.google.com/recaptcha/api.js?render=6Ld0KL0UABBBBCd2-aa00bbCCddeee1FfF2gHiJK
90
в массиве clients конфигурационного объекта ___grecaptcha_cfg используется индекс 100000: ___grecaptcha_cfg.clients[100000]
91
92
2) Для решения V3 через наш API необходимо найти значения трех параметров:
93
94
sitekey - его можно найти в html в значении параметра render при загрузке api.js, в параметре k в URI iframe, в который подгружается ReCaptcha, либо в javscript, в вызове функции grecaptcha.execute или в конфигурационном объекте ___grecaptcha_cfg.
95
96
action - это значение нужно искать в javascript коде сайта в вызове функции grecaptcha.execute. Пример: grecaptcha.execute(\'6Ld0KL0UABBBBCd2-aa00bbCCddeee1FfF2gHiJK\', {action: do_something}).
97
Иногда найти его достаточно сложно и требуется перевернуть вверх дном все js-файлы, подгружаемые сайтом. Кроме того, можно попробовать найти значение action в конфигурационном объекте ___grecaptcha_cfg, но очень часто оно может быть не задано там, а передаваться только при вызове grecaptcha.execute - поэтому наиболее эффективный метод - просмотр javascript кода.
98
pageurl - полный URL страницы, где вы хотите решить ReCaptcha V3.
99
100
Кроме того, нужно понять, какое значение score вам требуется. Определить извне, при каком score сайт решит, что вы человек и пропустит ваш запрос, можно только экспериментально. Самый низкий рейгинг 0.1 - робот, а самый высокий 0.9 - человек. Но, многие сайты ставят пороговые значения от 0.2 до 0.5, т.к. обычный человек зачастую получает довольно низкий рейтинг. С наибольшей вероятностью от нашего API можно получить score 0.3, более высокие значения score у работников встречаются довольно редко.
101
102
3) Имея все необходимые параметры, можно отправлять запрос.
103
104
4) После получения CODE, нужно корректно использовать его на сайте. Лучший метод понять, как это сделать - посмотреть на то, какие запросы отправляются на сайт, когда вы работаете с ним как обычный посетитель. Большинство браузеров позволяют легко это сделать в консоли разработчика, нужная вкладка обычно называется "Network".
105
106
Токен обычно отправляется в параметрах POST-запроса, это может быть g-recaptcha-response как у ReCaptcha V2, g-recaptcha-response-100000 или какой-либо другой параметр. Поэтому нужно внимательно просмотреть параметры запроса и найти, как именно передается токен, а затем сформировать аналогичный запрос.
107
108
5) После того, как вы использовали токен на сайте и стало понятно, сработал он или нет - вы можете сообщить нам об этом. В случае, если токен не был принят - мы вернем деньги за капчу на ваш баланс. А в случае, если токен был принят - мы поставим работника, который его получил в приоритет для ваших запросов. Кроме того, это позволяет нам копить и анализировать статистику по этому виду капч для последующей оптимизации алгоритмов ее решения.
109
110
Чтобы сообщить о том, сработал токен или нет 
111
112
```
113
$captcha->notTrue();
114
//или
115
$captcha->true();
116
```
117
',
118
            'en' => '1) First of all, you need to make sure that the site really uses ReCaptcha V3.
119
120
The main features of V3:
121
not visible to the user, does not require to click on the pictures;
122
The script api.js is loaded with the parameter render = sitekey, for example:
123
https://www.google.com/recaptcha/api.js?render=6Ld0KL0UABBBBCd2-aa00bbCCddeee1FfF2gHiJK
124
in the clients array of the ___grecaptcha_cfg configuration object, the index 100000 is used: ___ grecaptcha_cfg.clients [100000]
125
126
2) To solve V3 through our API, it is necessary to find the values ​​of three parameters:
127
128
sitekey - it can be found in html in the value of the render parameter when api.js is loaded, in the k parameter in the iframe URI into which ReCaptcha is loaded, either in javscript, in the function grecaptcha.execute or in the ___grecaptcha_cfg configuration object.
129
130
action - this value should be searched in the javascript code of the site in the function call grecaptcha.execute. Example: grecaptcha.execute (\'6Ld0KL0UABBBBCd2-aa00bbCCddeee1FfF2gHiJK\', {action: do_something}).
131
Sometimes it is quite difficult to find it and it is required to turn all js-files uploaded by the site upside down. In addition, you can try to find the value of action in the ___grecaptcha_cfg configuration object, but very often it may not be set there, but only transmitted when calling grecaptcha.execute - therefore the most effective method is to view javascript code.
132
pageurl - the full URL of the page where you want to solve ReCaptcha V3.
133
134
In addition, you need to understand what score you need. From the outside, it’s possible to determine at which score the site decides that you are human and miss your request, only experimentally. The lowest reiging 0.1 is a robot, and the highest 0.9 is a human. But, many sites set threshold values ​​from 0.2 to 0.5, because An ordinary person often gets a rather low rating. Most likely, our API can get score 0.3, higher scores for workers are quite rare.
135
136
3) Having all the necessary parameters, you can send a request.
137
138
4) After receiving the CODE, you need to correctly use it on the site. The best way to understand how to do this is to look at what requests are sent to the site when you work with it as a regular visitor. Most browsers make this easy to do in the developer console, the tab you need is usually called "Network."
139
140
The token is usually sent in the parameters of the POST request, it can be g-recaptcha-response like ReCaptcha V2, g-recaptcha-response-100000 or some other parameter. Therefore, you need to carefully review the request parameters and find out how the token is transmitted, and then form a similar request.
141
142
5) After you used the token on the site and it became clear whether it worked or not - you can tell us about it. In case the token was not accepted - we will return the money for the captcha to your balance. And if the token was accepted, we will put the employee who received it as a priority for your requests. In addition, it allows us to save and analyze statistics on this type of captchas for the subsequent optimization of algorithms for its solution.
143
144
To report whether the token worked or not - send a request to http://rucaptcha.com/res.php with your API key in the key parameter, captcha id in the id parameter of the same name and specifying the action parameter, depending on the result: reportgood - the token worked or reportbad - the token did not work.
145
146
```
147
$captcha->notTrue();
148
//or
149
$captcha->true();
150
```',
151
        ]);
152
        $this->wiki->setText(['field', 'main', 'name', self::ACTION_FIELD_ACTION], [
153
            'ru' => 'Параметр action',
154
            'en' => 'Action parameter',
155
        ]);
156
        $this->wiki->setText(['field', 'main', 'desc', self::ACTION_FIELD_ACTION], [
157
            'ru' => 'Значение параметра action, которые вы нашли в коде сайта',
158
            'en' => 'The value of the action parameter that you found in the site code',
159
        ]);
160
        $this->wiki->setText(['recognize', 'data'], [
161
            static::ACTION_FIELD_GOOGLEKEY => '54as5c6a5s4ca4s56a4sc56a',
162
            static::ACTION_FIELD_PAGEURL   => 'http://site.com/recaptcha-ex',
163
            static::ACTION_FIELD_ACTION    => 'verify',
164
            static::ACTION_FIELD_MIN_SCORE => 0.3,
165
        ]);
166
        $this->wiki->setText(['recognize', 'file'], false);
167
        $this->wiki->setText(['menu', 'from_service'], [
168
            RuCaptcha::class,
169
            RuCaptchaClick::class,
170
            RuCaptchaInstruction::class,
171
            RuCaptchaGrid::class,
172
            RuCaptchaFunCaptcha::class,
173
            RuCaptchaReCaptcha::class,
174
            RuCaptchaGeeTest::class,
175
        ]);
176
    }
177
178
    public function recognize($additionally = [], $null = null)
179
    {
180
        return parent::recognize(null, $additionally);
181
    }
182
}
183