functions.php 23 KB

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