functions.php 23 KB

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