functions.php 23 KB

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