| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Service\Weixin;
- use Exception;
- class WxTemplateMessageService extends WeixinService
- {
- /**
- * 发送微信模板消息
- *
- * @param string $templateKey 模板配置key(对应 config 中的 template_map)
- * @param array $dataData 模板参数(key 对应 config 中定义)
- * @param array $options [
- * 'pagepath' => '', // 小程序路径
- * 'url' => '', // 网页路径
- * 'openid' => '', // 可选,优先使用
- * ]
- * @return array [bool, string]
- */
- public function sendTemplateMessage(string $templateKey, array $dataData, array $options = []): array
- {
- try {
- $config = config("wx_msg.template_map.$templateKey");
- if (!$config) return [false, "微信消息模板键值不存在: {$templateKey}"];
- $openid = $options['openid'] ?? "";
- if (empty($openid)) return [false, "openid 不能为空"];
- list($tokenOk, $token) = $this->getTokenSTABLE();
- if (! $tokenOk) return [false, $token];
- $jumpType = $config['jump_type'] ?? '';
- $payload = [
- 'touser' => $openid,
- 'template_id' => $config['tmp_id'],
- 'data' => $this->buildTemplateData($config, $dataData, $options),
- ];
- // 动态跳转处理
- if ($jumpType === 'h5') {
- $payload['url'] = $options['url'] ?? '';
- } elseif ($jumpType === 'mp') {
- $payload['miniprogram'] = [
- 'appid' => config('wx_msg.default_appid'),
- 'pagepath' => $options['pagepath'] ?? '',
- ];
- }
- $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}";
- $res = $this->curlOpen($url, ['post' => json_encode($payload, JSON_UNESCAPED_UNICODE)]);
- $res = json_decode($res, true);
- if (isset($res['errcode']) && $res['errcode'] === 0) return [true, ''];
- return [false , $res['errmsg']];
- } catch (Exception $e) {
- return [false, $e->getMessage()];
- }
- }
- /**
- * 构建模板数据结构
- */
- protected function buildTemplateData(array $config, array $dataData, array $options = []): array
- {
- $result = [];
- $first = $options['first'] ?? $config['first'] ?? '';
- $remark = $options['remark'] ?? $config['remark'] ?? '';
- if ($first) {
- $result['first'] = ['value' => $first, 'color' => '#173177'];
- }
- foreach ($config['params'] as $key => $field) {
- $value = $dataData[$key] ?? '';
- $result[$field] = ['value' => (string)$value, 'color' => '#173177'];
- }
- if ($remark) {
- $result['remark'] = ['value' => $remark, 'color' => '#173177'];
- }
- return $result;
- }
- }
|