小程序发送订阅消息(前后端)

发布时间 2023-12-28 14:59:08作者: 79524795

uniapp代码

uni.requestSubscribeMessage({
      tmplIds: ['*****你的订阅消息模板ID1****', '******你的订阅消息模板ID2****' ],
     success(res) {
        if (res['******你的订阅消息模板ID1****'] === 'accept'  && res['******你的订阅消息模板ID2****'] === 'accept') {

			uni.showToast({
            title: '订阅成功',
            icon: 'success'
         });

        } else {
          uni.showToast({
            title: '订阅失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error(err);
      }
});


PHP后端代码-发送消息

 
 $this->sendxcx(用户的openid)
 
   public function sendxcx($openid){
        // 替换成你的小程序的 appid 和 appsecret
        $appid = 'wx68c10f529a4f6******';
        $appsecret = '0ad48418eecb77e84780*********';
        
        // 替换成你的模板消息 ID
        $templateId = '*************************';
  
    
        // 替换成你的模板消息的数据
        $messageData = array(
            'thing4' => array(
                'value' => '您有新的未读消息,请注意登录小程序查收',
            ),
            'time7' => array(
                'value' => date('Y-m-d H:i:s'),
            ),
        );
        // 获取访问令牌
        $accessToken = $this->getAccessToken($appid, $appsecret);
        // 发送订阅消息
        $this->sendSubscribeMessage($accessToken, $openid, $templateId, $messageData);
  
   }
    
    
        
     public function getAccessToken($appid, $appsecret) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
    
        $response = json_decode(file_get_contents($url), true);
    
        if (isset($response['access_token'])) {
            return $response['access_token'];
        } else {
            // 处理获取失败的情况
            die('Failed to get access token');
        }
    }
    
    public function sendSubscribeMessage($accessToken, $openid, $templateId, $messageData) {
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
    
        $postData = array(
            'touser' => $openid,
            'template_id' => $templateId,
            'data' => $messageData,
        );
    
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' => json_encode($postData),
            ),
        );
    
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
    
        $resultData = json_decode($result, true);
    
        if (isset($resultData['errcode']) && $resultData['errcode'] == 0) {
            echo 'Subscribe message sent successfully';
        } else {
            // 处理发送失败的情况
            echo 'Failed to send subscribe message: ' . json_encode($resultData);
        }
    }
    



注意发送消息的$messageData要按照 订阅消息模板来写

我的是

image