functions.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-9-23
  6. * Time: 上午10:56
  7. */
  8. use App\Exceptions\ExitOutException;
  9. //统一输出格式话的json数据
  10. if (!function_exists('out')) {
  11. function out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  12. {
  13. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  14. if ($exceptionData !== false) {
  15. trace([$message => $exceptionData], 'error');
  16. }
  17. return response()->json($out);
  18. }
  19. }
  20. //统一异常输出格式话的json数据
  21. if (!function_exists('exit_out')) {
  22. function exit_out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  23. {
  24. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  25. if ($exceptionData !== false) {
  26. trace([$message => $exceptionData], 'error');
  27. }
  28. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  29. throw new ExitOutException($json);
  30. }
  31. }
  32. //日志记录
  33. if (!function_exists('trace')) {
  34. function trace($log = '', $level = 'info')
  35. {
  36. Log::log($level, $log);
  37. }
  38. }
  39. //AES加密
  40. if (!function_exists('aes_encrypt')) {
  41. function aes_encrypt($data)
  42. {
  43. if (is_array($data)) {
  44. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  45. }
  46. $key = config('config.aes_key');
  47. $iv = config('config.aes_iv');
  48. $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  49. $cipher_text = base64_encode($cipher_text);
  50. return urlencode($cipher_text);
  51. }
  52. }
  53. //AES解密
  54. if (!function_exists('aes_decrypt')) {
  55. function aes_decrypt($encryptData)
  56. {
  57. $encryptData = urldecode($encryptData);
  58. $encryptData = base64_decode($encryptData);
  59. $key = config('config.aes_key');
  60. $iv = config('config.aes_iv');
  61. $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  62. return json_decode($original_plaintext, true);
  63. }
  64. }
  65. //获取distance的sql字段
  66. if (!function_exists('get_distance_field')) {
  67. function get_distance_field($latitude, $longitude)
  68. {
  69. if (empty($latitude) || empty($longitude)) {
  70. return '999999999 distance';
  71. }
  72. return 'if(longitude=0 and latitude=0,999999999,round(6378.138*2*asin(sqrt(pow(sin( (' . $latitude . '*pi()/180-latitude*pi()/180)/2),2)+cos(' . $latitude . '*pi()/180)*cos(latitude*pi()/180)* pow(sin((' . $longitude . '*pi()/180-longitude*pi()/180)/2),2)))*1000)) distance';
  73. }
  74. }
  75. //获取用户的distance的sql字段
  76. if (!function_exists('get_user_distance_field')) {
  77. function get_user_distance_field($user)
  78. {
  79. $coordinate = get_user_coordinate($user);
  80. $latitude = $coordinate['latitude'];
  81. $longitude = $coordinate['longitude'];
  82. if (empty($latitude) || empty($longitude)) {
  83. return '999999999 distance';
  84. }
  85. return 'if(longitude=0 and latitude=0,999999999,round(6378.138*2*asin(sqrt(pow(sin( (' . $latitude . '*pi()/180-latitude*pi()/180)/2),2)+cos(' . $latitude . '*pi()/180)*cos(latitude*pi()/180)* pow(sin((' . $longitude . '*pi()/180-longitude*pi()/180)/2),2)))*1000)) distance';
  86. }
  87. }
  88. //构建单号
  89. if (!function_exists('build_sn')) {
  90. function build_sn($id, $len = 2, $prefix = '')
  91. {
  92. $idx = 0 - $len;
  93. $suffix = substr($id, $idx);
  94. $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
  95. $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
  96. return $sn;
  97. }
  98. }
  99. //生日转年龄
  100. if (!function_exists('birthday_to_age')){
  101. function birthday_to_age($birthday)
  102. {
  103. list($year, $month, $day) = explode("-", $birthday);
  104. $year_diff = (date("Y") - $year) > 0 ? date("Y") - $year.'岁':'';
  105. $month_diff = (date("m") - $month) > 0 ? date("m") - $month.'个月':'';
  106. $day_diff = (date("d") - $day) > 0 ? date("d") - $day.'天':'';
  107. if ($day_diff < 0 || $month_diff < 0) {
  108. $year_diff--;
  109. }
  110. return $year_diff.$month_diff.$day_diff ;
  111. }
  112. }
  113. //计算经纬度两点之间距离(返回为米)
  114. if (!function_exists('get_distance')) {
  115. function get_distance($lat1, $lng1, $lat2, $lng2)
  116. {
  117. if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
  118. return '999999999';
  119. }
  120. $earthRadius = 6378138;
  121. $lat1 = ($lat1 * pi()) / 180;
  122. $lng1 = ($lng1 * pi()) / 180;
  123. $lat2 = ($lat2 * pi()) / 180;
  124. $lng2 = ($lng2 * pi()) / 180;
  125. $calcLongitude = $lng2 - $lng1;
  126. $calcLatitude = $lat2 - $lat1;
  127. $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  128. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  129. $calculatedDistance = $earthRadius * $stepTwo;
  130. return number_format($calculatedDistance, 2, '.', '');
  131. }
  132. }
  133. //获取用户坐标
  134. if (!function_exists('get_user_coordinate')) {
  135. function get_user_coordinate($user)
  136. {
  137. $req = request()->post();
  138. if (empty($req['latitude']) || empty($req['longitude'])) {
  139. $latitude = $user['latitude'] ?? 0;
  140. $longitude = $user['longitude'] ?? 0;
  141. }
  142. else {
  143. $latitude = $req['latitude'];
  144. $longitude = $req['longitude'];
  145. }
  146. return ['latitude' => $latitude, 'longitude' => $longitude];
  147. }
  148. }
  149. //获取用户距离
  150. if (!function_exists('get_user_distance')) {
  151. function get_user_distance($user, $lat, $lng)
  152. {
  153. $coordinate = get_user_coordinate($user);
  154. $data = get_distance($coordinate['latitude'], $coordinate['longitude'], $lat, $lng);
  155. return $data;
  156. }
  157. }
  158. //发送短信
  159. if (!function_exists('send_sms')) {
  160. function send_sms($phone, $templateKey, $templateParam = [])
  161. {
  162. $sms_config = config('config.aly_sms');
  163. //是否启用https
  164. $security = false;
  165. $params = [];
  166. $params["PhoneNumbers"] = $phone;
  167. $params["SignName"] = $sms_config['sign_name'];
  168. $params["TemplateCode"] = $sms_config[$templateKey];
  169. $params['TemplateParam'] = $templateParam;
  170. if (is_array($params["TemplateParam"])) {
  171. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  172. }
  173. $content = aly_sm_request(
  174. $sms_config['access_key'],
  175. $sms_config['access_secret'],
  176. "dysmsapi.aliyuncs.com",
  177. array_merge($params, array(
  178. "RegionId" => "cn-hangzhou",
  179. "Action" => "SendSms",
  180. "Version" => "2017-05-25",
  181. )),
  182. $security
  183. );
  184. return $content;
  185. }
  186. }
  187. if (!function_exists('aly_sm_request')) {
  188. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  189. {
  190. $apiParams = array_merge(array(
  191. "SignatureMethod" => "HMAC-SHA1",
  192. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  193. "SignatureVersion" => "1.0",
  194. "AccessKeyId" => $accessKeyId,
  195. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  196. "Format" => "JSON",
  197. ), $params);
  198. ksort($apiParams);
  199. $sortedQueryStringTmp = "";
  200. foreach ($apiParams as $key => $value) {
  201. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  202. }
  203. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  204. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  205. $signature = aly_sms_encode($sign);
  206. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  207. try {
  208. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  209. return json_decode($content);
  210. } catch (Exception $e) {
  211. return false;
  212. }
  213. }
  214. }
  215. if (!function_exists('aly_sms_encode')) {
  216. function aly_sms_encode($str)
  217. {
  218. $res = urlencode($str);
  219. $res = preg_replace("/\+/", "%20", $res);
  220. $res = preg_replace("/\*/", "%2A", $res);
  221. $res = preg_replace("/%7E/", "~", $res);
  222. return $res;
  223. }
  224. }
  225. if (!function_exists('aly_sms_fetch_content')) {
  226. function aly_sms_fetch_content($url, $method, $body)
  227. {
  228. $ch = curl_init();
  229. if ($method == 'POST') {
  230. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  231. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  232. } else {
  233. $url .= '?' . $body;
  234. }
  235. curl_setopt($ch, CURLOPT_URL, $url);
  236. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  237. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  238. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  239. "x-sdk-client" => "php/2.0.0"
  240. ));
  241. if (substr($url, 0, 5) == 'https') {
  242. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  243. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  244. }
  245. $rtn = curl_exec($ch);
  246. if ($rtn === false) {
  247. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  248. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  249. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  250. }
  251. curl_close($ch);
  252. return $rtn;
  253. }
  254. }
  255. //检测重复请求 超过就禁止访问 有用户flag就针对用户flag 没有flag就针对ip地址(ip的话注意反代情况,可能每个用户请求的ip都是反代服务器的ip,当然可以配置一波反代服务器使得业务服务器获取到真实用户ip) 最小只能设置1s一次请求 不支持1s以下 如果开启了redis可以改写支持毫秒级的方法
  256. if (!function_exists('check_repeat_request')) {
  257. function check_repeat_request($time, $limit, $flag = '')
  258. {
  259. $action = request()->getPathInfo();
  260. if (!empty($flag)){
  261. $key = $action.$flag;
  262. }
  263. else {
  264. $ip = request()->ip();
  265. $key = $action.$ip;
  266. }
  267. $time = $time < 1 ? 1 : $time;
  268. $time = round($time);
  269. if (Cache::has($key)){
  270. Cache::increment($key);
  271. $count = Cache::get($key);
  272. if($count > $limit){
  273. exit_out(null, 11003, '操作过于频繁,请稍后重试~');
  274. }
  275. }
  276. else {
  277. Cache::set($key, 1, $time);
  278. }
  279. return true;
  280. }
  281. }
  282. //随机生成验证码
  283. if (!function_exists('generate_code')) {
  284. function generate_code($length = 6)
  285. {
  286. $min = pow(10, ($length - 1));
  287. $max = pow(10, $length) - 1;
  288. return rand($min, $max);
  289. }
  290. }