Laravel 微信小程序后端实现用户登录的示例代码
这篇文章主要介绍了Laravel 微信小程序后端实现用户登录的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
接上篇微信小程序后端搭建:分享:Laravel 微信小程序后端搭建
后端搭建好后第一件事就是用户登录认证,简单实现微信小程序登录认证
1.user 模型
use Laravel\Passport\HasApiTokens; 新增
use HasApiTokens, Notifiable; protected $fillable = [ ‘id’, ‘name’, ‘email’, ‘email_verified_at’, ‘username’, ‘phone’, ‘avatar’,//我用来把微信头像的/0清晰图片,存到又拍云上 ‘weapp_openid’, ‘nickname’, ‘weapp_avatar’, ‘country’, ‘province’, ‘city’, ‘language’, ‘location’, ‘gender’, ‘level’,//用户等级 ‘is_admin’,//is管理员 ];
2. 新增一条路由
//前端小程序拿到的地址:https://域名/api/v1/自己写的接口 Route::group([‘prefix’ => ‘/v1’], function () { Route::post(‘/user/login’, ‘UserController@weappLogin’); });
3. 在 UserController 控制器里新建 function weappLogin (),别忘了 use 这些
use App\User; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage;
写两个 function weappLogin (),avatarUpyun ()
public function weappLogin(Request $request) { $code = $request->code; // 根据 code 获取微信 openid 和 session_key $miniProgram = \EasyWeChat::miniProgram(); $data =
m
i
n
i
P
r
o
g
r
a
m
−
>
a
u
t
h
−
>
s
e
s
s
i
o
n
(
miniProgram->auth->session(
miniProgram−>auth−>session(code); if (isset($data[‘errcode’])) { return $this->response->errorUnauthorized(‘code已过期或不正确’); } $weappOpenid = $data[‘openid’]; $weixinSessionKey = $data[‘session_key’]; $nickname = $request->nickname; $avatar = str_replace(‘/132’, ‘/0’, $request->avatar);//拿到分辨率高点的头像 $country =
r
e
q
u
e
s
t
−
>
c
o
u
n
t
r
y
?
request->country?
request−>country?request->country:‘’; $province =
r
e
q
u
e
s
t
−
>
p
r
o
v
i
n
c
e
?
request->province?
request−>province?request->province:‘’; $city =
r
e
q
u
e
s
t
−
>
c
i
t
y
?
request->city?
request−>city?request->city:‘’; $gender = $request->gender == ‘1’ ? ‘1’ : ‘2’;//没传过性别的就默认女的吧,体验好些 $language =
r
e
q
u
e
s
t
−
>
l
a
n
g
u
a
g
e
?
request->language?
request−>language?request->language:‘’; //找到 openid 对应的用户 $user = User::where(‘weapp_openid’,
w
e
a
p
p
O
p
e
n
i
d
)
−
>
f
i
r
s
t
(
)
;
/
/
没有,就注册一个用户
i
f
(
!
weappOpenid)->first(); //没有,就注册一个用户 if (!
weappOpenid)−>first();//没有,就注册一个用户if(!user) { $user = User::create([ ‘weapp_openid’ => $weappOpenid, ‘weapp_session_key’ => $weixinSessionKey, ‘password’ => $weixinSessionKey, ‘avatar’ =>
r
e
q
u
e
s
t
−
>
a
v
a
t
a
r
?
request->avatar?
request−>avatar?this->avatarUpyun($avatar):‘’, ‘weapp_avatar’ => $avatar, ‘nickname’ => $nickname, ‘country’ => $country, ‘province’ => $province, ‘city’ => $city, ‘gender’ => $gender, ‘language’ => $language, ]); } //如果注册过的,就更新下下面的信息 $attributes[‘updated_at’] = now(); $attributes[‘weixin_session_key’] = $weixinSessionKey; $attributes[‘weapp_avatar’] =
a
v
a
t
a
r
;
i
f
(
avatar; if (
avatar;if(nickname) { $attributes[‘nickname’] = KaTeX parse error: Expected 'EOF', got '}' at position 11: nickname; }̲ if (request->gender) { $attributes[‘gender’] = $gender; } // 更新用户数据
u
s
e
r
−
>
u
p
d
a
t
e
(
user->update(
user−>update(attributes); // 直接创建token并设置有效期 $createToken =
u
s
e
r
−
>
c
r
e
a
t
e
T
o
k
e
n
(
user->createToken(
user−>createToken(user->weapp_openid);
c
r
e
a
t
e
T
o
k
e
n
−
>
t
o
k
e
n
−
>
e
x
p
<
b
s
t
y
l
e
=
"
c
o
l
o
r
:
t
r
a
n
s
p
a
r
e
n
t
"
>
来源
g
a
o
@
d
a
i
!
m
a
.
c
o
m
搞
createToken->token->exp<b style="color:transparent">来源gao@dai!ma.com搞
createToken−>token−>exp<bstyle="color:transparent">来源gao@dai!ma.com搞代^码网ires_at = Carbon::now()->addDays(30); $createToken->token->save(); $token = $createToken->accessToken; return response()->json([ ‘access_token’ => $token, ‘token_type’ => “Bearer”, ‘expires_in’ => Carbon::now()->addDays(30), ‘data’ => KaTeX parse error: Expected 'EOF', got '}' at position 16: user, ], 200); }̲ //我保存到又拍云了,版权归…avatar) {
a
v
a
t
a
r
f
i
l
e
=
f
i
l
e
g
e
t
c
o
n
t
e
n
t
s
(
avatarfile = file_get_contents(
avatarfile=filegetcontents(avatar);
f
i
l
e
n
a
m
e
=
′
a
v
a
t
a
r
s
/
′
.
u
n
i
q
i
d
(
)
.
′
.
p
n
g
−
60
0
′
;
/
/
微信的头像链接我也不知道怎么获取后缀,直接保存成
p
n
g
的了
S
t
o
r
a
g
e
:
:
d
i
s
k
(
′
u
p
y
u
n
′
)
−
>
w
r
i
t
e
(
filename = 'avatars/' . uniqid() . '.png-600';//微信的头像链接我也不知道怎么获取后缀,直接保存成png的了 Storage::disk('upyun')->write(
filename=′avatars/′.uniqid().′.png−600′;//微信的头像链接我也不知道怎么获取后缀,直接保存成png的了Storage::disk(′upyun′)−>write(filename, $avatarfile); $wexinavatar = config(‘filesystems.disks.upyun.protocol’) . ‘😕/’ . config(‘filesystems.disks.upyun.domain’) . ‘/’ . $filename; return $wexinavatar;//返回链接地址 }
微信的头像 / 0
小头像默认 / 132
- 后端上面就写好了,再看下小程序端怎么做的哈,打开小程序的 app.json,添加 “pages/auth/auth”,
{ “pages”: [ “pages/index/index”, “pages/auth/auth”,//做一个登录页面 “pages/logs/logs” ], “window”: { “backgroundTextStyle”: “light”, “navigationBarBackgroundColor”: “#fff”, “navigationBarTitleText”: “WeChat”, “navigationBarTextStyle”: “black” }, “sitemapLocation”: “sitemap.json”, “permission”: { “scope.userLocation”: { “desc”: “你的位置信息将用于小程序位置接口的效果展示” } } }
5. 打开 auth.js
const app = getApp(); Page({ /** * 页面的初始数据 / data: { UserData: [], isClick: false, }, /* * 生命周期函数–监听页面加载 */ onLoad: function(options) { }, login: function(e) { let that=this that.setData({ isClick: true }) wx.getUserInfo({ lang: “zh_CN”, success: response => { wx.login({ success: res => { let data = { code:res.code, nickname: response.userInfo.nickName, avatar: response.userInfo.avatarUrl, country: response.userInfo.country ? response.userInfo.country : ‘’, province: response.userInfo.province ? response.userInfo.province : ‘’, city: response.userInfo.city ? response.userInfo.city : ‘’, gender: response.userInfo.gender ? response.userInfo.gender : ‘’, language: response.userInfo.language ? response.userInfo.language : ‘’, } console.log(data) app.globalData.userInfo = data; wx.request({ url: ‘你的后端地址’,//我用的valet,http://ak.name/api/v1/user/login method: ‘POST’, data: data, header: { ‘Content-Type’: ‘application/x-www-form-urlencoded’ }, success: function (res) { console.log(res) if (res.statusCode != ‘200’) { return false; } wx.setStorageSync(‘access_token’, res.data.access_token) wx.setStorageSync(‘UserData’, res.data.data ? res.data.data : ‘’) wx.redirectTo({ url: ‘/pages/index/index’, }) }, fail: function (e) { wx.showToast({ title: ‘服务器错误’, duration: 2000 }); that.setData({ isClick: false }) }, }); } }) }, fail: function (e) { that.setData({ isClick: false }) }, }) } })
6. 打开 auth.wxml
微信登录
以上就是Laravel 微信小程序后端实现用户登录的示例代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!