微信小程静默登录
1.小程序app.js onLaunch()方法中插入(路由进行模板字符串)
// app.js import {config} from "./pages/config/config.js" App({ onLaunch() { let token = wx.getStorageSync('token') if (!token) { wx.login({ success:ret=>{ let code = ret.code wx.request({ url: `${config.baseUrl}api/automatic/gain/token`, method:"POST", data:{code}, success:res=>{ // console.log(res); wx.setStorageSync('token', res.data.data) } }) } }) } } })
2:laravel8 获取接口(经token 生成 openid 和session_key添加入库)
//自动获取token(静默登录) Route::post('automatic/gain/token', [\App\Http\Controllers\Home\LoginController::class, 'automaticGainToken']);
/** * 微信小程序静默登录 *users:闫兵 *Data:2022/4/3 *Time:20:42 * @param Request $request * @return array */ public function automaticGainToken(Request $request) { $code = $request->post('code'); $appid = config('wechat_login.appid'); $secret = config('wechat_login.secret'); $url = sprintf(config('wechat_login.access_token_url'), $appid, $secret, $code); $res = json_decode(file_get_contents($url), true); //返回openid,session_key $getUserInfo = HomeUser::where('openid', $res['openid'])->first(); if ($getUserInfo) { $userId = $getUserInfo->id; } else { //获取openid $create['openid'] = $res['openid']; //session $create['session_key'] = $res['session_key']; // 添加openid 和session $result = HomeUser::create($create); // 获取结果里的id $userId = $result->id; } // 用户id生成token $token = JwtService::createToken($userId); return ['code' => 200, 'msg' => 'ok', 'data' => $token]; }
3:我们将用户id从token中解密出来,利用用户id添加用户信息(前提是路由的使用注册号的中间件才能获取用户id)
主要看下方的授权登录
//后台登录 Route::group(['namespace' => 'Home','middleware'=>'checkApiLogin'], function () { //账号密码登录 Route::post('home/login', [\App\Http\Controllers\Home\LoginController::class, 'login']); //授权登录 Route::post('wechat/login', [\App\Http\Controllers\Home\LoginController::class, 'wechatLogin']); //账号注册(用户账号密码登录) Route::post('home/register', [\App\Http\Controllers\Home\LoginController::class, 'register'])->name('register'); });
4:微信授权登录(将用户信息根据openID修改至数据库)
wx.html 代码:
<text> 账号登录: </text> <l-button type="success" size="large" shape="circle" bindtap="account">账号密码登录</l-button> <text> 微信授权: </text> <l-button type="warning" size="large" shape="circle" bind:tap="login" >微信一键登录</l-button> <image src="/pages/image/img.webp" style="height: 800rpx ; margin: 35px 0px 10px 0px;" ></image>
wx.js
/** * 微信授权 */ login(evt) { //获取token 后台获取用户id var token=wx.getStorageSync('token'); var that = this; // wx.getUserProfile获取用户信息 wx.getUserProfile({ // desc 声明获取用户个人信息后的用途,不超过30个字符 desc: 'desc', success: res => { if (res.userInfo) { /* wx.login 调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)*/ wx.login({ success: ret => { // 获取code var code = ret.code; // 获取用户昵称 var nickName = res.userInfo.nickName; // 获取用户照片 var avatarUrl = res.userInfo.avatarUrl; //性别 var gender = res.userInfo.gender // 发送至php后端 wx.request({ url: `${config.baseUrl}api/wechat/login`, //仅为示例,并非真实的接口地址 data: { code: code, nickName: nickName, avatarUrl: avatarUrl, gender: gender }, method: "POST", header: {token}, // 数据返回json格式 success(res) { if (res.data.code == 200 || res.data.code == 201) { wx.showToast({ title: '登录成功', icon: 'success', duration: 2000 }) // wx.switchTab({ // // 跳转至首页 // url: '/pages/good/good', // }) // 存储token wx.setStorageSync('token', res.data.data) } else { wx.showToast({ title: '登录失败', icon: 'error', duration: 2000 }) } } }) } }) } else { console.log('用户拒绝啦'); } } }) }
laravel 控制器:
/** * 微信授权登录 *users:闫兵 *Data:2022/4/3 *Time:20:37 * @param Request $request * @return array */ public function wechatLogin(Request $request) { // 获取用户id(就是token解密的id); $userId = $request->get('user_id'); // 接受小程序的参数 $params = $request->post(); // 获取appid $appid = config('wechat_login.appid'); // 从微信公众平台获得secret $secret = config('wechat_login.secret'); // 发送请求换取openid和sessionkey $url = sprintf(config('wechat_login.access_token_url'), $appid, $secret, $params['code']); // 暂使用file_get_contents()发送请求,你可以使用CURL扩展的形式实现,获取opid和session_key $res = json_decode(file_get_contents($url), true); $data = [ 'nickname' => $params['nickName'], 'openid' => $res['openid'], 'session_key' => $res['session_key'], 'head' => $params['avatarUrl'], 'gender' => $params['gender'] ]; //根据openid 将参数进行修改 $res = HomeUser::where('openid', $res['openid'])->update($data); if ($res) { return ['code' => 201, 'meg' => '修改成功', 'data' => '']; } else { return ['code' => 200, 'meg' => '修改失败', 'data' => '']; } }
5:用户注册代码(根据当前用户id进行注册添加数据)
wxml:
<form bindsubmit="submit"> <view class="container"> <view class="login-icon"> <image class="login-img" src="/pages/image/2.webp"></image> </view> <view class="login-from"> <!--账号--> <view class="inputView"> <image class="nameImage" src="/pages/image/suername.png"></image> <label class="loginLab">账号</label> <input class="inputText" placeholder="请输入账号" name="username" bindinput="usernameInput" /> </view> <view class="line"></view> <!--密码--> <view class="inputView"> <image class="keyImage" src="/pages/image/password.png"></image> <label class="loginLab">密码</label> <input class="inputText" password="true" placeholder="请输入密码" name="password" bindinput="passwordInput" /> </view> <!--按钮--> <view class="loginBtnView"> <button class="loginBtn" type="primary" form-type="submit">注册</button> </view> </view> </view> </form>
wx.ss
page{ height: 100%; } .container { height: 100%; display: flex; flex-direction: column; padding: 0; box-sizing: border-box; /* background-color: rgb(156, 23, 78) */ } /*登录图片*/ .login-icon{ flex: none; } .login-img{ width: 750rpx; } /*表单内容*/ .login-from { margin-top: 20px; flex: auto; height:100%; } .inputView { /* background-color: #fff; */ line-height: 45px; border-radius:20px; border:1px solid #999999; } /*输入框*/ .nameImage, .keyImage { margin-left: 22px; width: 18px; height: 16px } .loginLab { margin: 15px 15px 15px 10px; color: #545454; font-size: 14px } .inputText { flex: block; float: right; text-align: right; margin-right: 22px; margin-top: 11px; color: #cccccc; font-size: 14px } .line { margin-top: 8px; } /* .line { width: 100%; height: 1px; background-color: #cccccc; margin-top: 1px; } */ /*按钮*/ .loginBtnView { width: 100%; height: auto; /* background-color:#DCDCDC; */ margin-top: 0px; margin-bottom: 0px; padding-bottom: 0px; } .loginBtn { width: 90%; margin-top: 40px; border-radius:10px; }
wx.js
submit(e) { //获取token 后台获取用户id let token = wx.getStorageSync('token'); // 用户名 let username = e.detail.value.username; //密码 let password = e.detail.value.password; if (username == '') { wx.showToast({ title: '请填写用户名', icon: 'success', duration: 2000 }) return false } else if (password == '') { wx.showToast({ title: '请填写密码', icon: 'success', duration: 2000 }) return false } else { wx.request({ url: `${config.baseUrl}api/home/register`, //仅为示例,并非真实的接口地址 data: { username, password }, header: { token }, method: "POST", success: res => { if (res.data.code == 200) { wx.showToast({ title: '注册成功', icon: 'success', duration: 2000, success:function(){ console.log('跳转至首页'); } }) } } }) } },
laravel 控制器:
/** * 用户注册 *users:闫兵 *Data:2022/4/7 *Time:20:11 * @param Request $request */ public function register(Request $request) { // 接受参数 $params = $request->post(); $params['password'] = md5($params['password']); // 用户id $userId = $request->get('user_id'); // 验证 $validator = Validator::make($request->all(), [ 'username' => 'required', 'password' => 'required', ]); if ($validator->fails()) { return ['code' => 500, 'msg' => $validator->errors()->first()]; } // 进行添加数据,提示用户注册成功。跳转至用户登录页面 $data = [ 'account' => $params['username'], 'password' => $params['password'] ]; //进行查询 $result = HomeUser::find($userId); // 没有就进行添加 if (!$result){ HomeUser::where('id',$userId)->insertGetId($data); return ['code' => 200, 'meg' => '注册成功', 'data' => '']; }else{ // 有就进行修改 HomeUser::where('id',$userId)->update($data); return ['code' => 200, 'meg' => '注册成功', 'data' => '']; } }
6:用户账号密码登录代码:
wxml:
<form bindsubmit="submit"> <view class="container"> <view class="login-icon"> <image class="login-img" src="/pages/image/1.webp"></image> </view> <view class="login-from"> <!--账号--> <view class="inputView"> <image class="nameImage" src="/pages/image/suername.png"></image> <label class="loginLab">账号</label> <input class="inputText" placeholder="请输入账号" name="username" bindinput="usernameInput" /> </view> <view class="line"></view> <!--密码--> <view class="inputView"> <image class="keyImage" src="/pages/image/password.png"></image> <label class="loginLab">密码</label> <input class="inputText" password="true" placeholder="请输入密码" name="password" bindinput="passwordInput" /> </view> <!--按钮--> <view class="loginBtnView"> <button class="loginBtn" type="primary" form-type="submit">登录</button> <button class="loginBtn" type="primary" form-type="submit">密码找回</button> </view> </view> </view> </form>
wx.ss
page{ height: 100%; } .container { height: 100%; display: flex; flex-direction: column; padding: 0; box-sizing: border-box; /* background-color: rgb(156, 23, 78) */ } /*登录图片*/ .login-icon{ flex: none; } .login-img{ width: 750rpx; } /*表单内容*/ .login-from { margin-top: 20px; flex: auto; height:100%; } .inputView { /* background-color: #fff; */ line-height: 45px; border-radius:20px; border:1px solid #999999; } /*输入框*/ .nameImage, .keyImage { margin-left: 22px; width: 18px; height: 16px } .loginLab { margin: 15px 15px 15px 10px; color: #545454; font-size: 14px } .inputText { flex: block; float: right; text-align: right; margin-right: 22px; margin-top: 11px; color: #cccccc; font-size: 14px } .line { margin-top: 8px; } /* .line { width: 100%; height: 1px; background-color: #cccccc; margin-top: 1px; } */ /*按钮*/ .loginBtnView { width: 100%; height: auto; /* background-color:#DCDCDC; */ margin-top: 0px; margin-bottom: 0px; padding-bottom: 0px; } .loginBtn { width: 90%; margin-top: 40px; border-radius:10px; }
wx,js
submit(e) { //获取token 后台获取用户id let token = wx.getStorageSync('token'); // 用户名 let username = e.detail.value.username; //密码 let password = e.detail.value.password; if (username == '') { wx.showToast({ title: '请填写用户名', icon: 'success', duration: 2000 }) return false } else if (password == '') { wx.showToast({ title: '请填写密码', icon: 'success', duration: 2000 }) return false } else { wx.request({ url: `${config.baseUrl}api/home/login`, //仅为示例,并非真实的接口地址 data: { username, password }, header: { token }, method: "POST", success: res => { if (res.data.code == 500) { wx.showModal({ title: '尊敬的用户', content: '请先进行注册', success: function (res) { if (res.confirm) { wx.navigateTo({ url: '/pages/register/register', }) return } } }) }else if(res.data.code==501){ wx.showToast({ title: res.data.meg, icon: 'error', duration: 2000 }) }else if(res.data.code==200){ wx.showToast({ title: res.data.meg, icon: 'success', duration: 2000, success:function () { console.log('跳转至首页'); } }) }else{ wx.showToast({ title:'出错喽!!', icon: 'error', duration: 2000, }) } } }) } }
laravel8 控制器:
/** * 账号登录 *users:闫兵 *Data:2022/4/3 *Time:20:38 * @param Request $request * @return array|string|null */ public function login(Request $request) { $params = $request->post(); // 验证 $validator = Validator::make($request->all(), [ 'username' => 'required', 'password' => 'required', ]); if ($validator->fails()) { return ['code' => 500, 'msg' => $validator->errors()->first()]; } // 查看数据库是否有当前的用户 如果有进行登录成功,如果没有就提示用户进行注册 $userinfo = HomeUser::where('account', $params['username'])->first(); if (!$userinfo) { return ['code' => 500, 'meg' => '没有当前的用户', 'data' => '']; } elseif ($userinfo['account'] != $params['username']) { return ['code' => 501, 'meg' => '用户账号不正确', 'data' => '']; } elseif ($userinfo['password'] != md5($params['password'])) { return ['code' => 501, 'meg' => '用户密码不正确', 'data' => '']; } else { return ['code' => 200, 'meg' => '登录成功', 'data' => '']; } }
7:表结构:
CREATE TABLE `home_users` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id', `password` char(32) DEFAULT NULL COMMENT '密码', `account` varchar(100) DEFAULT NULL COMMENT '账号', `nickname` varchar(32) DEFAULT NULL COMMENT '昵称', `openid` varchar(32) DEFAULT NULL COMMENT 'openid', `session_key` varchar(64) DEFAULT NULL COMMENT 'session_key', `tel` varchar(16) DEFAULT NULL COMMENT '手机号', `head` varchar(200) DEFAULT NULL COMMENT '头像', `gendor` tinyint(1) DEFAULT NULL COMMENT '性别', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='前台用户表';
8:如果增加密码修改,就获取用户手机号进行修改密码