1.wxml
通过按钮触发绑定事件,来授权登录。
<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button type="primary" open-type="getUserInfo" bindtap="login">授权登录</button>
?
2.js
? ? ? ?在后端js页面里面写入。
data: {
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
login() {
undefined
wx.getUserProfile({
undefined,
desc: '用于完善会员资料',
success: (res) => {
undefined
wx.login({
undefined,
success(res) {
undefined
// 判断是否有code
console.log(res.code)
if (res.code) {
undefined
//发起网络请求
wx.request({
undefined,
url: 'http://www.xiao.com/index.php/Wlogin',//填写自己的地址
method: "POST",
data: {
undefined,
code: res.code
},
success(res) {
undefined
console.log(res.data.data)
// 缓存session_key
wx.setStorage({
undefined,
key: "openid",
data: res.data.data.openid
})
// 跳转到成功页面
wx.navigateTo({
undefined,
url:"/pages/me/me"//跳转页面地址
})
}
})
} else {
undefined
console.log('登录失败!' + res.errMsg)
}
}
})
}
})
},
3.后端框架
//微信授权登录
public function WxLogin(Request $request)
{
// 接收code
$code = $request->post("code");
// 读取appid
$appId = "wxa2469ff6402360ff";
// 读取开发密钥
$appSecret = "47732169fb165797f0303f1f781de142";
//向平台换取session_key和open_id
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
// 用curl对接
$headerArray = array("Content-type:application/json;", "Accept:application/json");
$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);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output, true);
return json(['data' => $output]);
}
效果图:
?
|