微信扫码登陆/微信公交号 登录PHP 自适应 UnionID统一用户
admin
2023-06-19 18:01:53
0

namespace Topxia\Component\OAuthClient;
/**
 * 微信扫码登陆
 * Enter description here ...
 * @author Administrator
 *
 */
class WeixinOAuthClient extends AbstractOAuthClient
{

    public $tokenURL;
    public $authorizeURL;
    public $userURL;

    public $scope = '';
    public $app_key;
    public $app_secret;
    public $display = '';
    public $graphURL = '';


    public $token = array();
    public $meth = array();

    public $post_login = array();
    public $post_token = array();
    public $post_msg = array();

    public function getAuthorizeUrl($callbackUrl)
    {
        $state = md5(time()+rand(0,9999));
        $_SESSION['weixin_state'] = $state;

        $url="";
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
        {
            /**
             * 公众号登录
             * Enter description here ...
             * @var unknown_type
             */
                
            $this->config['key']="wx";//用户 微信公交号登录的 APPID
            
            $url = "https://open.weixin.qq.com/connect/oauth3/authorize";
            $url .="?appid=".$this->config['key']."&redirect_uri=".urlencode($callbackUrl)."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

        }
        else
        {
            /**
             * 微信网页授权登录
             * Enter description here ...
             * @var unknown_type
             */
            $this->authorizeURL = 'https://open.weixin.qq.com/connect/qrconnect';
            $this->app_key = $this->config['key'];
            $this->app_secret = $this->config['secret'];
            $this->parameter = array(
                'response_type' => 'code',
                'scope' => 'snsapi_login',
                'state' => $state,
            );

            $url = $this->authorizeURL.'?';
            $url .= 'appid='.$this->app_key;
            if(!empty($callbackUrl))
            {
                $this->parameter['redirect_uri'] = $callbackUrl;
            }
            $url .= '&'.http_build_query($this->parameter);
        }
        return $url;
    }



    public function getAccessToken($code, $callbackUrl)
    {


        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
        {
            /**
             * 公众号登录
             * Enter description here ...
             * @var unknown_type
             */
                
            $APPID="wx";//用户 微信公交号登录的 APPID
            $SCRETID="200049";//用户 微信公交号登录的 SCRETID
            
            
            
            $url = "https://api.weixin.qq.com/sns/oauth3/access_token?appid=".$APPID."&secret=".$SCRETID."&code=".$code."&grant_type=authorization_code";

            $re = $this->curl_get_contents1($url);
            $rearr = json_decode($re,true);
            $openid = $rearr['openid'];

            $url3 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$SCRETID;
            $re3 = $this->curl_get_contents1($url3);
            $re3arr = json_decode($re3,true);
            //print_r($re3arr);exit;
            
            $token1['openid1']=$openid;
            $token1['token']=$re3arr['access_token'];
            
            $unionid=$this->getunionid($token1);
            
            //$_SESSION['openid'] = $openid;
            $token = array(
               'userId' => $unionid,
            'token' => $re3arr['access_token'],
            'openid' => $unionid,
            'openid1' => $openid,
            // 'refresh_token' => $rawToken['refresh_token'],
            );
            return $token;

        }
        else
        {

            $url = sprintf('https://api.weixin.qq.com/sns/oauth3/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',$this->config['key'],$this->config['secret'],$code);
            $re = $this->curl_get_contents1($url);
            $rawToken = json_decode($re,true);
            if($rawToken['errcode']){
                echo "错误提示:".$data;
                exit;
            }
            //$_SESSION['openid'] = $rawToken['openid'];
            
            $token1['openid1']=$rawToken['openid'];
            $token1['token']=$rawToken['access_token'];
            
            $unionid=$this->getunionid($token1);
            $token = array(
        'userId' => $unionid,
            'token' => $rawToken['access_token'],
            'openid' => $unionid,
            'openid1' => $rawToken['openid'],
            'refresh_token' => $rawToken['refresh_token'],
            );
            return $token;
        }

    }

    /**
     * 获取unionid 统一微信登录用户
     * Enter description here ...
     * @param unknown_type $token
     */
    public function getunionid($token)
    {
        $userInfo=array();
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
        {
            /**
             * 公众号登录
             * Enter description here ...
             * @var unknown_type
             */
            header("Content-type: text/html; charset=utf-8");   
            $url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token['token']."&openid=".$token['openid1']."&lang=zh_CN";
            $re2 = $this->curl_get_contents1($url2);
            $userInfo = json_decode($re2,true);
        }
        else
        {
            $params = array();
            $params['access_token'] = $token['token'];
            $params['openid'] = $token['openid1'];
            $url='https://api.weixin.qq.com/sns/userinfo';
            $url .="?access_token=".$params['access_token']."&openid=".$params['openid']."&lang=zh_CN";
            $re = $this->curl_get_contents1($url);
            $userInfo = json_decode($re,true);
        }
        
        return $userInfo['unionid'];
    }
    
    
    
    public function getUserInfo($token)
    {

        $userInfo=array();
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
        {
            
            /**
             * 公众号登录
             * Enter description here ...
             * @var unknown_type
             */
            header("Content-type: text/html; charset=utf-8");   
            $url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token['token']."&openid=".$token['openid1']."&lang=zh_CN";
            $re2 = $this->curl_get_contents1($url2);
            $userInfo = json_decode($re2,true);
        }
        else
        {
            $params = array();
            $params['access_token'] = $token['token'];
            $params['openid'] = $token['openid1'];
            $url='https://api.weixin.qq.com/sns/userinfo';
            $url .="?access_token=".$params['access_token']."&openid=".$params['openid']."&lang=zh_CN";
            $re = $this->curl_get_contents1($url);
            $userInfo = json_decode($re,true);
            //$this->checkError($userInfo);
        }
        //print_r($userInfo);exit;
        return $this->convertUserInfo($userInfo);
    }

    protected function convertUserInfo($rawUserInfo)
    {
        $info = array();
        //print_r($rawUserInfo);
        $info['name'] = $rawUserInfo['nickname'];
        $info['sex'] = $rawUserInfo['sex'];
        $info['id'] = $rawUserInfo['unionid'];
        $info['smallAvatar'] = $rawUserInfo['headimgurl'];
        return $info;
    }


    //var_dump($openid);
    function curl_get_contents1($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_USERAGENT, "IE 6.0");
        curl_setopt($ch, CURLOPT_REFERER, "");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    private function checkError($userInfo)
    {
        if (!array_key_exists('error_code', $userInfo)) {
            return ;
        }
        if ($userInfo['error_code'] == '21321') {
            throw new \Exception('unaudited');
        }
        throw new \Exception($userInfo['error']);
    }
}

相关内容

热门资讯

伊媒公布对美备忘录草案,白宫:... 在伊朗媒体披露美伊“初步非正式备忘录”,称美将解除海上封锁并换取霍尔木兹通航后,白宫方面迅速予以否认...
吴思瑶批蒋万安又翻车?游淑慧举... 海峡导报综合报道 英伟达进驻台北北投士林科技园区(北士科),用电问题引发台北市长选战攻防。民进党民代...
俄军空袭强度骤升,泽连斯基紧急... 在俄罗斯加大对乌克兰空袭力度,并威胁打击基辅决策中心之际,乌克兰总统泽连斯基紧急致信特朗普。《基辅独...
禁止中国厂商参与欧盟电信网络?... 【文/观察者网 熊超然】当地时间5月27日,彭博社援引知情人士报道称,德国和西班牙正带头反对欧盟委员...
男子为方便上下班两次拆除路中隔... 道路中央隔离护栏是规范行车秩序、守护出行安全的重要公共设施,但是有人为了一己私利,故意破坏交通设施,...
女子称车祸住院遭男医生侵犯,警... 极目新闻记者 马浩然近日,河北的王女士向极目新闻反映,今年3月,她开车经过辽宁葫芦岛时,在高速遭遇汽...
美军的“眼中钉”,伊朗岸舰导弹... 澎湃新闻特约撰稿 邰丰顺据中国新闻社报道,当地时间5月25日,美军中央司令部称,美军在伊朗南部实施了...
张雪峰因病去世,其江苏省人大代... 5月27日,江苏省人民代表大会常务委员会发布公告:江苏省人民代表大会常务委员会公告由无锡市选出的陈大...
电热水器一加热就跳闸 可能跟安装电热水器有关,如果是家里安装电热水器,最好要找专业人士,安装不仔细或者是安装不到位,比如在...
家里电热水器通电就跳闸 这种情况可能是电热水器漏电,解决方法建议检测电热水器加热管是否漏电、温控器有无问题,发现问题及时处理...