微信小程序结合后端php发送模版消息

前端:

html 复制代码
<view class="container">
  <button bindtap="requestSubscribeMessage">订阅消息</button>
</view>
javascript 复制代码
// index.js
Page({
  data: {
    tmplIds: ['UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0'] // 使用你的模板ID
  },

  requestSubscribeMessage() {
    const tmplIds = this.data.tmplIds;

    if (wx.requestSubscribeMessage) {
      // 使用基础库 2.4.4 及以上版本
      wx.requestSubscribeMessage({
        tmplIds: tmplIds,
        success: (res) => {
          // 处理订阅消息成功的结果
          console.log('Subscribe message success:', res);

          // 遍历结果,检查用户是否同意订阅
          for (let tmplId of tmplIds) {
            if (res[tmplId] === 'accept') {
              console.log(`Template ID ${tmplId} subscription accepted.`);
            } else {
              console.log(`Template ID ${tmplId} subscription denied or filtered.`);
            }
          }
        },
        fail: (err) => {
          // 处理订阅消息失败的结果
          console.error('Subscribe message failed:', err);
        },
        complete: () => {
          // 接口调用结束
          console.log('RequestSubscribeMessage complete');
        }
      });
    } else {
      // 兼容低版本
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      });
    }
  },

  onLoad() {
    // 页面加载时的逻辑
  }
});

后端:php7.4

php 复制代码
/*function getWeChatToken($appid, $secret) {
    $url = "https://api.weixin.qq.com/cgi-bin/token";
    $params = http_build_query([
        'grant_type' => 'client_credential',
        'appid' => $appid,
        'secret' => $secret,
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 忽略 SSL 证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 忽略 SSL 证书验证
    
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'cURL Error: ' . curl_error($ch);
        return null;
    }
    
    curl_close($ch);
    
    return json_decode($response, true);
}

// 替换为你的 AppID 和 AppSecret
$appid = '';
$secret = '';

$tokenInfo = getWeChatToken($appid, $secret);

if ($tokenInfo && isset($tokenInfo['access_token'])) {
    echo 'Access Token: ' . $tokenInfo['access_token'];
    $accessToken = $tokenInfo['access_token'];
} else {
    echo 'Failed to get access token. Response: ' . json_encode($tokenInfo);
}*/


function sendSubscribeMessage($accessToken, $templateId, $touser, $data, $page = '', $miniprogramState = 'formal', $lang = 'zh_CN') {
    $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$accessToken";
    
    $postData = json_encode([
        'touser' => $touser,
        'template_id' => $templateId,
        'page' => $page,
        'data' => $data,
        'miniprogram_state' => $miniprogramState,
        'lang' => $lang,
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 证书验证
    
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'cURL Error: ' . curl_error($ch);
        return null;
    }
    
    curl_close($ch);
    
    return json_decode($response, true);
}

// 替换为你的 AccessToken, TemplateID, Touser, 和 Data
$accessToken = 'your_access_token_here'; // 请替换为实际的 access token
$templateId = 'UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0';
$touser = 'oCmkd7cO3vjwvHhLUtjDJwklvLOE';
$data = [
    'time1' => ['value' => '2024-7-25 12:23:25'],
    'amount2' => ['value' => '128'],
    'thing3' => ['value' => '黑金卡'],
    'thing4' => ['value' => '24小时内发货'],
    'character_string5' => ['value' => '202407251236962365']
];
$page = 'index?foo=bar'; // 可选
$miniprogramState = 'formal'; // 可选,默认 'formal'
$lang = 'zh_CN'; // 可选,默认 'zh_CN'

$response = sendSubscribeMessage($accessToken, $templateId, $touser, $data, $page, $miniprogramState, $lang);

if ($response && isset($response['errcode'])) {
    if ($response['errcode'] == 0) {
        echo 'Message sent successfully!';
    } else {
        echo 'Failed to send message. Error code: ' . $response['errcode'] . ', Error message: ' . $response['errmsg'];
        // 根据错误码提供解决方案
        switch ($response['errcode']) {
            case 40001:
                echo ' - 获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口。';
                break;
            case 40003:
                echo ' - 不合法的 OpenID ,请开发者确认 OpenID (该用户)是否已关注公众号,或是否是其他公众号的 OpenID。';
                break;
            case 40014:
                echo ' - 不合法的 access_token ,请开发者认真比对 access_token 的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口。';
                break;
            case 40037:
                echo ' - 不合法的 template_id。';
                break;
            case 43101:
                echo ' - 用户未订阅消息。检查订阅弹窗回调结果或事件推送确认是否订阅成功,检查是否一次性订阅的次数之前已下发完。';
                break;
            case 43107:
                echo ' - 订阅消息能力封禁。检查账号是否被封禁订阅消息能力,检查模板id对应的模板是否被封禁。';
                break;
            case 43108:
                echo ' - 并发下发消息给同一个粉丝。检查是否有同时下发多个消息给同一粉丝的情况。';
                break;
            case 45168:
                echo ' - 命中敏感词。检查下发消息中是否带有敏感词。';
                break;
            case 47003:
                echo ' - 参数错误。根据wiki文档检查data结构格式是否正确,检查各个关键词是否满足对应规则。';
                break;
            default:
                echo ' - 未知错误,请参考微信公众平台文档。';
                break;
        }
    }
} else {
    echo 'Failed to send message. Invalid response.';
}