functions.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-9-23
  6. * Time: 上午10:56
  7. */
  8. use EasyWeChat\Factory;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Exceptions\ExitOutException;
  11. use App\Models\SystemConfig;
  12. use App\Models\TimePeriod;
  13. use App\Models\DocterOrganization;
  14. use App\Models\Organization;
  15. //统一输出格式话的json数据
  16. if (!function_exists('out')) {
  17. function out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  18. {
  19. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  20. if ($exceptionData !== false) {
  21. trace([$message => $exceptionData], 'error');
  22. }
  23. return response()->json($out);
  24. }
  25. }
  26. //统一异常输出格式话的json数据
  27. if (!function_exists('exit_out')) {
  28. function exit_out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  29. {
  30. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  31. if ($exceptionData !== false) {
  32. trace([$message => $exceptionData], 'error');
  33. }
  34. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  35. throw new ExitOutException($json);
  36. }
  37. }
  38. //日志记录
  39. if (!function_exists('trace')) {
  40. function trace($log = '', $level = 'info')
  41. {
  42. Log::log($level, $log);
  43. }
  44. }
  45. if (!function_exists('upDecimal')) {
  46. /**
  47. * 对价格进行向上取整
  48. * @param $price 价格
  49. * @param $decimal 保留小数位数
  50. */
  51. function upDecimal($price, $decimal = 2){
  52. $data1 = pow(10, $decimal);
  53. $data2 = ceil(bcmul($price, $data1,10));
  54. $data3 = bcdiv($data2, $data1, $decimal);
  55. return $data3;
  56. }
  57. }
  58. //AES加密
  59. if (!function_exists('aes_encrypt')) {
  60. function aes_encrypt($data)
  61. {
  62. if (is_array($data)) {
  63. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  64. }
  65. $key = config('config.aes_key');
  66. $iv = config('config.aes_iv');
  67. $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  68. $cipher_text = base64_encode($cipher_text);
  69. return urlencode($cipher_text);
  70. }
  71. }
  72. //AES解密
  73. if (!function_exists('aes_decrypt')) {
  74. function aes_decrypt($encryptData)
  75. {
  76. $encryptData = urldecode($encryptData);
  77. $encryptData = base64_decode($encryptData);
  78. $key = config('config.aes_key');
  79. $iv = config('config.aes_iv');
  80. $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  81. return json_decode($original_plaintext, true);
  82. }
  83. }
  84. //获取distance的sql字段
  85. if (!function_exists('get_distance_field')) {
  86. function get_distance_field($latitude, $longitude)
  87. {
  88. if (empty($latitude) || empty($longitude)) {
  89. return '未知 distance';
  90. }
  91. return 'if(longitude=0 and latitude=0,未知,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';
  92. }
  93. }
  94. //获取用户的distance的sql字段
  95. if (!function_exists('get_user_distance_field')) {
  96. function get_user_distance_field($user)
  97. {
  98. $coordinate = get_user_coordinate($user);
  99. $latitude = $coordinate['latitude'];
  100. $longitude = $coordinate['longitude'];
  101. if (empty($latitude) || empty($longitude)) {
  102. return '"未知" distance';
  103. }
  104. return 'if(longitude=0 and latitude=0,"未知",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';
  105. }
  106. }
  107. //构建单号
  108. if (!function_exists('build_sn')) {
  109. function build_sn($id, $len = 2, $prefix = '')
  110. {
  111. $idx = 0 - $len;
  112. $suffix = substr($id, $idx);
  113. $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
  114. $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
  115. return $sn;
  116. }
  117. }
  118. //生日转年龄
  119. if (!function_exists('birthday_to_age')){
  120. function birthday_to_age($birthday)
  121. {
  122. if($birthday==null)
  123. {
  124. return "0岁";
  125. }
  126. list($year, $month, $day) = explode("-", $birthday);
  127. $year_diff = (date("Y") - $year) > 0 ? date("Y") - $year.'岁':'';
  128. $month_diff = (date("m") - $month) > 0 ? date("m") - $month.'个月':'';
  129. $day_diff = (date("d") - $day) > 0 ? date("d") - $day.'天':'';
  130. if ($day_diff < 0 || $month_diff < 0) {
  131. $year_diff--;
  132. }
  133. return $year_diff.$month_diff.$day_diff ;
  134. }
  135. }
  136. //计算经纬度两点之间距离(返回为米)
  137. if (!function_exists('get_distance')) {
  138. function get_distance($lat1, $lng1, $lat2, $lng2)
  139. {
  140. if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
  141. return '未知';
  142. }
  143. $earthRadius = 6378138;
  144. $lat1 = ($lat1 * pi()) / 180;
  145. $lng1 = ($lng1 * pi()) / 180;
  146. $lat2 = ($lat2 * pi()) / 180;
  147. $lng2 = ($lng2 * pi()) / 180;
  148. $calcLongitude = $lng2 - $lng1;
  149. $calcLatitude = $lat2 - $lat1;
  150. $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  151. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  152. $calculatedDistance = $earthRadius * $stepTwo;
  153. return number_format($calculatedDistance, 2, '.', '');
  154. }
  155. }
  156. //获取用户坐标
  157. if (!function_exists('get_user_coordinate')) {
  158. function get_user_coordinate($user)
  159. {
  160. $req = request()->post();
  161. if (empty($req['latitude']) || empty($req['longitude'])) {
  162. $latitude = $user['latitude'] ?? 0;
  163. $longitude = $user['longitude'] ?? 0;
  164. }
  165. else {
  166. $latitude = $req['latitude'];
  167. $longitude = $req['longitude'];
  168. }
  169. return ['latitude' => $latitude, 'longitude' => $longitude];
  170. }
  171. }
  172. //获取用户距离
  173. if (!function_exists('get_user_distance')) {
  174. function get_user_distance($user, $lat, $lng)
  175. {
  176. $coordinate = get_user_coordinate($user);
  177. $data = get_distance($coordinate['latitude'], $coordinate['longitude'], $lat, $lng);
  178. return $data;
  179. }
  180. }
  181. if (!function_exists('numBirthday')){
  182. /**
  183. * 生日转年龄
  184. * @author Yuanhang Liu & Xiaoyun Liu
  185. * @param $birthday 2020-10-14 00:48
  186. * @return string
  187. */
  188. function numBirthday($birthday){
  189. if ($birthday){
  190. try {
  191. list($year,$month,$day) = explode("-",$birthday);
  192. $year_diff = (date("Y") - $year)>0?date("Y") - $year.'岁':'';
  193. $month_diff = (date("m") - $month)>0?date("m") - $month.'个月':'';
  194. $day_diff = (date("d") - $day)>0?date("d") - $day.'天':'';
  195. if ($day_diff < 0 || $month_diff < 0)
  196. $year_diff--;
  197. return $year_diff.$month_diff.$day_diff ;
  198. }catch (Exception $e){
  199. return '';
  200. }
  201. }else{
  202. return '';
  203. }
  204. }
  205. }
  206. if (!function_exists('getWeek')){
  207. /**
  208. * 获取当日周几
  209. * @author Yuanhang Liu & Xiaoyun Liu
  210. * @param $birthday 2020-10-14 00:48
  211. * @return string
  212. */
  213. function getWeek($date){
  214. $weekarray=array("周日","周一","周二","周三","周四","周五","周六");
  215. $weekday['week'] = $weekarray[date("w",strtotime($date))];
  216. $weekday['flag'] = date("w",strtotime($date));
  217. return $weekday ;
  218. }
  219. }
  220. //发送短信
  221. if (!function_exists('send_sms')) {
  222. function send_sms($phone, $templateKey, $templateParam = [])
  223. {
  224. $sms_config = config('config.aly_sms');
  225. //是否启用https
  226. $security = false;
  227. $params = [];
  228. $params["PhoneNumbers"] = $phone;
  229. $params["SignName"] = $sms_config['sign_name'];
  230. $params["TemplateCode"] = $sms_config[$templateKey];
  231. $params['TemplateParam'] = $templateParam;
  232. if (is_array($params["TemplateParam"])) {
  233. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  234. }
  235. $content = aly_sm_request(
  236. $sms_config['access_key'],
  237. $sms_config['access_secret'],
  238. "dysmsapi.aliyuncs.com",
  239. array_merge($params, array(
  240. "RegionId" => "cn-hangzhou",
  241. "Action" => "SendSms",
  242. "Version" => "2017-05-25",
  243. )),
  244. $security
  245. );
  246. return $content;
  247. }
  248. }
  249. if (!function_exists('aly_sm_request')) {
  250. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  251. {
  252. $apiParams = array_merge(array(
  253. "SignatureMethod" => "HMAC-SHA1",
  254. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  255. "SignatureVersion" => "1.0",
  256. "AccessKeyId" => $accessKeyId,
  257. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  258. "Format" => "JSON",
  259. ), $params);
  260. ksort($apiParams);
  261. $sortedQueryStringTmp = "";
  262. foreach ($apiParams as $key => $value) {
  263. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  264. }
  265. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  266. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  267. $signature = aly_sms_encode($sign);
  268. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  269. try {
  270. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  271. return json_decode($content, true);
  272. } catch (Exception $e) {
  273. return false;
  274. }
  275. }
  276. }
  277. if (!function_exists('aly_sms_encode')) {
  278. function aly_sms_encode($str)
  279. {
  280. $res = urlencode($str);
  281. $res = preg_replace("/\+/", "%20", $res);
  282. $res = preg_replace("/\*/", "%2A", $res);
  283. $res = preg_replace("/%7E/", "~", $res);
  284. return $res;
  285. }
  286. }
  287. if (!function_exists('aly_sms_fetch_content')) {
  288. function aly_sms_fetch_content($url, $method, $body)
  289. {
  290. $ch = curl_init();
  291. if ($method == 'POST') {
  292. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  293. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  294. } else {
  295. $url .= '?' . $body;
  296. }
  297. curl_setopt($ch, CURLOPT_URL, $url);
  298. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  299. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  300. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  301. "x-sdk-client" => "php/2.0.0"
  302. ));
  303. if (substr($url, 0, 5) == 'https') {
  304. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  305. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  306. }
  307. $rtn = curl_exec($ch);
  308. if ($rtn === false) {
  309. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  310. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  311. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  312. }
  313. curl_close($ch);
  314. return $rtn;
  315. }
  316. }
  317. if (!function_exists('getDateFromList')) {
  318. /**
  319. * 获取指定日期段内每一天的日期
  320. * @param Date $startdate 开始日期
  321. * @param Date $enddate 结束日期
  322. * @return Array
  323. */
  324. function getDateFromList($start,$end){
  325. $stimestamp = strtotime($start);
  326. $etimestamp = strtotime($end);
  327. // 计算日期段内有多少天
  328. $days = ($etimestamp-$stimestamp)/86400+1;
  329. // 保存每天日期
  330. $arr = [];
  331. for($i=0;$i<$days;$i++){
  332. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  333. }
  334. return $arr;
  335. }
  336. }
  337. if (!function_exists('numDays')){
  338. /**
  339. * 计算日期到现在多天天
  340. * @param $date
  341. * @return float
  342. */
  343. function numDays($date){
  344. $Date_List_a1=explode("-",date('Y-m-d',time()));
  345. $Date_List_a2=explode("-",$date);
  346. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  347. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  348. $Days=round(($d1-$d2)/3600/24);
  349. return $Days;
  350. }
  351. }
  352. //检测重复请求 超过就禁止访问 有用户flag就针对用户flag 没有flag就针对ip地址(ip的话注意反代情况,可能每个用户请求的ip都是反代服务器的ip,当然可以配置一波反代服务器使得业务服务器获取到真实用户ip) 最小只能设置1s一次请求 不支持1s以下 如果开启了redis可以改写支持毫秒级的方法
  353. if (!function_exists('check_repeat_request')) {
  354. function check_repeat_request($time, $limit, $flag = '')
  355. {
  356. $action = request()->getPathInfo();
  357. if (!empty($flag)){
  358. $key = $action.$flag;
  359. }
  360. else {
  361. $ip = request()->ip();
  362. $key = $action.$ip;
  363. }
  364. $time = $time < 1 ? 1 : $time;
  365. $time = round($time);
  366. if (Cache::has($key)){
  367. Cache::increment($key);
  368. $count = Cache::get($key);
  369. if($count > $limit){
  370. exit_out(null, 11003, '操作过于频繁,请稍后重试~');
  371. }
  372. }
  373. else {
  374. Cache::set($key, 1, $time);
  375. }
  376. return true;
  377. }
  378. }
  379. //随机生成验证码
  380. if (!function_exists('generate_code')) {
  381. function generate_code($length = 6)
  382. {
  383. $min = pow(10, ($length - 1));
  384. $max = pow(10, $length) - 1;
  385. return rand($min, $max);
  386. }
  387. }
  388. if (!function_exists('object_array')) {
  389. function object_array($array) {
  390. if(is_object($array)) {
  391. $array = (array)$array;
  392. }
  393. if(is_array($array)) {
  394. foreach($array as $key=>$value) {
  395. $array[$key] = object_array($value);
  396. }
  397. }
  398. return $array;
  399. }
  400. }
  401. if (!function_exists('sechedule_timeperiod')) {
  402. function sechedule_timeperiod()
  403. {
  404. $schedule_config = SystemConfig::get('docter_config');
  405. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['morning_start'])->where('end_time_period','<=',$schedule_config['morning_end'])->pluck('id')->toArray();
  406. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['afternoon_start'])->where('end_time_period','<=',$schedule_config['afternoon_end'])->pluck('id')->toArray();
  407. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['evening_start'])->where('end_time_period','<=',$schedule_config['evening_end'])->pluck('id')->toArray();
  408. return $times;
  409. }
  410. }
  411. if (!function_exists('apiReturn')) {
  412. function apiReturn($code,$msg ='', $data ='') {
  413. return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);
  414. }
  415. }
  416. if (!function_exists('getDateFromList')) {
  417. /**
  418. * 获取指定日期段内每一天的日期
  419. * @param Date $startdate 开始日期
  420. * @param Date $enddate 结束日期
  421. * @return Array
  422. */
  423. function getDateFromList($start,$end){
  424. $stimestamp = strtotime($start);
  425. $etimestamp = strtotime($end);
  426. // 计算日期段内有多少天
  427. $days = ($etimestamp-$stimestamp)/86400+1;
  428. // 保存每天日期
  429. $arr = [];
  430. for($i=0;$i<$days;$i++){
  431. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  432. }
  433. return $arr;
  434. }
  435. }
  436. if (!function_exists('numDays')){
  437. /**
  438. * 计算日期到现在多天天
  439. * @param $date
  440. * @return float
  441. */
  442. function numDays($date){
  443. $Date_List_a1=explode("-",date('Y-m-d',time()));
  444. $Date_List_a2=explode("-",$date);
  445. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  446. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  447. $Days=round(($d1-$d2)/3600/24);
  448. return $Days;
  449. }
  450. }
  451. //发送微信消息
  452. if (!function_exists('send_wechat_message')) {
  453. function send_wechat_message($type, $official_arr, $subscribe_arr = [])
  454. {
  455. try {
  456. $app = Factory::miniProgram(config('config.wechat_small_program'));
  457. //先发送模板消息
  458. $data = config('config.wechat_official_message_template')[$type];
  459. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  460. $json = vsprintf($json, $official_arr);
  461. $data = json_decode($json, true);
  462. $ret = $app->uniform_message->send($data);
  463. if (empty($subscribe_arr) && (!isset($ret['errcode']) || $ret['errcode'] != 0)) {
  464. trace(['发送微信模板消息失败,请求参数' => $data, '返回数据' => $ret], 'error');
  465. }
  466. //如果模板消息发送失败(可能因用户没有关注公众号而失败)再发送订阅消息
  467. if (!empty($subscribe_arr) && isset($ret['errcode']) && $ret['errcode'] != 0) {
  468. $data = config('config.wechat_subscribe_message_template')[$type];
  469. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  470. $json = vsprintf($json, $subscribe_arr);
  471. $data = json_decode($json, true);
  472. $ret = $app->subscribe_message->send($data);
  473. if (isset($ret['errcode']) && $ret['errcode'] != 0) {
  474. trace(['发送微信订阅消息失败,请求参数' => $data ?? '', '返回数据' => $ret ?? ''], 'error');
  475. }
  476. }
  477. } catch (Exception $e) {
  478. trace(['发送微信消息失败' => $e->getMessage(), '请求参数' => $data ?? '', '返回数据' => $ret ?? ''], 'error');
  479. }
  480. return $ret ?? false;
  481. }
  482. }
  483. //发送微信消息到医生端
  484. if (!function_exists('send_wechat_message_to_docter')) {
  485. function send_wechat_message_to_docter($type, $official_arr)
  486. {
  487. try {
  488. $app = Factory::miniProgram(config('config.docter_wechat_small_program'));
  489. //先发送模板消息
  490. $data = config('config.wechat_official_message_template')[$type];
  491. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  492. $json = vsprintf($json, $official_arr);
  493. $data = json_decode($json, true);
  494. $ret = $app->uniform_message->send($data);
  495. if (!isset($ret['errcode']) || $ret['errcode'] != 0) {
  496. trace(['发送医生端微信模板消息失败,请求参数' => $data, '返回数据' => $ret], 'error');
  497. }
  498. } catch (Exception $e) {
  499. trace(['发送医生端微信模板消息失败' => $e->getMessage(), '请求参数' => $data ?? '', '返回数据' => $ret ?? ''], 'error');
  500. }
  501. return $ret ?? false;
  502. }
  503. }
  504. // 医生端发送公众号模板消息方法
  505. if (!function_exists('send_wechatSubscription_message')) {
  506. function send_wechatSubscription_message($type, $arr,$message='docter_wechat_small_program')
  507. {
  508. try {
  509. $app = Factory::miniProgram(config('config.'.$message));
  510. $data = config('config.wechatSubscription_template')[$type];
  511. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  512. $json = vsprintf($json, $arr);
  513. $data = json_decode($json, true);
  514. $result = $app->uniform_message->send($data);
  515. } catch (Exception $e) {
  516. trace(['发送微信模板消息失败' => $e->getMessage(), '请求参数' => $data ?? '', '返回数据' => $result ?? ''], 'error');
  517. }
  518. return $result ?? false;
  519. }
  520. }
  521. if (!function_exists('get_docter_organization')) {
  522. function get_docter_organization($id){
  523. $org_id = DocterOrganization::where('docter_id',$id)->where('state',1)->pluck('organization_id')->toArray();
  524. if(empty($org_id)) return '';
  525. $name = Organization::whereIn('id',$org_id)->pluck('name')->toArray();
  526. return implode(',',$name);
  527. }
  528. }
  529. //后台发送微信消息
  530. if (!function_exists('admin_send_wechat_message')) {
  531. function admin_send_wechat_message($type, $official_arr, $subscribe_arr = [])
  532. {
  533. try {
  534. $app = Factory::miniProgram(config('config.wechat_small_program'));
  535. //先发送模板消息
  536. $data = config('notice.wechat_official_message_template')[$type];
  537. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  538. $json = vsprintf($json, $official_arr);
  539. $data = json_decode($json, true);
  540. $ret = $app->uniform_message->send($data);
  541. //如果模板消息发送失败(可能因用户没有关注公众号而失败)再发送订阅消息
  542. if (!empty($subscribe_arr) && isset($ret['errcode']) && $ret['errcode'] != 0) {
  543. $data = config('notice.wechat_subscribe_message_template')[$type];
  544. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  545. $json = vsprintf($json, $subscribe_arr);
  546. $data = json_decode($json, true);
  547. $ret = $app->subscribe_message->send($data);
  548. if (isset($ret['errcode']) && $ret['errcode'] != 0) {
  549. trace(['发送微信订阅消息失败,请求参数' => $data ?? '', '返回数据' => $ret ?? ''], 'error');
  550. }
  551. }
  552. } catch (Exception $e) {
  553. trace(['发送微信消息失败' => $e->getMessage(), '请求参数' => $data ?? '', '返回数据' => $ret ?? ''], 'error');
  554. }
  555. return $ret ?? false;
  556. }
  557. }
  558. // 后台医生端发送公众号模板消息方法
  559. if (!function_exists('admin_send_docter_message')) {
  560. function admin_send_docter_message($type, $arr)
  561. {
  562. try {
  563. $app = Factory::miniProgram(config('notice.docter_wechat_small_program'));
  564. $data = config('notice.wechatSubscription_template')[$type];
  565. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  566. $json = vsprintf($json, $arr);
  567. $data = json_decode($json, true);
  568. $result = $app->uniform_message->send($data);
  569. } catch (Exception $e) {
  570. trace(['发送微信模板消息失败' => $e->getMessage(), '请求参数' => $data ?? '', '返回数据' => $result ?? ''], 'error');
  571. }
  572. return $result ?? false;
  573. }
  574. }