WxTplMsg.php 1.8 KB

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