WechatMessage.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Com;
  3. use App\Com\WechatAccessToken;
  4. use App\Models\AccountWechat;
  5. use App\Models\OperatorsUser;
  6. use App\Com\Redis;
  7. use EasySwoole\EasySwoole\Logger;
  8. /**
  9. * 微信公众号消息模板发送
  10. */
  11. class WechatMessage
  12. {
  13. protected $minwechat_appid = null; //小程序公众号appid
  14. protected $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
  15. protected $access_token = null; //公众号access_token
  16. protected $redis = null; //redis实例
  17. public function __construct($operators_id=0)
  18. {
  19. $at = new WechatAccessToken($operators_id);
  20. $this->access_token = $at->getAccess_token();
  21. $set = AccountWechat::create()->get()->toArray();
  22. if(!$operators_id){
  23. $this->minwechat_appid = $set['key'];
  24. }
  25. else{
  26. //获取运营商数据
  27. $operators_res = OperatorsUser::create()->where('id',$operators_id)->get()->toArray();
  28. $this->minwechat_appid = $operators_res['key']?$operators_res['key']:$set['key'];
  29. }
  30. //加载redis
  31. $this->redis = Redis::getInstance()->getConnect();
  32. }
  33. /**
  34. * @param $openid 公众号openid
  35. * @param $templateId 消息模板ID
  36. * @param $jump_path 小程序跳转路径
  37. * @param $templateBody 消息模板标签内容
  38. * @return Bool 是否发送成功
  39. */
  40. public function send_message($openid,$templateId,$jump_path,$templateBody){
  41. //请求数据体
  42. $json_Body = Array(
  43. 'touser' => $openid,
  44. 'template_id' => $templateId, //模板ID
  45. 'miniprogram' => Array(
  46. 'appid' => $this->minwechat_appid,
  47. 'pagepath' => $jump_path,
  48. ),
  49. //公众号消息模板
  50. 'data' => $templateBody,
  51. );
  52. $res = $this->http_rquest($this->url."?access_token=".$this->access_token,$json_Body);
  53. //记录微信服务器返回值
  54. Logger::getInstance()->info('公众号模板消息接口返回值:'.$res);
  55. $api_res = json_decode($res,true);
  56. $result['request'] = $json_Body;
  57. $result['response'] = $api_res;
  58. return $result;
  59. //return $result['errcode']!=0?false:true;
  60. }
  61. /**
  62. * http请求
  63. * @param $url 请求地址
  64. * @param $jsonBody 数组内容
  65. * @return String 请求返回原生数据
  66. */
  67. protected function http_rquest($url,$jsonBody){
  68. $opts = array(
  69. 'http' => array(
  70. 'method' => 'POST',
  71. 'heade' => "Content-type:application/json",
  72. 'content' => json_encode($jsonBody),
  73. )
  74. );
  75. $context = stream_context_create($opts);
  76. $response = file_get_contents($url,false,$context);
  77. return $response;
  78. }
  79. }