微信小程序推送公众号模板消息

 /***
     * @param $touser  //需要接受订阅消息的openid
     * @param $template_id //模板ID
     * @param $page //点击返回页面路径
     * @param $dataArray //订阅格式请参照小程序订阅消息模板中的格式
     * @return array
     * 订阅消息模板
     */
    public function sendSubscribeMessage($touser, $template_id, $page, $dataArray)
    {
        $data = array(
            "touser"        =>  $touser,        //openid
            "template_id"   =>  $template_id,             //模板id
            'miniprogram' => [
                'appid' => '',  //跳转关联小程序appid
                'pagepath' => 'pages/index/index', //跳转关联小程序页面
            ],
            "data"          =>  $dataArray      //模板数据
        );
        //access_token 一般都存在缓存 ,
        $access_token = $this->access_token();
        if ($access_token == 400){
            return ['code'=>0,'message'=>'获取access_token失败'];
        }
        $urls = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $result = $this->http_post_json($urls,json_encode($data));//发送请求
        if($result[0] == 200){
            return ['code'=>1,'data'=>'推送成功'];
        }
        return ['code'=>0,'message'=>$result[1]['errmsg']];
    }

    public function http_post_json($url, $jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [$httpCode,$response];
    }

    //获取access_token
    public function access_token(){
        $appId = self::$appid;
        $appSecret = self::$secret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url); //要访问的地址
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        $data = json_decode(curl_exec($ch),true);
        if(curl_errno($ch)){
            var_dump(curl_error($ch)); //若错误打印错误信息
        }
        curl_close($ch);//关闭curl
        return $data['access_token'];
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容