1.去微信开放平台注册,获取 appid 和 appsecret , 并设置回调的在线域名 等
2.付300元进行开发者资质认证,微信才会给你接口权限
3.在登陆网站下建两个 PHP 文件
4.好了 开始写代码
一 . wx.php 调取微信提供的二维码(可嵌入登录页面),参数参考文档
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
<title>微信登录</title>
<!-- 网站内嵌二维码微信登录 -->
<script type="text/javascript" src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
</head>
<body >
<div id="login_container"></div>
<script type="text/javascript">
<?php $rand=(1000,9999);session_start(); $_SESSION["wx_rand"]=$rand;?>//存入 session 在回调页面与微信返回的 state 比对 ,防攻击
var obj = new WxLogin({
self_redirect:true,
id:"login_container", //第三方页面显示二维码的容器id
appid: "wx6e45200f1aebf0c4",
scope: "snsapi_login", //应用授权作用域
redirect_uri: encodeURIComponent("http://www_callback.php"),//回调地址
state: <? echo $rand;?>,
style: "black",
href:"data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30NCi5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0NCi5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9"//自定义样式链接
});
</script>
</body>
</html>"
二.wx_callback.php 接收微信返回的参数
<?php
header("Content-Type: text/html;charset=utf-8");
session_start();
$info=$_GET;
$code = $_GET['code'];
$state = $_GET['state'];
$rand=$_SESSION["wx_rand"]
//扫码后同意授权 code 有值,判断 rand 是否异常
if ($code=='' && $rand!==$state) {
exit();
}else{
$appid = ''; //自己的id和秘钥
$appsecret = '';
//通过code获取access_token
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url),true);
$r_token=$token['refresh_token'];
//刷新或续期access_token
$refresh_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$r_token;
$refresh_token = json_decode(file_get_contents($refresh_token_url),true);
$access_token=$refresh_token['access_token'];
$openid=$refresh_token['openid'];
//检验授权凭证(access_token)是否有效 有效期为 2小时
$verify_access_token_url='https://api.weixin.qq.com/sns/auth?access_token='.$access_token.'&openid='.$openid;
$res = json_decode(file_get_contents($verify_access_token_url),true);
//获取 unionid
if ($res['errcode']==0 && $res['errmsg']== ok) {
$user_info_url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$user_info = json_decode(file_get_contents( $user_info_url),true);
//var_dump($user_info);exit();
$unionid=$user_info['unionid'];//unionid为唯一,可区分用户,绑定unionid就可以进行登录了
{
}
?>
问题:登录成功自动跳转时,发现展示页面被 iframe框架套住
解决:
echo "<script>top.location.href='xxx.php</script>";
即可