gt4.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. "v4.1.5 Geetest Inc.";
  2. (function (window) {
  3. "use strict";
  4. if (typeof window === 'undefined') {
  5. throw new Error('Geetest requires browser environment');
  6. }
  7. var document = window.document;
  8. var Math = window.Math;
  9. var head = document.getElementsByTagName("head")[0];
  10. var TIMEOUT = 10000;
  11. function _Object(obj) {
  12. this._obj = obj;
  13. }
  14. _Object.prototype = {
  15. _each: function (process) {
  16. var _obj = this._obj;
  17. for (var k in _obj) {
  18. if (_obj.hasOwnProperty(k)) {
  19. process(k, _obj[k]);
  20. }
  21. }
  22. return this;
  23. },
  24. _extend: function (obj){
  25. var self = this;
  26. new _Object(obj)._each(function (key, value){
  27. self._obj[key] = value;
  28. })
  29. }
  30. };
  31. var uuid = function () {
  32. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33. var r = Math.random() * 16 | 0;
  34. var v = c === 'x' ? r : (r & 0x3 | 0x8);
  35. return v.toString(16);
  36. });
  37. };
  38. function Config(config) {
  39. var self = this;
  40. new _Object(config)._each(function (key, value) {
  41. self[key] = value;
  42. });
  43. }
  44. Config.prototype = {
  45. apiServers: ['gcaptcha4.geetest.com','gcaptcha4.geevisit.com','gcaptcha4.gsensebot.com'],
  46. staticServers: ["static.geetest.com",'static.geevisit.com', "dn-staticdown.qbox.me"],
  47. protocol: 'http://',
  48. typePath: '/load',
  49. fallback_config: {
  50. bypass: {
  51. staticServers: ["static.geetest.com",'static.geevisit.com',"dn-staticdown.qbox.me"],
  52. type: 'bypass',
  53. bypass: '/v4/bypass.js'
  54. }
  55. },
  56. _get_fallback_config: function () {
  57. var self = this;
  58. if (isString(self.type)) {
  59. return self.fallback_config[self.type];
  60. } else {
  61. return self.fallback_config.bypass;
  62. }
  63. },
  64. _extend: function (obj) {
  65. var self = this;
  66. new _Object(obj)._each(function (key, value) {
  67. self[key] = value;
  68. })
  69. }
  70. };
  71. var isNumber = function (value) {
  72. return (typeof value === 'number');
  73. };
  74. var isString = function (value) {
  75. return (typeof value === 'string');
  76. };
  77. var isBoolean = function (value) {
  78. return (typeof value === 'boolean');
  79. };
  80. var isObject = function (value) {
  81. return (typeof value === 'object' && value !== null);
  82. };
  83. var isFunction = function (value) {
  84. return (typeof value === 'function');
  85. };
  86. var MOBILE = /Mobi/i.test(navigator.userAgent);
  87. var callbacks = {};
  88. var status = {};
  89. var random = function () {
  90. return parseInt(Math.random() * 10000) + (new Date()).valueOf();
  91. };
  92. // bind 函数polify, 不带new功能的bind
  93. var bind = function(target,context){
  94. if(typeof target !== 'function'){
  95. return;
  96. }
  97. var args = Array.prototype.slice.call(arguments,2);
  98. if(Function.prototype.bind){
  99. return target.bind(context, args);
  100. }else {
  101. return function(){
  102. var _args = Array.prototype.slice.call(arguments);
  103. return target.apply(context,args.concat(_args));
  104. }
  105. }
  106. }
  107. var toString = Object.prototype.toString;
  108. var _isFunction = function(obj) {
  109. return typeof(obj) === 'function';
  110. };
  111. var _isObject = function(obj) {
  112. return obj === Object(obj);
  113. };
  114. var _isArray = function(obj) {
  115. return toString.call(obj) == '[object Array]';
  116. };
  117. var _isDate = function(obj) {
  118. return toString.call(obj) == '[object Date]';
  119. };
  120. var _isRegExp = function(obj) {
  121. return toString.call(obj) == '[object RegExp]';
  122. };
  123. var _isBoolean = function(obj) {
  124. return toString.call(obj) == '[object Boolean]';
  125. };
  126. function resolveKey(input){
  127. return input.replace(/(\S)(_([a-zA-Z]))/g, function(match, $1, $2, $3){
  128. return $1 + $3.toUpperCase() || "";
  129. })
  130. }
  131. function camelizeKeys(input, convert){
  132. if(!_isObject(input) || _isDate(input) || _isRegExp(input) || _isBoolean(input) || _isFunction(input)){
  133. return convert ? resolveKey(input) : input;
  134. }
  135. if(_isArray(input)){
  136. var temp = [];
  137. for(var i = 0; i < input.length; i++){
  138. temp.push(camelizeKeys(input[i]));
  139. }
  140. }else {
  141. var temp = {};
  142. for(var prop in input){
  143. if(input.hasOwnProperty(prop)){
  144. temp[camelizeKeys(prop, true)] = camelizeKeys(input[prop]);
  145. }
  146. }
  147. }
  148. return temp;
  149. }
  150. var loadScript = function (url, cb, timeout) {
  151. var script = document.createElement("script");
  152. script.charset = "UTF-8";
  153. script.async = true;
  154. // 对geetest的静态资源添加 crossOrigin
  155. if ( /static\.geetest\.com/g.test(url)) {
  156. script.crossOrigin = "anonymous";
  157. }
  158. script.onerror = function () {
  159. cb(true);
  160. // 错误触发了,超时逻辑就不用了
  161. loaded = true;
  162. };
  163. var loaded = false;
  164. script.onload = script.onreadystatechange = function () {
  165. if (!loaded &&
  166. (!script.readyState ||
  167. "loaded" === script.readyState ||
  168. "complete" === script.readyState)) {
  169. loaded = true;
  170. setTimeout(function () {
  171. cb(false);
  172. }, 0);
  173. }
  174. };
  175. script.src = url;
  176. head.appendChild(script);
  177. setTimeout(function () {
  178. if (!loaded) {
  179. script.onerror = script.onload = null;
  180. script.remove && script.remove();
  181. cb(true);
  182. }
  183. }, timeout || TIMEOUT);
  184. };
  185. var normalizeDomain = function (domain) {
  186. // special domain: uems.sysu.edu.cn/jwxt/geetest/
  187. // return domain.replace(/^https?:\/\/|\/.*$/g, ''); uems.sysu.edu.cn
  188. return domain.replace(/^https?:\/\/|\/$/g, ''); // uems.sysu.edu.cn/jwxt/geetest
  189. };
  190. var normalizePath = function (path) {
  191. path = path.replace(/\/+/g, '/');
  192. if (path.indexOf('/') !== 0) {
  193. path = '/' + path;
  194. }
  195. return path;
  196. };
  197. var normalizeQuery = function (query) {
  198. if (!query) {
  199. return '';
  200. }
  201. var q = '?';
  202. new _Object(query)._each(function (key, value) {
  203. if (isString(value) || isNumber(value) || isBoolean(value)) {
  204. q = q + encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
  205. }
  206. });
  207. if (q === '?') {
  208. q = '';
  209. }
  210. return q.replace(/&$/, '');
  211. };
  212. var makeURL = function (protocol, domain, path, query) {
  213. domain = normalizeDomain(domain);
  214. var url = normalizePath(path) + normalizeQuery(query);
  215. if (domain) {
  216. url = protocol + domain + url;
  217. }
  218. return url;
  219. };
  220. var load = function (config, protocol, domains, path, query, cb, handleCb) {
  221. var tryRequest = function (at) {
  222. // 处理jsonp回调,这里为了保证每个不同jsonp都有唯一的回调函数
  223. if(handleCb){
  224. var cbName = "geetest_" + random();
  225. // 需要与预先定义好cbname参数,删除对象
  226. window[cbName] = bind(handleCb, null, cbName);
  227. query.callback = cbName;
  228. }
  229. var url = makeURL(protocol, domains[at], path, query);
  230. loadScript(url, function (err) {
  231. if (err) {
  232. // 超时或者出错的时候 移除回调
  233. if(cbName){
  234. try {
  235. window[cbName] = function(){
  236. window[cbName] = null;
  237. }
  238. } catch (e) {}
  239. }
  240. if (at >= domains.length - 1) {
  241. cb(true);
  242. // report gettype error
  243. } else {
  244. tryRequest(at + 1);
  245. }
  246. } else {
  247. cb(false);
  248. }
  249. }, config.timeout);
  250. };
  251. tryRequest(0);
  252. };
  253. var jsonp = function (domains, path, config, callback) {
  254. var handleCb = function (cbName, data) {
  255. // 保证只执行一次,全部超时的情况下不会再触发;
  256. if (data.status == 'success') {
  257. callback(data.data);
  258. } else if (!data.status) {
  259. callback(data);
  260. } else {
  261. //接口有返回,但是返回了错误状态,进入报错逻辑
  262. callback(data);
  263. }
  264. window[cbName] = undefined;
  265. try {
  266. delete window[cbName];
  267. } catch (e) {
  268. }
  269. };
  270. load(config, config.protocol, domains, path, {
  271. captcha_id: config.captchaId,
  272. challenge: config.challenge || uuid(),
  273. client_type: MOBILE? 'h5':'web',
  274. risk_type: config.riskType,
  275. user_info: config.userInfo,
  276. call_type: config.callType,
  277. lang: config.language? config.language : navigator.appName === 'Netscape' ? navigator.language.toLowerCase() : navigator.userLanguage.toLowerCase()
  278. }, function (err) {
  279. // 网络问题接口没有返回,直接使用本地验证码,走宕机模式
  280. // 这里可以添加用户的逻辑
  281. if(err && typeof config.offlineCb === 'function'){
  282. // 执行自己的宕机
  283. config.offlineCb();
  284. return;
  285. }
  286. if(err){
  287. callback(config._get_fallback_config());
  288. }
  289. }, handleCb);
  290. };
  291. var reportError = function (config, url) {
  292. load(config, config.protocol, ['monitor.geetest.com'], '/monitor/send', {
  293. time: Date.now().getTime(),
  294. captcha_id: config.gt,
  295. challenge: config.challenge,
  296. exception_url: url,
  297. error_code: config.error_code
  298. }, function (err) {})
  299. }
  300. var throwError = function (errorType, config, errObj) {
  301. var errors = {
  302. networkError: '网络错误',
  303. gtTypeError: 'gt字段不是字符串类型'
  304. };
  305. if (typeof config.onError === 'function') {
  306. config.onError({
  307. desc: errObj.desc,
  308. msg: errObj.msg,
  309. code: errObj.code
  310. });
  311. } else {
  312. throw new Error(errors[errorType]);
  313. }
  314. };
  315. var detect = function () {
  316. return window.Geetest || document.getElementById("gt_lib");
  317. };
  318. if (detect()) {
  319. status.slide = "loaded";
  320. }
  321. var GeetestIsLoad = function (fname) {
  322. var GeetestIsLoad = false;
  323. var tags = { js: 'script', css: 'link' };
  324. var tagname = tags[fname.split('.').pop()];
  325. if (tagname !== undefined) {
  326. var elts = document.getElementsByTagName(tagname);
  327. for (var i in elts) {
  328. if ((elts[i].href && elts[i].href.toString().indexOf(fname) > 0)
  329. || (elts[i].src && elts[i].src.toString().indexOf(fname) > 0)) {
  330. GeetestIsLoad = true;
  331. }
  332. }
  333. }
  334. return GeetestIsLoad;
  335. };
  336. window.initGeetest4 = function (userConfig,callback) {
  337. var config = new Config(userConfig);
  338. if (userConfig.https) {
  339. config.protocol = 'https://';
  340. } else if (!userConfig.protocol) {
  341. config.protocol = window.location.protocol + '//';
  342. }
  343. if (isObject(userConfig.getType)) {
  344. config._extend(userConfig.getType);
  345. }
  346. jsonp(config.apiServers , config.typePath, config, function (newConfig) {
  347. //错误捕获,第一个load请求可能直接报错
  348. var newConfig = camelizeKeys(newConfig);
  349. if(newConfig.status === 'error'){
  350. return throwError('networkError', config, newConfig);
  351. }
  352. var type = newConfig.type;
  353. if(config.debug){
  354. new _Object(newConfig)._extend(config.debug)
  355. }
  356. var init = function () {
  357. config._extend(newConfig);
  358. callback(new window.Geetest4(config));
  359. };
  360. callbacks[type] = callbacks[type] || [];
  361. var s = status[type] || 'init';
  362. if (s === 'init') {
  363. status[type] = 'loading';
  364. callbacks[type].push(init);
  365. if(newConfig.gctPath){
  366. load(config, config.protocol, Object.hasOwnProperty.call(config, 'staticServers') ? config.staticServers : newConfig.staticServers || config.staticServers , newConfig.gctPath, null, function (err){
  367. if(err){
  368. throwError('networkError', config, {
  369. code: '60205',
  370. msg: 'Network failure',
  371. desc: {
  372. detail: 'gct resource load timeout'
  373. }
  374. });
  375. }
  376. })
  377. }
  378. load(config, config.protocol, Object.hasOwnProperty.call(config, 'staticServers') ? config.staticServers : newConfig.staticServers || config.staticServers, newConfig.bypass || (newConfig.staticPath + newConfig.js), null, function (err) {
  379. if (err) {
  380. status[type] = 'fail';
  381. throwError('networkError', config, {
  382. code: '60204',
  383. msg: 'Network failure',
  384. desc: {
  385. detail: 'js resource load timeout'
  386. }
  387. });
  388. } else {
  389. status[type] = 'loaded';
  390. var cbs = callbacks[type];
  391. for (var i = 0, len = cbs.length; i < len; i = i + 1) {
  392. var cb = cbs[i];
  393. if (isFunction(cb)) {
  394. cb();
  395. }
  396. }
  397. callbacks[type] = [];
  398. }
  399. });
  400. } else if (s === "loaded") {
  401. // 判断gct是否需要重新加载
  402. if(!GeetestIsLoad(newConfig.gctPath)){
  403. load(config, config.protocol, Object.hasOwnProperty.call(config, 'staticServers') ? config.staticServers : newConfig.staticServers || config.staticServers , newConfig.gctPath, null, function (err){
  404. if(err){
  405. throwError('networkError', config, {
  406. code: '60205',
  407. msg: 'Network failure',
  408. desc: {
  409. detail: 'gct resource load timeout'
  410. }
  411. });
  412. }
  413. })
  414. }
  415. return init();
  416. } else if (s === "fail") {
  417. throwError('networkError', config, {
  418. code: '60204',
  419. msg: 'Network failure',
  420. desc: {
  421. detail: 'js resource load timeout'
  422. }
  423. });
  424. } else if (s === "loading") {
  425. callbacks[type].push(init);
  426. }
  427. });
  428. };
  429. })(window);