Skip to content

Commit

Permalink
weapp users store
Browse files Browse the repository at this point in the history
  • Loading branch information
liyu001989 committed Aug 23, 2020
1 parent 140b98c commit 3455b48
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
41 changes: 41 additions & 0 deletions app/Http/Controllers/Api/UsersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,47 @@ public function store(UserRequest $request)
return (new UserResource($user))->showSensitiveFields();
}

public function weappStore(UserRequest $request)
{
// 缓存中是否存在对应的 key
$verifyData = \Cache::get($request->verification_key);

if (!$verifyData) {
abort(403, '验证码已失效');
}

// 判断验证码是否相等,不相等反回 401 错误
if (!hash_equals((string)$verifyData['code'], $request->verification_code)) {
throw new AuthenticationException('验证码错误');
}

// 获取微信的 openid 和 session_key
$miniProgram = \EasyWeChat::miniProgram();
$data = $miniProgram->auth->session($request->code);

if (isset($data['errcode'])) {
throw new AuthenticationException('code 不正确');
}

// 如果 openid 对应的用户已存在,报错403
$user = User::where('weapp_openid', $data['openid'])->first();

if ($user) {
throw new AuthenticationException('微信已绑定其他用户,请直接登录');
}

// 创建用户
$user = User::create([
'name' => $request->name,
'phone' => $verifyData['phone'],
'password' => $request->password,
'weapp_openid' => $data['openid'],
'weixin_session_key' => $data['session_key'],
]);

return (new UserResource($user))->showSensitiveFields();
}

public function show(User $user, Request $request)
{
return new UserResource($user);
Expand Down
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
// 小程序登录
Route::post('weapp/authorizations', 'AuthorizationsController@weappStore')
->name('weapp.authorizations.store');
// 小程序注册
Route::post('weapp/users', 'UsersController@weappStore')
->name('weapp.users.store');
// 刷新token
Route::put('authorizations/current', 'AuthorizationsController@update')
->name('authorizations.update');
Expand Down

0 comments on commit 3455b48

Please sign in to comment.