1.微信公众平台 '设置与开发'->'公众号设置'->'功能设置'->'网页授权域名'
2.uniapp
<button @click="wechatAuth()"> 点击授权登录</button>
onShow() {
// 调用uni.getLaunchOptionsSync()获取启动参数信息
const launchOptions = uni.getLaunchOptionsSync();
// 获取启动来源及其相关信息
const {
path,
query
} = launchOptions;
// 判断是否存在code参数
if (query && query.code) {
const code = query.code;
var _self = this
_self.oven.get(
'https://cs.vip/api/user/getuserinfoh5', {
code: code,
}, {},
(res) => {
if (res.code == "1") {
uni.setStorageSync('userinfo', res.data);
_self.loginsuccess()
} else {}
},
(e) => {
}
);
}
},
wechatAuth(){
// 替换成你的微信公众号的AppID和授权回调页面URL
const appid = 'AppID';
const redirect_uri = encodeURIComponent('URL');
const scope = 'snsapi_userinfo';
const state = 'STATE';
// 构造授权跳转链接
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
// 在新窗口中打开微信授权页面
window.location.href = authUrl;
},
3.tp5
public function getuserinfoh5(){
$code = $this->request->param('code');
// 设置参数
$params = [
'appid' => 'appid',// 替换
'secret' => 'secret',// 替换
'code' => $code,
'grant_type' => 'authorization_code',
];
// 构建请求 URL
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query($params);
$result = file_get_contents($url);
$data = json_decode($result, true);
$openid = $data['openid'];
$oauth2Url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$openid."&lang=zh_CN";
$result = file_get_contents($oauth2Url);
$getuser = json_decode($result,true);
// 其它逻辑
}