<?php

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/oauth2/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/oauth2/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/oauth2/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']);
    }
}

转载于:https://blog.51cto.com/3037704620/1902754

微信扫码登陆/微信公交号 登录PHP 自适应 UnionID统一用户相关推荐

  1. php 微信登陆unionid,微信扫码登陆/微信公交号 登录PHP 自适应 UnionID统一用户

    标签:php<?php namespace Topxia\Component\OAuthClient; /** * 微信扫码登陆 * Enter description here ... * @ ...

  2. java实现PC网站实现微信扫码登陆

    近期,开发一个项目要求PC网站可以进行扫码登陆. 1.前期工作 需要先在微信开放平台进行注册(https://open.weixin.qq.com/),并认证一个网站应用. 点击查看按钮,我们需要记录 ...

  3. 第六天 黑马十次方 用户注册、用户登陆掌握js-cookie、微信扫码登陆、nuxt嵌套路由

    学习目标: ** 完成用户注册功能 完成用户登陆功能,掌握js-cookie的使用 完成微信扫码登陆的功能 完成用户中心嵌套布局,掌握nuxt嵌套路由的使用 ** 1 用户注册 1.1 页面构建 创建 ...

  4. 微信扫码登陆PC端(Vue)(小程序)

    本文章基于Vue项目并且已经开发一个完整上线的微信小程序,制作PC端时实现微信小程序扫码登陆PC端. 一.向后端请求token 1.后端会定时生成并更新的一个token 2.正常的接口请求从后端拿到这 ...

  5. 微信扫码登陆功能(保姆级)

    微信官网文档 https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html 一.申 ...

  6. 微信扫码登陆在chrome浏览器失败

    浏览器会提示:(新版本的浏览器会提示) Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://www. ...

  7. 微信扫码登陆在chrome浏览器被拦截

    浏览器会提示:(新版本的浏览器会提示) Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://www. ...

  8. Android 微信扫码登陆

    最近项目需求中有一个微信扫码登陆功能,即用手机微信扫码功能扫描终端二维码实现登陆的功能 随即打开微信开发者文档查看,不亏为官方,简洁明了,看得我是一脸懵逼,踩了N多坑,太不友好了,言归正传,希望对一些 ...

  9. 账号与微信绑定,微信扫码登陆

    今天完成了pc端微信相关功能的开发,主要是账号与微信绑定,微信扫码登陆. 流程,用户登陆后,在个人中心里有一个和微信绑定界面,用户使用微信扫描后,当前账号和微信账号绑定,可以用来微信扫描登陆. 在登陆 ...

最新文章

  1. python编写爬虫的步骤-如何编写python脚本?教你做简单的爬虫,适合初学者
  2. Ubuntu 安装 Docker
  3. 快速转换vs2008到vs2010
  4. Error: no such column
  5. 【立即报名】解码AI大杀器:华为云GPU+Tensorflow 容器实战
  6. Spring4.x()--Spring整合Jdbc的HelloWorld
  7. 等级保护2.0发布!过了4级的华为云如何帮助你?
  8. 牛客寒假算法基础训练营3
  9. H.264视频质量评价算法(基于偏最小二乘法回归)
  10. GridView常见问题及解决办法
  11. java 需求文档_java 项目需求文档要怎么写?
  12. matlab求导赋值,MATLAB 函数先求导再赋值
  13. 计算机按()的程序进行工作,2016计算机一级考试WPS练习题及答案
  14. 计算机提示应用程序无法启动,告诉你电脑提示应用程序无法正常启动0x000007b怎么办...
  15. idea复制代码空格报错
  16. awk linux 分隔_Linux:批量修改分隔符(awk、BEGIN、FS、OFS、print、tr命令)
  17. python实现mysql多条件查询筛选功能
  18. gluster分布式存储总结与实践
  19. 区块链公司依靠电信主网颠覆汇款行业
  20. 密码(mima)的答案

热门文章

  1. 研发团队来了高颜值的妹子,这结局万万没想到 | 每日趣闻
  2. Go语言中的Struct
  3. 景观格局动态变化分析方法(基于ArcGIS、Fragstats、ENVI、ERDAS、Patch Analysis for ArcGIS) (2011-03-15 08:07:03)...
  4. Microsoft Visual C++ 14.0 is required错误解决办法
  5. SQL语句中不同的连接JOIN
  6. git 基本操作语句
  7. C++中的 Round(),floor(),ceil()
  8. 大数据的应用难题:是否该建立数据公地
  9. /etc/issue、shutdown练习
  10. Spring @SessionAttributes @ModelAttribute