ProcurementWeiXinSendMessageService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services;
  3. use App\Components\AsyncResponse;
  4. class ProcurementWeiXinSendMessageService
  5. {
  6. use AsyncResponse;
  7. //获取access_token
  8. public function get_access_token($appId = '', $appSecret = ''){
  9. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
  10. $result = file_get_contents($url);
  11. $result = json_decode($result,true);
  12. if (array_key_exists("access_token", $result)) return $result['access_token'];
  13. LogService::log(__METHOD__,"模板信息5",json_encode($result));
  14. return null;
  15. }
  16. //发送微信模版消息通知
  17. public function sendWenChantTemplate($param)
  18. {
  19. try {
  20. $params['touser'] = $param['touser'];
  21. $params['mp_template_msg'] = $param['mp_template_msg'];
  22. $res = $this -> send_message($params);
  23. } catch (\Exception $e) {
  24. LogService::log(__METHOD__,"发送模板消息失败",$params." | ".$e->getMessage());
  25. }
  26. LogService::log(__METHOD__,"发送模板消息成功",$params);
  27. }
  28. /**
  29. * @desc 发送微信消息
  30. * param string
  31. * $type
  32. * $param['title'] 消息标题
  33. * $param['reason'] 消息内容或者消息原因
  34. */
  35. public function send_message($param)
  36. {
  37. $appId=config('weiXin.xiaoChengXu.appId');
  38. $appSecret=config('weiXin.xiaoChengXu.appSecret');
  39. $data = [
  40. "touser" => $param['touser'],
  41. "mp_template_msg" => $param['mp_template_msg'],
  42. ];
  43. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  44. $access_token = self::get_access_token($appId, $appSecret);
  45. $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" . $access_token;
  46. //以'json'格式发送post的https请求
  47. $curl = curl_init();
  48. curl_setopt($curl, CURLOPT_URL, $url);
  49. curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
  50. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  51. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  52. if (!empty($json)) {
  53. curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
  54. }
  55. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  56. $output = curl_exec($curl);
  57. curl_close($curl);
  58. LogService::log(__METHOD__,"模板信息4",json_encode($output));
  59. return $output;
  60. }
  61. }