微信授权登录PC端
微信授权登录PC端,原创来自于梦雪。QQ群:324098841。官网 www.php127.com 论坛 www.flash127.com
//微信登录的三次握手,开始
function get_url($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function get_token($appid,$appsecret,$code){
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$result=get_url($url);
$res=json_decode($result,true);
return $res;
}
function get_userinfo($appid,$appsecret,$code){
$res=get_token($appid,$appsecret,$code);
$access_token=$res['access_token'];
$openid=$res['openid'];
$userinfo=get_url("https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN");
$userinfo=json_decode($userinfo,true);
return $userinfo;
}
//微信登录的三次握手,结束
<?php
namespace Home\Controller;
class ThirdLoginController extends ba
seController
{
public function callback(){
$code=$_GET['code'];
$appid='***********';//你们公司的appid
$appsecret=C('AppSecret');//你们公司的AppSecret,建议写在配置文件中调用。
$state=$_GET['state'];
if($code){
$uinfo=get_userinfo($appid,$appsecret,$code);//使用三次握手方法获取客户信息
$name=$uinfo['unionid'];//客户唯一标识
$nickname=$uinfo['nickname'];//客户昵称
$where['name']=$name;
$customer_select=M('customer')->where($where)->find();//查看客户唯一标识是否存在
if(empty($customer_select)){
$data['name']=$name;
$data['nickname']=$nickname;
$add=M('customer')->add($data);
if($add){
$loginUser = M('customer')->where($where)->find();
$_SESSION['isLogin']=1;
$_SESSION['uid']=$loginUser['uid'];
$_SESSION['name']=$loginUser['name'];
$this->assign('customer', $_SESSION['uid']);
echo '<script>'.'window.location.href="./../Index/index"'.'</script>';
}else{
echo '<script>'.'alert("'.'登录失败'.'");'.'window.location.href="../../Login/index"'.'</script>';
}
}
elseif (!empty($customer_select)) {
$loginUser = M('customer')->where($where)->find();
$_SESSION['isLogin']=1;
$_SESSION['uid']=$loginUser['uid'];
$_SESSION['name']=$loginUser['name'];
$this->assign('customer', $_SESSION['uid']);
echo '<script>'.'window.location.href="./../Index/index"'.'</script>';
}
}
}
}
到此微信登录结束,需要你把自己的数据库表名,字段名进行更改。逻辑方法为原创,三次握手方法来自于梦雪!!
博客地址:antionzhou.cn,欢迎转载和使用!