functions.php 11 KB

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