最近做一个网站需要用到微信第三方授权,这里记录一下。
一.准备
要去微信开放平台认证,认证成功后在开放平台的管理中心选择网站应用点击创建网站应用,按照微信的要求填写好即可等待审核大约7个工作日左右,审核通过即可开发。
二.开发
新建一个Wechat.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| namespace app\index\controller; class Wechat { public function __construct() { $this->AppID = '微信的Appid'; $this->AppSecret = '微信的AppSecret'; $this->callback = '回调地址'; } public function index() { $state = '3d6be0a4035d839573b04816624a415e';//这个可不用 $callback = urlencode($this->callback); $url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->AppID."&redirect_uri=".$callback."&response_type=code&scope=snsapi_login&state=".$state."#wechat_redirect"; return redirect($url); } }
|
这样就可以跳转到微信扫描登陆页面了,接下来就是回调接受值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| /** *微信授权回调 **/ public function WxCallback() { $code = input('code'); $acctoken = $this->getAccessToken($code); $userinfo = $this->getUserInfo($acctoken['openid'],$acctoken['access_token']); //这个$userinfo里面就有用户的信息 if($userinfo){ //对用户进行操作 } } /** *获取accesstoken **/ public function getAccessToken($code) { $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->AppID."&secret=".$this->AppSecret."&code={$code}&grant_type=authorization_code"; $array=(array)json_decode($this->curlGet($url)); return $array; } //获取用户信息 public function getUserInfo($openid,$access_token) { $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN "; $array=(array)json_decode($this->curlGet($url)); return $array; } //curl请求 private function curlGet($url) { $ch = curl_init($url) ; curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回 $userInfo = curl_exec($ch) ; curl_close($ch); return $userInfo; }
|
基本的操作就是这样了,剩下的就是一些常规操作了。
再页面中直接用。
1
| <a href="{:url('Wechat/index')}" class="land oranged" style="line-height: 25px;">登录</a>
|