functions.php 23 KB

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