微信操作


/*微信登录tp后台代码
    require_once PLUGIN_PATH.'/login/wx/wx.class.php';
    $options['appid'] = '';
    $options['appsecret'] = '';
    $wechat = new \WechatApi($options);
    $code = $_GET['code'];
    if (!empty($code)) {
        $json = $wechat->getOauthAccessToken($code);
        if ($json !== false) {
            $jsonUserinfo = $wechat->getOauthUserinfo($json['access_token'], $json['openid']);
            if ($jsonUserinfo !== false) {
                $this->redirect('/mobile/login/login?wxUserinfo=' . json_encode($jsonUserinfo));
            } else {
                $this->redirect('/mobile/login/login/');
            }
        } else {
            $this->redirect('/mobile/login/login/');
        }
    }else {
        $this->redirect('/mobile/login/login/');
   }
 */
//$postStr="<xml>
//    <ToUserName><![CDATA[gh_ef8c05a27813]]></ToUserName>
//    <FromUserName><![CDATA[o04_XvmkaV45MlKY8sprr0gsZaw8]]></FromUserName>
//    <CreateTime>1473228115</CreateTime>
//    <MsgType><![CDATA[event]]></MsgType>
//    <MsgId>6327466573882180259</MsgId>
//    <Event>subscribe</Event>
//    <Encrypt><![CDATA[/jSnPXAov74SV/NpkvAswk0tPVDIYjjGy5IsKZVbshyfNLcRNL1QiN52+FT09ZoRWAPeWxeCXvFgdzEAXfkDeYjibJzzoET5a3s51TF3xwHbUPVvwSMBsAIxZtN5gtT8O61SOlNJBdyHtSqT8e4c2A6FMOUr6NUcHDznAOr9anOCXX/sUzKLS7USbG+k8vBub+bzEUG5GwqBLSetw7Jzxe6p+/FsW5oGPPGdBfhLummH4HnbUYQpcNqzPhbKcE9MwyRJmAgRQ2ONbsD5HGJV+hggzLL5O2K27X7+3eGGHsBS/7aCfAapGk7p8sOnkN3AESaHCJrpGN8T+YwAQOHjPhLecvxlBgMSVCIxA5vichj+QWhU+yMmM+aTUfa0WjaWTD3lM6le1wNADR+/mxFA9Z/kCEbKwFlqd1XPi8SMACs=]]></Encrypt>
//</xml>";

//require_once('/Public/wechat/wechat.class.php');
//vendor('wechat/wechat.class.php');
//$wechat = new weixin();
//$postStr = file_get_contents("php://input");//xml数据
////file_put_contents('message.txt',$postStr);
////var_dump($postStr);
////接收微信消息并回复
//if($postStr) {
//    $wechat->weixinreplay($postStr);
//}
////微信登录
//elseif (isset($_GET['code'])) {
//    if ($_GET['c'] == "ewm") {
//        header("location:http://www.abc.com/web/index/wxbd.html?code=" . $_GET['code']);
//    } else {
//        header("location:http://www.abc.com/web/index/wx.html?code=" . $_GET['code']);
//    }
//}
////验证公众号绑定地址
//elseif(isset($_GET['echostr'])){
//    $wechat->valid();
//}

class Wechat
{
    public function __construct()
    {
        $this->Token = '';//微信公众号token
        $this->APPID = '';//微信公众号appid
        $this->APPSECRET = '';//微信公众号appsecret
        $this->API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';//微信公众号平台
        $this->API_URL_OPEN='https://api.weixin.qq.com/sns/';//微信开放平台
        $this->OPENAPPID='';//微信开放平台appid
        $this->OPENSECRET='';//微信开放平台APPSECRET
        $this->User_INFO_URL = '/user/info?';// 获取用户信息
        $this->CUSTOM_SEND_URL = '/message/custom/send?';//客服发消息接口
        $this->GET_CALLBACK_IP = '/getcallbackip?';//获取微信服务器ip
    }

    //微信公众号验证绑定地址
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $this->Token;
        //将token、timestamp、nonce按字典序排序
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        //对tmpStr进行sha1加密
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    //验证消息是否来自微信服务器
    public function checkweixinip()
    {
        $accesstoken = $this->getToken();
        $url = $this->API_URL_PREFIX . $this->GET_CALLBACK_IP . 'access_token=' . $accesstoken;
        $result = $this->http_weixinget($url);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || isset($json['errcode'])) {
                $errcode = $json['errcode'];
                $errmsg = $json['errmsg'];
                return false;
                exit();
            } else {
                return true;
                exit();
            }
        }
    }
    //微信开放平台获得用户信息
    public function getinfo($code)
    {
        $url =$this->API_URL_OPEN."oauth2/access_token?appid=".$this->OPENAPPID."&secret=". $this->OPENSECRET."&code=".$code."&grant_type=authorization_code";
        $accesstoken = $this->http_weixinpost($url,'');
        $token = json_decode($accesstoken,true);
        $refresh_token=$token['refresh_token'];//获得access_token 与微信公众平台access_token不同

        $tokenurl=$this->API_URL_OPEN."oauth2/refresh_token?appid=".$this->OPENAPPID."&grant_type=refresh_token&refresh_token=".$refresh_token;
        $refreshtoken=$this->http_weixinpost($tokenurl,'');
        $refresh= json_decode($refreshtoken,true);
        $access_token = $refresh['access_token'];
        
        $openid = $refresh['openid'];
        $get_user_info_url =$this->API_URL_OPEN. 'userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $userinfo=$this->http_weixinpost($get_user_info_url,'');
        $json_userinfo= json_decode($userinfo,true);
        return $json_userinfo;
    }



    //访问外网
    public function http_weixinget($url)
    {
        //$content = file_get_contents($url);
        //return $content;
        $curl = curl_init($url);//获取网络资源
        if (strripos($url, 'https://') !== false) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($curl);
        $status = curl_getinfo($curl);
        curl_close($curl);
        if ($status['http_code'] == 200) {
            return $content;
            exit();
        } else {
            return false;
            exit();
        }
    }

    //访问外网
    public function http_weixinpost($url, $data)
    {
        $curl = curl_init($url);//获取网络资源
        if (strripos($url, 'https://') !== false) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $content = curl_exec($curl);
        $status = curl_getinfo($curl);
        curl_close($curl);
        if ($status['http_code'] == 200) {
            return $content;
            exit();
        } else {
            return false;
            exit();
        }
    }

    //获取  access_token
    public function getToken()
    {
        //如果是微信服务器
        if ($this->checkweixinip()) {
            $tabtoken = M('accesstoken');
            $tabtoken->field('accesstoken,time')->find();
            $lastGetTime = $tabtoken['time'];
            //如果已有accesstoken
            if (!empty($lastGetTime)) {
                $now = time();
                //判断已存在的accesstoken的时间在7000秒以上重新获取accesstoken
                if (($now - $lastGetTime) > 7000) {
                    $url = $this->API_URL_PREFIX . $this->AUTH_URL . 'appid=' . $this->APPID . '&secret=' . $this->APPSECRET;
                    $result = $this->http_weixinget($url);
                    //json转换成数组 取accesstoken
                    if ($result) {
                        $json = json_decode($result, true);
                        if (!$json || isset($json['errcode'])) {
                            $errcode = $json['errcode'];
                            $errmsg = $json['errmsg'];
                            return false;
                            exit();
                        }
                        $accesstoken = $json['access_token'];
                        $Time = time();
                        $data = array('accesstoken' => $accesstoken, 'time' => $Time);//获取到的accesstoken插入数据库
                        $tabtoken->save($data);
                        return $accesstoken;
                        exit();
                    }
                } //否则继续用已有的accesstoken
                else {
                    $accesstoken = $tabtoken['accesstoken'];
                    return $accesstoken;
                    exit;
                }
            } //如果没有accesstoken获取accesstoken
            else {
                $url = $this->API_URL_PREFIX . $this->AUTH_URL . 'appid=' . $this->APPID . '&secret=' . $this->APPSECRET;
                $result = $this->http_weixinget($url);
                //json转换成数组 取accesstoken
                if ($result) {
                    $json = json_decode($result, true);
                    if (!$json || isset($json['errcode'])) {
                        $errcode = $json['errcode'];
                        $errmsg = $json['errmsg'];
                        return false;
                        exit();
                    }
                    $accesstoken = $json['access_token'];
                    $Time = time();
                    $data = array('accesstoken' => $accesstoken, 'time' => $Time);
                    $tabtoken->add($data);//获取到的accesstoken插入数据库
                    return $accesstoken;
                    exit();
                }
            }
        }
    }

    //微信回复
    public function weixinreplay($postStr)
    {
        //如果是微信服务器
        if ($this->checkweixinip()) {
            if (!empty($postStr)) {
                $recive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                //接收到文本消息
                if ($recive['MsgType'] == 'text') {
                    if (isset($recive['Content'])) {
                        $content = $recive['Content'];
                        $time = $recive['CreateTime'];
                        $message = array(
                            'openid' => $recive['FromUserName'],
                            'content' => $content,
                            'image' => '',
                            'time' => $time,
                        );
                        $tabweimessage = M('weimessage');
                        $tabweimessage->add($message);//消息插入数据库
                        $recontent = '您的消息已接收';
                        $openId = $recive['FromUserName'];
                        $data = "{\"touser\":\"$openId\",\"msgtype\":\"text\",\"text\":{\"content\":\"$recontent\"}}";
                        $accesstoken = $this->getToken();
                        $clientMsgUrl = $this->API_URL_PREFIX . $this->CUSTOM_SEND_URL . 'access_token=' . $accesstoken;//客服发消息接口
                        $this->http_weixinpost($clientMsgUrl, $data);
                        return $content;
                        exit;
                    }
                } //接受到时间推送
                elseif ($recive['MsgType'] == 'event') {
                    switch ($recive['Event']) {
                        //关注事件
                        case 'subscribe':
                            $recontent = "欢迎关注!";
                            $openId = $recive['FromUserName'];
                            $data = "{\"touser\":\"$openId\",\"msgtype\":\"text\",\"text\":{\"content\":\"$recontent\"}}";
                            $accesstoken = $this->getToken();
                            $clientMsgUrl = $this->API_URL_PREFIX . $this->CUSTOM_SEND_URL . 'access_token=' . $accesstoken;//客服发消息接口
                            $this->http_weixinpost($clientMsgUrl, $data);
                            $userinfourl = $this->API_URL_PREFIX . $this->User_INFO_URL . 'access_token=' . $accesstoken . '&openid=' . $openId . '&lang=zh_CN ';//获取用户信息
                            $userinfo = json_decode($this->http_weixinget($userinfourl), true);
                            $time = $recive['CreateTime'];
                            $user = array(
                                'openid' => $userinfo['openid'],
                                'nickname' => $userinfo['nickname'],
                                'headimgurl' => $userinfo['headimgurl'],
                                'time' => $time,
                            );
                            $tabweiuserinfo = M('weiuserinfo');
                            $tabweiuserinfo->add($user);//获取关注人信息
                            break;
                        //取消关注事件
                        case 'unsubscribe';
                            $openId = $recive['FromUserName'];
                            $tabweiuserinfo = M('weiuserinfo');
                            $tabweiuserinfo->where("openid='%s'", array($openId))->delete();//删除关注人信息
                            break;
                    }
                    exit;
                } //接收到图片消息
                elseif ($recive['MsgType'] == 'image') {
                    $recontent = "您的消息已接收";
                    $openId = $recive['FromUserName'];
                    $time = $recive['CreateTime'];
                    $data = "{\"touser\":\"$openId\",\"msgtype\":\"text\",\"text\":{\"content\":\"$recontent\"}}";
                    $accesstoken = $this->getToken();
                    $clientMsgUrl = $this->API_URL_PREFIX . $this->CUSTOM_SEND_URL . 'access_token=' . $accesstoken;//客服发消息接口
                    $this->http_weixinpost($clientMsgUrl, $data);
                    $imageurl = $recive['PicUrl'];
                    $message = array(
                        'openid' => $openId,
                        'content' => '',
                        'image' => $imageurl,
                        'time' => $time,
                    );
                    $tabweimessage = M('weimessage');
                    $tabweimessage->add($message);//消息插入数据库
                    exit;
                }
            }
        }
    }

}

?>



©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容