WxTplMsg.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace app\common\library\wechat;
  3. /**
  4. * 微信模板消息 (废弃)
  5. * Class WxTplMsg
  6. * @package app\common\library\wechat
  7. */
  8. class WxTplMsg extends WxBase
  9. {
  10. /**
  11. * 发送模板消息
  12. * @param array $param
  13. * @return bool
  14. * @throws \app\common\exception\BaseException
  15. */
  16. public function sendTemplateMessage($param)
  17. {
  18. // 微信接口url
  19. $accessToken = $this->getAccessToken();
  20. $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$accessToken}";
  21. // 构建请求
  22. $params = [
  23. 'touser' => $param['touser'],
  24. 'template_id' => $param['template_id'],
  25. 'page' => $param['page'],
  26. 'form_id' => $param['form_id'],
  27. 'data' => $this->createData($param['data'])
  28. ];
  29. $result = $this->post($url, $this->jsonEncode($params));
  30. // 记录日志
  31. $this->doLogs(['describe' => '发送模板消息', 'url' => $url, 'params' => $params, 'result' => $result]);
  32. // 返回结果
  33. $response = $this->jsonDecode($result);
  34. if (!isset($response['errcode'])) {
  35. $this->error = 'not found errcode';
  36. return false;
  37. }
  38. if ($response['errcode'] != 0) {
  39. $this->error = $response['errmsg'];
  40. return false;
  41. }
  42. return true;
  43. }
  44. /**
  45. * 生成关键字数据
  46. * @param $data
  47. * @return array
  48. */
  49. private function createData($data)
  50. {
  51. $params = [];
  52. foreach ($data as $key => $value) {
  53. $params[$key] = [
  54. 'value' => $value,
  55. 'color' => '#333333'
  56. ];
  57. }
  58. return $params;
  59. }
  60. }