Skip to content

Commit

Permalink
weapp login
Browse files Browse the repository at this point in the history
  • Loading branch information
liyu001989 committed Aug 31, 2020
1 parent f4328f7 commit fe881bd
Show file tree
Hide file tree
Showing 4 changed files with 828 additions and 250 deletions.
54 changes: 54 additions & 0 deletions app/Http/Controllers/Api/AuthorizationsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Overtrue\Socialite\AccessToken;
use Illuminate\Auth\AuthenticationException;
use App\Http\Requests\Api\AuthorizationRequest;
use App\Http\Requests\Api\WeappAuthorizationRequest;
use App\Http\Requests\Api\SocialAuthorizationRequest;

class AuthorizationsController extends Controller
Expand Down Expand Up @@ -80,6 +81,59 @@ public function socialStore($type, SocialAuthorizationRequest $request)
return $this->respondWithToken($token)->setStatusCode(201);
}

public function weappStore(WeappAuthorizationRequest $request)
{
$code = $request->code;

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

// 如果结果错误,说明 code 已过期或不正确,返回 401 错误
if (isset($data['errcode'])) {
throw new AuthenticationException('code 不正确');
}

// 找到 openid 对应的用户
$user = User::where('weapp_openid', $data['openid'])->first();

$attributes['weixin_session_key'] = $data['session_key'];

// 未找到对应用户则需要提交用户名密码进行用户绑定
if (!$user) {
// 如果未提交用户名密码,403 错误提示
if (!$request->username) {
throw new AuthenticationException('用户不存在');
}

$username = $request->username;

// 用户名可以是邮箱或电话
filter_var($username, FILTER_VALIDATE_EMAIL) ?
$credentials['email'] = $username :
$credentials['phone'] = $username;

$credentials['password'] = $request->password;

// 验证用户名和密码是否正确
if (!auth('api')->once($credentials)) {
throw new AuthenticationException('用户名或密码错误');
}

// 获取对应的用户
$user = auth('api')->getUser();
$attributes['weapp_openid'] = $data['openid'];
}

// 更新用户数据
$user->update($attributes);

// 为对应用户创建 JWT
$token = auth('api')->login($user);

return $this->respondWithToken($token)->setStatusCode(201);
}

public function update()
{
$token = auth('api')->refresh();
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/Api/VerificationCodesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use Illuminate\Auth\AuthenticationException;
use App\Http\Requests\Api\VerificationCodeRequest;
use Illuminate\Auth\AuthenticationException;

class VerificationCodesController extends Controller
{
Expand Down
Loading

0 comments on commit fe881bd

Please sign in to comment.