微信公众号发送消息

<?php
/**
 * PushMessage
 * 微信公众号发送文本信息
 */
class PushMessage{
    private $appID = "";          // 服务号appID
    private $appSecret = "";     // 服务号appSerect
    // 获取access_token
    public function getAccessToken() {
        $appID = $this->appID;                                   // 服务号appID
        $appSecret = $this->appSecret;                           // 服务号appSerect
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appID&secret=$appSecret";
        $content = file_get_contents($url); 
        $content = (array)json_decode($content); 
        if(isset($content[‘errcode‘])){
            echo ‘授权失败‘;
            exit;
        }
        $record = array();
        $record[‘token‘] = $content[‘access_token‘];
        return $record[‘token‘];
    }

    // 2. 判断是否关注公众号。
    // 判断当前用户是否关注公众号
    public  function isSubscribe($openid) {

        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appID&secret=$this->appSecret";
        $access_msg = json_decode(file_get_contents($access_token));
        $token = $access_msg->access_token;
        $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid={$openid}";
        $subscribe = json_decode(file_get_contents($subscribe_msg));
        $gzxx = $subscribe->subscribe;
        //
        if($gzxx === 1){
            return 1;
        }else{
            return 0;
             
        }
    }
 

    // 3. 发送客服消息。
    public function solPushMsg($openid, $content) {
        // 获取access_token
        $accessToken = $this->getAccessToken();
       $sta = $this->isSubscribe($openid);
        if(!$sta){
            return ‘请关注公众号接受信息‘;
        }
       // content
        $data = array(
          ‘touser‘ => $openid,              // 用户openID
          ‘msgtype‘ => ‘text‘,
          ‘text‘ => [
                ‘content‘ => urlencode($content),     // 内容
            ],
        );
        // send
        $url = ‘https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=‘.$accessToken; 
        $res = $this->getJson($url,urldecode(json_encode($data))); // urldecode必须带上,不然发出的消息可能是unicode编码的
        
        return $res;
        
    }   
    function getJson($url,$data=0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($data)){
               curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         }
        
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}
$message = new PushMessage;
$message->solPushMsg(‘openID‘,‘文本内容‘);

 

微信公众号发送消息

上一篇:基于第三方微信授权登录的iOS代码分析


下一篇:微信公共开发者文档 阅读笔记