1. 前端(html)
<button onclick="getcode()">一键微信登录</button>
<script>
function getcode(){
location.href="{:url('/getcode')}";
}
</script>
2. 后端PHP
<?php
namespace app\index\controller;
use app\model\Users;
use think\facade\Config;
use think\facade\Session;
/**
* 登录
*/
class Login extends Common
{
private $appid = '';
private $appsecret = '';
private $redirect_uri = 'http://域名/get_userinfo';
/**
* @return void
* 初始化参数
*/
public function initialize()
{
parent::initialize();
$this->appid = config('weixin.appid');
$this->appsecret = config('weixin.appsecret');
}
/**
* 登录页
*/
public function login() {
return view();
}
/**
* 微信登录 获取code
*/
public function getcode(){
$code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".urlencode($this->redirect_uri)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
$this->redirect($code_url);
}
/**
* 微信登录 获取openid以及用户信息
*/
public function get_userinfo(){
//获取code
$code = $this->getinput('code');
//获取access_token openid
$return_data = json_decode($this->curl_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code"),true);
$access_token = $return_data['access_token'];
$openid = $return_data['openid'];
//查询是否已绑定
$users_id = Users::where('openid',$openid)->value('users_id');
if($users_id){
//已绑定直接登录 保存session
Session::set('users_id',$users_id);
$this->redirect('/');
}else{
//获取信息
$user_info = json_decode($this->curl_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"),true);
$insert_data = [
'openid'=>$user_info['openid'],
'users_name'=>$user_info['nickname'],
'img_url'=>$user_info['headimgurl']
];
//新增
$insert_status = Users::create($insert_data);
if (!$insert_status){
$this->error('绑定失败','/login');
}
//保存session
Session::set('users_id',$insert_status->id);
$this->redirect('/');
}
}
/**
* 远程获取
*/
public function curl_get_contents($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
微信登录步骤
1. 根据appid 获取code
2. 根据code 获取 access_token openid
3.检测access_token 是否有效。 无效刷新access_token、
4. 根据access_token openid 拉去用户信息