common.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. use app\common\model\Setting;
  3. use think\Env;
  4. /**
  5. * 获取响应数据
  6. *
  7. * @param string $url 请求地址
  8. * @param mixed $param 请求参数
  9. * @param string $method 请求方式
  10. * @param array $httpHeader 需要更改的表头协议
  11. * @return string
  12. */
  13. function get_http_response($url, $param, $method='post', $httpHeader='') {
  14. $ch = curl_init();
  15. if ( 'get' == $method ) {
  16. curl_setopt($ch, CURLOPT_URL, "{$url}?{$param}");
  17. } else {
  18. curl_setopt($ch, CURLOPT_URL, $url);
  19. curl_setopt($ch, CURLOPT_POST, 1);
  20. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
  21. }
  22. if (strstr($url, 'https')){
  23. //https必须要跳过证书检查才能正常请求
  24. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //这个是重点,规避ssl的证书检查。
  25. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过host验证
  26. }
  27. if (!empty($httpHeader)){
  28. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
  29. }
  30. curl_setopt($ch, CURLOPT_HEADER, false);
  31. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  32. // 超时设置
  33. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  34. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  35. $responseText = curl_exec($ch);
  36. curl_close($ch);
  37. $logMsg = '请求接口连接:' . $url;
  38. $logMsg .= ', 请求参数:' . json_encode($param);
  39. $logMsg .= ', 响应结果:' . $responseText;
  40. //writeLogToElk($logMsg);
  41. // log_message($logMsg,'log',LOG_PATH . 'complexLoginlog/');
  42. trace('请求: ' . $logMsg, 'api/common@get_http_response.result');
  43. return trim($responseText);
  44. }
  45. /**
  46. * 获取游戏指定的用户名连接符
  47. *
  48. * @param int $gameid 游戏ID
  49. * @return string
  50. */
  51. function get_username_connector($gameid) {
  52. $specify = ['116','173','201'];
  53. if ( in_array($gameid, $specify) ) {
  54. return '#';
  55. } else {
  56. return '___';
  57. }
  58. }
  59. /**
  60. * 根据身份证判断,是否满足年龄条件
  61. * @param type $IDCard 身份证
  62. * @param type $minAge 最小年龄
  63. * @param type $minAge 最大年龄
  64. */
  65. function isMeetAgeByIDCard($IDCard, $minAge,$maxAge) {
  66. if (strlen($IDCard) <= 15) {
  67. $IDCard = convertIDCard15to18($IDCard);
  68. }
  69. $year = date('Y') - substr($IDCard, 6, 4);
  70. $monthDay = date('md') - substr($IDCard, 10, 4);
  71. // 验证最小年龄
  72. if ($year < $minAge || $year == $minAge && $monthDay <= 0) {
  73. return false;
  74. }
  75. // 验证最大年龄
  76. if ($year > $maxAge || $year == $maxAge && $monthDay > 0) {
  77. return false;
  78. }
  79. return true;
  80. }
  81. // 将15位身份证升级到18位
  82. function convertIDCard15to18($IDCard) {
  83. if (strlen($IDCard) != 15) {
  84. return false;
  85. } else {
  86. // 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
  87. if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {
  88. $IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);
  89. } else {
  90. $IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);
  91. }
  92. }
  93. $IDCard = $IDCard . calcIDCardCode($IDCard);
  94. return $IDCard;
  95. }
  96. //计算身份证的最后一位验证码,根据国家标准GB 11643-1999
  97. function calcIDCardCode($IDCardBody) {
  98. if (strlen($IDCardBody) != 17) {
  99. return false;
  100. }
  101. //加权因子
  102. $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  103. //校验码对应值
  104. $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  105. $checksum = 0;
  106. for ($i = 0; $i < strlen($IDCardBody); $i++) {
  107. $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
  108. }
  109. return $code[$checksum % 11];
  110. }
  111. // 代替each函数
  112. function fun_adm_each(&$array)
  113. {
  114. $res = array();
  115. $key = key($array);
  116. if ($key !== null) {
  117. next($array);
  118. $res[1] = $res['value'] = $array[$key];
  119. $res[0] = $res['key'] = $key;
  120. } else {
  121. $res = false;
  122. }
  123. return $res;
  124. }
  125. /**
  126. * 通用化API数据格式输出
  127. * @param $status
  128. * @param string $message
  129. * @param array $data
  130. * @param int $httpStatus
  131. * @return \think\response\Json
  132. */
  133. function resultJson($status, $message = "error", $data = [], $httpStatus = 200)
  134. {
  135. $result = [
  136. "status" => $status,
  137. "message" => $message,
  138. "data" => $data
  139. ];
  140. return json($result, $httpStatus);
  141. }
  142. // 加密
  143. // $a = strEncrypt("13","Su)sjKsu23G0slow");
  144. function strEncrypt($bytes, $key)
  145. {
  146. $encrypted = openssl_encrypt($bytes, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key); // 加密
  147. return bin2hex($encrypted);
  148. }
  149. // 解密
  150. // $b = hex2bin($a);
  151. // var_dump(str_decrypt($b,"Su)sjKsu23G0slow"));
  152. function str_decrypt($encrypted, $key)
  153. {
  154. $decrypted = openssl_decrypt($encrypted, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $key);
  155. if ($decrypted === false) {
  156. return "";
  157. }
  158. return $decrypted;
  159. }
  160. function strDecrypt($encrypted, $key)
  161. {
  162. $decrypted = openssl_decrypt(hex2bin($encrypted),'aes-128-cbc',$key,OPENSSL_RAW_DATA,$key);
  163. if ($decrypted === false) {
  164. return "";
  165. }
  166. return $decrypted;
  167. }
  168. function pkcs5UnPadding($origData)
  169. {
  170. $length = strlen($origData);
  171. $unpadding = ord($origData[$length - 1]);
  172. return substr($origData, 0, $length - $unpadding);
  173. }
  174. function pkcs5_padding($ciphertext, $blockSize)
  175. {
  176. $padding = $blockSize - (strlen($ciphertext) % $blockSize);
  177. $padtext = str_repeat(chr($padding), $padding);
  178. return $ciphertext . $padtext;
  179. }
  180. /**
  181. * 修复指定游戏的区服ID问题
  182. * @param string $gameid 游戏ID
  183. * @param string $serverid 区服ID
  184. *
  185. * @return string
  186. */
  187. function repairRoleServerid($gameid, $serverid)
  188. {
  189. if(APP_STATUS == 'stable'){
  190. if (in_array($gameid, ['266', '259'])) {
  191. if(mb_strlen($serverid) < 10){
  192. $serverid = str_pad($serverid+10010000, 10, "0", STR_PAD_LEFT);
  193. }
  194. }
  195. }else if(APP_STATUS == 'dev'){
  196. if (in_array($gameid, ['266', '259'])) {
  197. if(mb_strlen($serverid) < 10){
  198. $serverid = str_pad($serverid+10010000, 10, "0", STR_PAD_LEFT);
  199. }
  200. }
  201. }
  202. return $serverid;
  203. }
  204. /**
  205. * 随机获取一个支付方式
  206. *
  207. * @param $paymentTypes
  208. *
  209. * @return false|mixed
  210. */
  211. function getRandomPaymentType($paymentTypes)
  212. {
  213. // 计算所有概率的总和
  214. $totalProbability = array_sum(array_column($paymentTypes, 'probability'));
  215. if ($totalProbability == 0) {
  216. return [];
  217. // throw new Exception("所有的概率值都为0,无法进行随机选择。");
  218. }
  219. // 生成一个 0 到 1 之间的随机数
  220. $rand = mt_rand() / mt_getrandmax();
  221. $cumulativeProbability = 0.0;
  222. foreach ($paymentTypes as $paymentType) {
  223. // 归一化概率
  224. $normalizedProbability = $paymentType['probability'] / $totalProbability;
  225. $cumulativeProbability += $normalizedProbability;
  226. if ($rand <= $cumulativeProbability) {
  227. return $paymentType;
  228. }
  229. }
  230. // 如果没有匹配项,返回最后一个(理论上不应该发生)
  231. return end($paymentTypes);
  232. }
  233. /**
  234. * 注册管控
  235. * 每个月,同一个设备号注册上限三个,同一个IP注册上限五个。
  236. *
  237. * @param string $ip 访问的IP地址
  238. * @param string $imeil 访问的Imeil标识
  239. *
  240. * @return bool true:允许访问 false:超出频率限制
  241. */
  242. function regidterHandle($ip, $imeil){
  243. try {
  244. $redis = think\Cache::store('default')->handler();
  245. $monthKey = date('Y-m', time());
  246. $ipKey = "register:ip_limit:{$monthKey}_{$ip}";
  247. $imeilKey = "register:imeil_limit:{$monthKey}_{$imeil}";
  248. $ipLimit = (new Setting())->getSetting('register_month_ip_limit');
  249. $imeilLimit = (new Setting())->getSetting('register_month_imeil_limit');
  250. $expireTime = strtotime(date('Y-m-t 23:59:59')) - time();
  251. $redis->multi();
  252. $redis->incr($ipKey, 1);
  253. $redis->expire($ipKey, $expireTime);
  254. $redis->incr($imeilKey, 1);
  255. $redis->expire($imeilKey, $expireTime);
  256. $results = $redis->exec();
  257. $ipCount = $results[0];
  258. $imeilCount = $results[2];
  259. // trace("# regidterHandle: {$ipLimit}, {$imeilLimit} -- {$ipCount}, {$imeilCount}", 'error');
  260. // 检查是否超出限制
  261. if($ipCount > $ipLimit || $imeilCount > $imeilLimit) {
  262. return false;
  263. }
  264. return true;
  265. } catch (\Exception $e) {
  266. trace('# 注册管控异常: ' . $e->getMessage(), 'error');
  267. // TODO: 钉钉异常通知
  268. }
  269. return false;
  270. }
  271. /**
  272. * 请求频率管控
  273. *
  274. * @param string $userName 玩家用户名
  275. * @param string $route 请求路由(例如:v1.login/index)
  276. *
  277. * @return bool true:允许访问 false:超出频率限制
  278. */
  279. function requestFrequencyHandle($userName, $route){
  280. try {
  281. $count = Env::get('REQUEST_FREQUENCY_COUNT', 3); // 请求次数
  282. $time = Env::get('REQUEST_FREQUENCY_TIME', 60); // 请求间隔时间(秒)
  283. $redis = think\Cache::store('default')->handler();
  284. $key = "request:frequency:{$userName}:{$route}";
  285. $currentCount = $redis->get($key);
  286. if ($currentCount === false) {
  287. $redis->setex($key, $time, 1);
  288. return true;
  289. }
  290. if ($currentCount < $count) {
  291. $redis->incr($key);
  292. return true;
  293. }
  294. return false;
  295. } catch (\Exception $e) {
  296. trace('# 请求频率管控异常: ' . $e->getMessage(), 'error');
  297. // TODO:钉钉异常通知
  298. }
  299. return true;
  300. }
  301. /**
  302. * 判断数组中是否包含数组中键
  303. *
  304. * @param array $data 数据数组
  305. * @param array $requiredKeys 需要判断的键数组
  306. *
  307. * @return array
  308. */
  309. function checkDataHasKeys(array $data, array $requiredKeys) {
  310. $missing = [];
  311. foreach ($requiredKeys as $key) {
  312. $keys = explode('.', $key);
  313. $temp = $data;
  314. foreach ($keys as $k) {
  315. if (!isset($temp[$k])) {
  316. $missing[] = $key;
  317. break;
  318. }
  319. $temp = $temp[$k];
  320. }
  321. }
  322. return $missing;
  323. }
  324. /**
  325. * 判断数组A是否包含数组B中的所有键
  326. *
  327. * @param array $arrayA
  328. * @param array $keysB
  329. *
  330. * @return bool
  331. */
  332. function hasAllKeys(array $arrayA, array $keysB): bool
  333. {
  334. foreach ($keysB as $key) {
  335. if (!array_key_exists($key, $arrayA)) {
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. /**
  342. * 是否虚拟号判断
  343. *
  344. * @param $mobile 需要判断的手机号
  345. *
  346. * | 号段 | 运营商 | 备注 |
  347. * | ----------------------- | ----------- | ---------------------- |
  348. * | 1700/1701/1702 | 中国电信虚拟运营商 | 归属电信网络 |
  349. * | 1703/1705/1706 | 中国移动虚拟运营商 | 归属移动网络 |
  350. * | 1704/1707/1708/1709 | 中国联通虚拟运营商 | 归属联通网络 |
  351. * | 171 | 联通专属虚拟运营商号段 | 常见于阿里通信、京东通信等 |
  352. * | 162 | 用于物联网和行业专用 | 虚拟运营商/物联网号段(部分归联通) |
  353. * | 165 | 联通新型虚拟号段 | 多用于物联网、政企服务 |
  354. * | 167 | 移动新型虚拟号段 | 多为企业服务、物联网 |
  355. * | 140/141/144/146/148 | 物联网卡号段 | 用于工业/车联网设备等(注意:这不是通话号) |
  356. *
  357. * @return false|int
  358. */
  359. function isVirtualMobile($mobile) {
  360. // 清洗手机号
  361. $mobile = preg_replace('/\D/', '', $mobile);
  362. // 匹配虚拟号段
  363. return preg_match('/^1(70\d|71\d|65\d|67\d)\d{7}$/', $mobile);
  364. }
  365. /**
  366. * base64封装
  367. * @param $str string 需要加密或解密的字符串
  368. * @param $type string 加密或解密类型,'encode' 为加密,'decode' 为解密
  369. * @param $salt string 加密或解密的盐值,必须与加密和解密时保持一致
  370. *
  371. * @return false|string
  372. */
  373. function base64_salt($str, $type = 'encode', $salt = 'qmsdk') {
  374. if ($type === 'encode') {
  375. return base64_encode($str . $salt);
  376. } else {
  377. $decoded = base64_decode($str);
  378. return substr($decoded, 0, -strlen($salt));
  379. }
  380. }