微信扫码登陆/微信公交号 登录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']);
    }
}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...