微信第三方授权核心

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/26
 * Time: 16:29
 */
require_once("/include/lib/weixindisanfang/wxBizMsgCrypt.php");
class Wechat{
    private $token = '*****';
    private $encodingAesKey = '********';
    private $appId = '***********';
    private $cache ;
    public $authorizer_appid;
    public $authorizer_access_token;
    public $authorizer_refresh_token;
    private $appsecret = '**********';
    private $access_token_url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";//获取第三方平台component_access_token
    private $pre_auth_code_url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=";//获取预授权码pre_auth_code
    private $auth_page_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage';
    private $redirect_uri = "http://www.51yanjing.com/setting/weixin_shouquan";
    private $authorizer_access_token_url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=";
    private $refresh_authorizer_token_url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=";
    private $get_mp_info_api_url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=";
    private $create_menu_post_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
    private $get_menu_api_url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";

    function  __construct(){
        $this->cache = new cache();
    }

    public function getMpInfo(){
        $component_access_token = $this->getComponentAccessToken();
        $post_url = $this->get_mp_info_api_url.$component_access_token;
        $post_data = array(
            'component_appid'=>$this->appId,
            'authorizer_appid'=>$this->authorizer_appid,
        );
        $post_data = json_encode($post_data);
        $curl_return = $this->curl($post_url,$post_data,'post');
        $data_decode = $this->doJson($curl_return);
        return $data_decode;
    }

    /**
     * 获取自定义菜单
     * @param $jsonMenu
     */
    public function getMenu($zhutiId,$db=null){
        $db = is_null($db)? new mysql():$db;
        $access_token = $this->checkTokenExpire($zhutiId,$db);
        /*
        $access_token = $this->cache->Get('authorizer_access_token');
        if(!$access_token){
            $access_token = $this->refreshAuthorizerToken($appid);
        }
        */
        $get_url = $this->get_menu_api_url.$access_token;
        $return_data = $this->curl($get_url);
        return  $this->doJson($return_data);
    }
    /**
     * 设置/创建自定义菜单
     * @param $jsonMenu
     */
    public function createMenu($jsonMenu,$zhutiId,$db=null){
        $db = is_null($db)? new mysql():$db;
        $access_token = $this->checkTokenExpire($zhutiId,$db);
        $post_url = $this->create_menu_post_url.$access_token;
        $jsonMenu =  str::tohtml($jsonMenu);
        //print_r(json_decode($jsonMenu,true));exit;
        //$arr_menu = json_encode($arr_menu,JSON_UNESCAPED_UNICODE);
        $return_data = $this->curl($post_url,$jsonMenu,'POST');
        return $return_data;
    }

    //获取最近token
    public function checkTokenExpire($zhutiId,$db=null){
        $db = is_null($db)? new mysql():$db;
        $weixinInfo = $db->getOne('scs_mendian_zhuti_weixin',' * ','e_zhutiid = "'.$zhutiId.'" AND e_isauth = 1');
        if( !$weixinInfo ){
            return '';
        }

        if( $weixinInfo && $weixinInfo['e_weixin_authorizer_access_token'] && $weixinInfo['e_token_expire'] && $weixinInfo['e_token_expire'] != '0000-00-00 00:00:00' && time() < strtotime($weixinInfo['e_token_expire']) ){
            $access_token =  $weixinInfo['e_weixin_authorizer_access_token'];
        }else {
            $access_token = $this->refreshAuthorizerToken($weixinInfo['e_weixin_authorizer_appid']);
            $db->UpdateRecord('scs_mendian_zhuti_weixin', $weixinInfo['e_id'],array('e_weixin_authorizer_access_token'=>$access_token,'e_token_expire'=> date('Y-m-d H:i:s',time() + 3600)), 'e_id');
        }
        return $access_token;
    }
    /**
     * @param $auth_code
     * @return bool
     * 使用授权码换取公众号的接口调用凭据和授权信息
     * 该API用于使用授权码换取授权公众号的授权信息,
     * 并换取authorizer_access_token和authorizer_refresh_token。
     * 授权码的获取,需要在用户在第三方平台授权页中完成授权流程后,在回调URI中通过URL参数提供给第三方平台方。
     * 请注意,由于现在公众号可以自定义选择部分权限授权给第三方平台,
     * 因此第三方平台开发者需要通过该接口来获取公众号具体授权了哪些权限,而不是简单地认为自己声明的权限就是公众号授权的权限。
     */
    public function getAuthorizerAccessToken($auth_code){
        if(!$auth_code) return false;
        $access_token = $this->getComponentAccessToken();
        $post_url = $this->authorizer_access_token_url.$access_token;
        $post_data = array(
            'component_appid'=>$this->appId,
            'authorization_code'=>$auth_code
        );
        $post_data = json_encode($post_data);
        $return_data = $this->curl($post_url,$post_data,'POST');
        $data_dejson = $this->doJson($return_data);
        $authorizer_access_token = $data_dejson['authorization_info']['authorizer_access_token'];
        if($authorizer_access_token){
            $this->setAuthorizerAppid($data_dejson['authorization_info']['authorizer_appid']);
            $this->set_authorizer_access_token($data_dejson['authorization_info']['authorizer_access_token']);
            $this->set_authorizer_refresh_token($data_dejson['authorization_info']['authorizer_refresh_token']);
            $this->cache->Add('authorizer_appid', $data_dejson['authorization_info']['authorizer_appid'],7200);
            $this->cache->Add('authorizer_access_token', $data_dejson['authorization_info']['authorizer_access_token'],3600);
            $this->cache->Add('authorizer_refresh_token', $data_dejson['authorization_info']['authorizer_refresh_token'],7200);
            return array(
                'authorizer_appid'=>$data_dejson['authorization_info']['authorizer_appid'],
                'authorizer_access_token'=>$data_dejson['authorization_info']['authorizer_access_token'],
                'authorizer_refresh_token'=>$data_dejson['authorization_info']['authorizer_refresh_token']
            );
        }
        return array();
    }
    private function setAuthorizerAppid($authorizer_appid){
        $this->authorizer_appid = $authorizer_appid;
    }
    private function set_authorizer_access_token($authorizer_access_token){
        $this->authorizer_access_token = $authorizer_access_token;
    }
    private function set_authorizer_refresh_token($authorizer_refresh_token){
        $this->authorizer_refresh_token = $authorizer_refresh_token;
    }
    /**
     * 获取(刷新)授权公众号的接口调用凭据(令牌)
     * 该API用于在授权方令牌(authorizer_access_token)失效时,可用刷新令牌(authorizer_refresh_token)获取新的令牌。
     * 请注意,此处token是2小时刷新一次,开发者需要自行进行token的缓存,避免token的获取次数达到每日的限定额度。
     */
    public function refreshAuthorizerToken($appid){
        $component_access_token = $this->getComponentAccessToken();
        $post_url = $this->refresh_authorizer_token_url.$component_access_token;

        // $authorizer_appid = $this->cache->Get('authorizer_appid');
        // $authorizer_refresh_token = $this->cache->Get('authorizer_refresh_token');
        // if( !$authorizer_appid || !$authorizer_refresh_token){
        $wx = new weixin();
        $weixinInfo = $wx->getOneMpInfo($appid);
        $authorizer_appid = $weixinInfo['e_weixin_authorizer_appid'];
        $authorizer_refresh_token = $weixinInfo['e_weixin_authorizer_refresh_token'];
        // }

        $post_data = array(
            'component_appid'=>$this->appId,
            'authorizer_appid'=> $authorizer_appid,
            'authorizer_refresh_token'=>$authorizer_refresh_token,
        );

        $post_data = json_encode($post_data);
        $return_data = $this->curl($post_url,$post_data,'POST');
        $after_dejson = $this->doJson($return_data);
        if($after_dejson && isset($after_dejson['authorizer_access_token'])){
            $this->cache->Add('authorizer_appid',$this->cache->Get('authorizer_appid') ,7200);
            $this->cache->Add('authorizer_access_token',$after_dejson['authorizer_access_token'],3600);
            $this->cache->Add('authorizer_refresh_token',$after_dejson['authorizer_refresh_token'] ,7200);
            return $after_dejson['authorizer_access_token'];
        }
    }

    /**
     * @return URL
     * 引入用户进入授权页
     * 第三方平台方可以在自己的网站:中放置“微信公众号授权”的入口,
     * 引导公众号运营者进入授权页。授权页网址为
     * https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=xxxx&pre_auth_code=xxxxx&redirect_uri=xxxx,
     * 该网址中第三方平台方需要提供第三方平台方appid、预授权码和回调URI
     */
    public function getAuthUrl(){
        $pre_auth_code = $this->getPreAuthCode();
        $bulid_query = array(
            'component_appid'=>$this->appId,
            'pre_auth_code'=>$pre_auth_code,
            'redirect_uri'=>$this->redirect_uri
        );
        return $this->auth_page_url."?".http_build_query($bulid_query);
    }
    /**
     * @return bool
     * 获取预授权码pre_auth_code
     */
    private function getPreAuthCode(){
        $access_token =self::getComponentAccessToken();
        $post_url = $this->pre_auth_code_url.$access_token;
        $post_data = json_encode(array('component_appid'=>$this->appId));
        $data_return = $this->curl($post_url,$post_data,'POST');
        $pre_auth_code = $this->doJson($data_return,'pre_auth_code');
        return $pre_auth_code;
    }
    /**
     * return $access_token
     * 获取第三方平台component_access_token
     */
    public  function getComponentAccessToken(){
        if($access_token = $this->cache->Get('component_access_token')){
            return $access_token;
        }
        $component_verify_ticket = $this->cache->Get('component_verify_ticket');
        $post_data = array(
            'component_appid'=>$this->appId,
            'component_appsecret'=>$this->appsecret,
            'component_verify_ticket'=>$component_verify_ticket
        );
        $post_data = json_encode($post_data);
        $ret = $this->curl($this->access_token_url,$post_data,'POST');
        $component_token = $this->doJson($ret,'component_access_token');
        $this->cache->Add('component_access_token',$component_token,7000);
        return $component_token;
    }

    /**
     * @param $timeStamp
     * @param $nonce
     * @param $encrypt_type
     * @param $msg_sign
     * @param $encryptMsg
     * @return bool|string
     * 在公众号第三方平台创建审核通过后,
     * 微信服务器会向其“授权事件接收URL”每隔10分钟定时推送component_verify_ticket。
     * 第三方平台方在收到ticket推送后也需进行解密(详细请见【消息加解密接入指引】),
     * 接收到后必须直接返回字符串success。
     */
    function getVerify_Ticket($timeStamp,$nonce,$encrypt_type,$msg_sign,$encryptMsg){
        $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            $xml = new DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            return $component_verify_ticket;
        }else{
            return false;
        }
    }


    function checkMsgDecode($timeStamp,$nonce,$encrypt_type,$msg_sign,$encryptMsg){
        $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        $xml = new DOMDocument();
        $xml->loadXML($msg);

        $Content = $xml->getElementsByTagName('Content')->item(0)->nodeValue;
        $FromUserName = $xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;

        file_put_contents('msg.txt', '8'.$Content,FILE_APPEND);
        if( strstr($Content,'QUERY_AUTH_CODE') ){
            file_put_contents('QUERY_AUTH_CODE.txt', $Content);

            $auth_code = str_replace('QUERY_AUTH_CODE:','',$Content);
            $access_token = self::getComponentAccessToken();

            $post_url = $this->authorizer_access_token_url.$access_token;
            $post_data = array(
                'component_appid'=>$this->appId,
                'authorization_code'=>$auth_code
            );
            $post_data = json_encode($post_data);
            $return_data = $this->curl($post_url,$post_data,'POST');
            $data_dejson = $this->doJson($return_data);
            $authorizer_access_token = $data_dejson['authorization_info']['authorizer_access_token'];
            $this->cache->Add('check_authorizer_access_token',$authorizer_access_token,7000);
            file_put_contents('authorizer_access_token.txt',$authorizer_access_token);

            $post_url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
            $new_Content =  $auth_code. '_from_api';

            //$res = json_decode(self::https_request($new_url,$new_Content));

            $post_data = array(
                "touser" => $FromUserName,
                "msgtype" => "text",
                "text" => array("content"=>$new_Content)
            );
            $post_data = json_encode($post_data);
            $return_data = $this->curl($post_url,$post_data,'POST');
            //$data_dejson = $this->doJson($return_data);
            file_put_contents('touser.txt',$return_data);
            file_put_contents('return_data.txt',$return_data);
            file_put_contents('new_url.txt',$post_url);
            file_put_contents('new_Content.txt',$new_Content);
            return  true;

        }



        if( strstr($Content,'TESTCOMPONENT_MSG_TYPE_TEXT') ){
            /*
                file_put_contents('msg2.txt', $msg);
                 $xml_format = $this->xmlFormat($msg,'TESTCOMPONENT_MSG_TYPE_TEXT_callback');
                  file_put_contents('msg22.txt', $xml_format);
                  $res = $this->msgEncode($timeStamp,$nonce,$xml_format);
                     file_put_contents('msg222.txt', $res);
            */

            $authorizer_access_token = $this->cache->Get('check_authorizer_access_token');
            $post_url2="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
            $post_data2 = array(
                "touser" => $FromUserName,
                "msgtype" => "text",
                "text" => array("content"=>"TESTCOMPONENT_MSG_TYPE_TEXT_callback")
            );
            $post_data2 = json_encode($post_data2);
            file_put_contents('post_data.txt',$post_data2);

            $return_data = $this->curl($post_url2,$post_data2,'POST');
            file_put_contents('return_data2.txt',$return_data);

            return '';

        }


        $Event = $xml->getElementsByTagName('Event')->item(0)->nodeValue;
        if( isset($Event) ){
            file_put_contents('ori_msg.txt', $msg);

            $authorizer_access_token = $this->cache->Get('check_authorizer_access_token');
            $post_url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
            $post_data = array(
                "touser" => $FromUserName,
                "msgtype" => "text",
                "text" => array("content"=>$Event.'from_callback')
            );
            $post_data = json_encode($post_data);
            $return_data = $this->curl($post_url,$post_data,'POST');
            file_put_contents('return_data3.txt',$return_data);


            return $return_data;
        }
    }



    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }



    //公众号发过来的信息进行解密
    /**
     * @param $timeStamp
     * @param $nonce
     * @param $encrypt_type
     * @param $msg_sign
     * @param $encryptMsg
     * @return string
     */
    public function msgDecode($timeStamp,$nonce,$encrypt_type,$msg_sign,$encryptMsg){
        $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
        $errCode = $pc->decryptMsg ( $msg_sign, $timeStamp, $nonce, $encryptMsg, $msg );
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        //file_put_contents('from_xml.txt', print_r($from_xml, true));
        $msg = '';
        $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        return $msg;
    }
    //回复的信息进行XML格式化
    /**
     * @param $encryptMsg
     * @param $content
     * @return string
     */
    public function xmlFormat($encryptMsg,$content){
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $fromUserName = $xml_tree->getElementsByTagName('FromUserName')->item(0)->nodeValue;
        $toUserName = $xml_tree->getElementsByTagName('ToUserName')->item(0)->nodeValue;
        $resultStr = sprintf($textTpl,$fromUserName ,$toUserName, time(), $content);
        return $resultStr;
    }
    //公众号发过来的信息进行加密
    /**
     * @param $timeStamp
     * @param $nonce
     * @param $text
     * @return string
     */
    public function msgEncode($timeStamp,$nonce,$text){
        $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
        $encryptMsg = '';
        $errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
        if($errCode == 0){
            return $encryptMsg;
        }
    }
    /**
     * @param $url  请求链接
     * @param $data  请求数据
     * @param $method  请求方式
     */
    public function curl($url,$data=null,$method=null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        if($method && ($method=='post'||$method=='POST')){
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $output = curl_exec($ch);
        }else{
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
        }
        curl_close($ch);
        return $output;
    }

    /**
     * @param $json
     * @param $key
     * @return bool
     * 解析Json数据
     */
    public function doJson($json,$key=null){
        if($json){
            $json_arr = json_decode($json,true);
            if(!$key){
                return $json_arr;
            }
            return isset($json_arr[$key]) ? $json_arr[$key] : '';
        }
        return false;
    }

    //生成公众号二维码
    public  function getWachatCode($zhutiId,$sel_md_id = '',$sel_member_id = '',$db = null){
        $codeUrl = '';
        $db = is_null($db)? new mysql():$db;
        $weixinInfo = $db->getOne('scs_mendian_zhuti_weixin','e_weixin_authorizer_appid,e_weixin_authorizer_access_token,e_isauth,e_token_expire','e_zhutiid = '.$zhutiId);
        if( $weixinInfo && $weixinInfo['e_isauth'] == 1 && $weixinInfo['e_weixin_authorizer_appid']  ){
            $appid = $weixinInfo['e_weixin_authorizer_appid'];
            if( $weixinInfo['e_weixin_authorizer_access_token'] && $weixinInfo['e_token_expire'] && time() < strtotime($weixinInfo['e_token_expire']) ){
                $access_token =  $weixinInfo['e_weixin_authorizer_access_token'];
            }else{
                $access_token = $this->refreshAuthorizerToken($appid);
            }

            //$access_token = 'OtDUesYcDrIa24oQGkJdaNIEPvJW5aDlAqNKn8IMvGB7iJAW8p8u1XicZeN63vdeRSFgj53NcA3K4IoOv4PigIlFYUXkceo0MmpHJfV-IsWZQVa46RtFrHaGQ3a_d7YkDDUfAHDVVM';
            $post_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
            $post_data = array(
                'action_name' => 'QR_LIMIT_STR_SCENE',
                'action_info' => array(
                    'scene' => array(
                        'scene_str' => $sel_md_id.':'.$sel_member_id
                    )
                )
            );
            $post_data = json_encode($post_data);
            $return_data = $this->curl($post_url,$post_data,'POST');
            $res_arr = $this->doJson($return_data);

            if( isset($res_arr['ticket']) ){
                $r = $this->getImgHeader('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.UrlEncode($res_arr['ticket']));
                if( isset($r['header']['url']) ){
                    $codeUrl = $r['header']['url'];
                }
            }
        }
        return  $codeUrl;
    }


    public function getImgHeader($url){
        $ch =curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_NOBODY,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        return array_merge(array('body'=>$package),array('header'=>$httpinfo));
    }




    //授权服务号跟踪平台的微信动作接口
    public function responseWechat($postStr,$appid = '')
    {
        //  $postStr = $this->msgDecode($timeStamp,$nonce,$encrypt_type,$msg_sign,$encryptMsg);

        //extract post data
        if (!empty($postStr)){
            $db = new mysql();
            @session_start();
            $time = timer::now();
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA, '', true);
            $postObj = (array)$postObj;
            $FromUserName = $postObj['FromUserName'];
            $toUsername  = $postObj['ToUserName'];
            $keyword  = trim($postObj['Content']);
            $event = $postObj['Event'];
            $EventKey = $postObj['EventKey'];//雇员uid

            /*
            {
                "ToUserName": "gh_91f7d504c9a5",
                "FromUserName": "ov7ewwirVGRCn0FBsuKZy2NE-Hzc",
                "CreateTime": "1489564168",
                "MsgType": "event",
                "Event": "subscribe",
                "EventKey": "qrscene_1000",
                "Ticket": "gQFx8jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyUVA2R0YxX1RlTTIxMDAwMDAwMzIAAgQGsMhYAwQAAAAA"
            }
            */


            $access_token = '';
            if( $appid ){
                $weixinInfo = $db->getOne('scs_mendian_zhuti_weixin','e_id,e_weixin_authorizer_appid,e_weixin_authorizer_access_token,e_isauth,e_token_expire,e_auto_reply','e_weixin_authorizer_appid = "'.$appid.'" AND e_isauth = 1 ORDER BY e_addtime DESC LIMIT 1');
                if( $weixinInfo && $weixinInfo['e_weixin_authorizer_access_token'] && $weixinInfo['e_token_expire'] && time() < strtotime($weixinInfo['e_token_expire']) ){
                    $access_token =  $weixinInfo['e_weixin_authorizer_access_token'];
                }else{
                    $access_token = $this->refreshAuthorizerToken($appid);
                    if( $weixinInfo ){
                        $db->UpdateRecord('scs_mendian_zhuti_weixin', $weixinInfo['e_id'],array('e_weixin_authorizer_access_token'=>$access_token,'e_token_expire'=> date('Y-m-d H:i:s',time() + 3600)), 'e_id');
                    }
                }
            }
            //Func::fileSave('text.txt', $access_token); //调试模式
            if( !$appid || !$access_token ){
                return false;
            }



            $userInfo = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=". $access_token ."&openid=".$FromUserName);
            /*
            {
                "subscribe": 1,
                "openid": "ov7ewwirVGRCn0FBsuKZy2NE-Hzc",
                "nickname": "晃晃゛",
                "sex": 1,
                "language": "zh_CN",
                "city": "",
                "province": "",
                "country": "安道尔",
                "headimgurl": "http://wx.qlogo.cn/mmopen/30MvQccejdMbbsW8fgD1Bmicj5wfejR05H5ibmR23eyTO8rUYueKtfRK6jqhYFcw3gMb4t9yCv57WQr1fktRkicCLFNgU5DTcYh/0",
                "subscribe_time": 1489568389,
                "unionid": "os7-QwcuTjV-V6UgpJkQMjg5ls8I",
                "remark": "",
                "groupid": 0,
                "tagid_list": []
            }
            */


            $userInfo = json_decode($userInfo, true);
            $openid = $userInfo['openid'];
            $unionid = $userInfo['unionid'];
            //取消订阅时 可能获取不到昵称
            if(!isset($userInfo['nickname'])) {
                $nickname = '';
                $sex = 0;
                $language = '';
                $city = '';
                $province = '';
                $country = '';
                $headimgurl = '';
            } else {
                /*
                $nickname = $userInfo['nickname'];
                $sex = $userInfo['sex'];
                $language = $userInfo['language'];
                $city = $userInfo['city'];
                $province = $userInfo['province'];
                $country = $userInfo['country'];
                $headimgurl = $userInfo['headimgurl'];
                //判断会员是否入库
                if(!$db->ifExist("w_weixin_user", "w_unionid='". $unionid ."'", "w_id")) {
                    $newUserData = array(
                        'w_nick' => $nickname,
                        'w_faceurl' => $headimgurl,
                        'w_unionid' => $unionid,
                        'w_sex' => $sex,
                        'w_country' => $country,
                        'w_province' => $province,
                        'w_city' => $city,
                        'w_addtime' => timer::now()
                    );
                    $db->InsertRecord("w_weixin_user", $newUserData);
                }
                */
            }


            //获取本地微信会员id
            $ourUid = 0;
            $weixinUserInfo = $db->getOne("w_weixin_user", "w_id", "w_unionid='". $unionid ."'");
            if($weixinUserInfo) {
                $ourUid = $weixinUserInfo['w_id'];
            }

            //$event 操作类型 subscribe 订阅,unsubscribe 取消订阅,scan 扫描


            if(strtolower($event) == 'subscribe' || strtolower($event) == 'scan') {
                //关注要加session
                //$_SESSION['guanzhu_user_sess'] = $unionid;
            }
            //扫描回复信息

            if(strtolower($event) == 'subscribe') {
                $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
                $msgType = "text";


                //获取代码
                $contentStr = '';
                if($weixinInfo && $weixinInfo['e_auto_reply'] ) {
                    $contentStr = $weixinInfo['e_auto_reply'];
                }
                $xml_format = sprintf($textTpl, $FromUserName, $toUsername, time(), $msgType, $contentStr);
                //$result = $this->msgEncode($timeStamp,$nonce,$xml_format);//消息加密回复
                //Func::fileSave('text7.txt', $xml_format); //调试模式
                //Func::fileSave('text2.txt', $result); //调试模式
                return $xml_format;

            }
        }else {
            echo "";
        }
    }



    public function getXml($decodemsg){
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($decodemsg);
        $fromUserName = $xml_tree->getElementsByTagName('FromUserName')->item(0)->nodeValue;
        $toUserName = $xml_tree->getElementsByTagName('ToUserName')->item(0)->nodeValue;
        $keyword  =$xml_tree->getElementsByTagName('Content')->item(0)->nodeValue;
        $event =$xml_tree->getElementsByTagName('Event')->item(0)->nodeValue;
        $EventKey =  $xml_tree->getElementsByTagName('EventKey')->item(0)->nodeValue;
        return $fromUserName;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用PHP完成微信第三方平台授权,你可以按照以下步骤进行操作: 1. 首先,你需要注册成为微信开放平台的开发者,并创建一个第三方平台应用。 2. 在创建应用后,你会得到一个AppID和AppSecret,这些是与微信平台进行通信的凭证。 3. 在你的PHP项目中,你需要使用curl库或其他HTTP请求库来发送HTTP请求到微信开放平台的API接口。 4. 首先,你需要获取预授权码(pre_auth_code)。发送GET请求到以下接口: ``` https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=xxx ``` 其中,component_access_token是通过调用获取第三方平台component_access_token接口获取的。 5. 获取到预授权码后,你可以使用预授权码和你的AppID生成授权链接,引导用户进入授权页面: ``` https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=xxx&amp;pre_auth_code=xxx&amp;redirect_uri=xxx ``` 其中,component_appid是你的AppID,pre_auth_code是上一步获取的预授权码,redirect_uri是用户授权后的回调URL。 6. 用户在授权页面确认授权后,会跳转到你指定的回调URL,并携带授权码(authorization_code)参数。 7. 在回调URL对应的PHP页面中,你需要解析URL中的授权码参数,并使用授权码发送POST请求到以下接口,获取授权令牌(authorizer_access_token)和刷新令牌(authorizer_refresh_token): ``` https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=xxx ``` 其中,component_access_token是通过调用获取第三方平台component_access_token接口获取的。 8. 获取到授权令牌和刷新令牌后,你可以使用它们来调用微信开放平台的其他API接口,完成后续的操作。 以上是使用PHP完成微信第三方平台授权的基本流程,具体的实现细节可能会因具体需求而有所不同。在实际开发中,你还需要处理授权过期、刷新令牌等情况,以保证授权的有效性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值