1、配置微信网页授权域名和JS安全接口域名公后台。(域名需备案)
位置:微信公众号后台->公众号设置->功能设置->网页授权域名->JS安全接口域名
微信提示:前端后端分的话,网页授权域名配置前端网址域名,后端配置JS安全接口域名。如果前端后端不分,都配置同样的域名。然后前端通过code传给后端再去获取openid或用户基本信息。
例如:
//我就前后端不分,配置域名为:www.zhenyuya.com
//微信开发者APPID
$appId = 'wx..............';
//微信开发者密码AppSecret
$appSecret = '*****************************';
2、不获取详细信息,只获取openid(不会弹出用户授权)
第一步,跳转微信获取code
//微信开发者APPID
$appId = 'wx..............';
//回调URL
$redirect_uri = urlencode('https://www.zhenyuya.com/code_to_openid.php');
//跳转微信回调到redirect_uri获取code
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("Location:".$url);
第二步,回调回来获取到code换取openid
/**
* @method getWeiXinJson 解析微信信息
* @param url
* @return json 微信解析信息
* @c-author Mr Zhen
*/
function getWeiXinJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
//微信开发者APPID
$appId = 'wx..............';
//微信开发者密码AppSecret
$appSecret = '*****************************';
//微信回调回来的code
$code = $_GET["code"];
//code换取微信openid等信息,也可以将code传给后端,在换取openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
$oauth2 = getWeiXinJson($oauth2Url);
echo $oauth2['openid'];
3、获取用户基本信息包含openid和unionid
第一步,跳转微信用户授权获取code
//微信开发者APPID
$appId = 'wx..............';
//回调URL
$redirect_uri = urlencode('https://www.zhenyuya.com/code_to_userinfo.php');
//跳转微信回调到redirect_uri获取code
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:".$url);
第二步,用code换取用户基本信息
/**
* @method getWeiXinJson 解析微信信息
* @param url
* @return json 微信解析信息
* @c-author Mr Zhen
*/
function getWeiXinJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
//微信开发者APPID
$appId = 'wx..............';
//微信开发者密码AppSecret
$appSecret = '*****************************';
//微信回调回来的code
$code = $_GET["code"];
//获取到code换取信息,如果前后端分离的话,下面这部分应该写在后端
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
$oauth2 = getWeiXinJson($oauth2Url);
$access_token = $oauth2["access_token"];
$openId = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
//获取到用户基本信息
$userInfo = getWeiXinJson($get_user_info_url);
4、如果发现不理解或者有错误,可以留言。谢谢!