101 lines
2.6 KiB
PHP
101 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\User;
|
|
use Auth;
|
|
use Illuminate\Http\Request;
|
|
|
|
class AuthController extends Controller
|
|
{
|
|
|
|
public function login_dd(Request $request)
|
|
{
|
|
$code = $request->code;
|
|
|
|
if (!$code) {
|
|
return $this->failed('Must need CODE');
|
|
}
|
|
|
|
$user = User::updateOrCreate(
|
|
['openid' => $code],
|
|
['session_key' => '$session_key']
|
|
);
|
|
|
|
$token = Auth::guard('api')->login($user);
|
|
return $this->success($this->withToken($token));
|
|
|
|
}
|
|
|
|
/**
|
|
* 登录认证
|
|
* @Author:<C.Jason>
|
|
* @Date:2019-04-15T09:20:16+0800
|
|
* @param Request $request [description]
|
|
* @return [type] [description]
|
|
*/
|
|
public function login(Request $request)
|
|
{
|
|
$code = $request->code;
|
|
$parent_id = $request->parent_id ?? 0;
|
|
$info = $request->userinfo;
|
|
|
|
if (!$code) {
|
|
return $this->failed('Must need CODE');
|
|
}
|
|
|
|
$app = app('wechat.mini_program');
|
|
$session = $app->auth->session($code);
|
|
|
|
if ($session->errcode == 0) {
|
|
$session_key = $session->session_key;
|
|
$openid = $session->openid;
|
|
$user = User::where('openid', $openid)->first();
|
|
if (empty($info) && !$user) {
|
|
return $this->failed('自动注册时必须传个人信息');
|
|
}
|
|
|
|
$user = User::updateOrCreate(
|
|
[
|
|
'openid' => $openid,
|
|
], [
|
|
'session_key' => $session_key,
|
|
'parent_id' => $parent_id,
|
|
]
|
|
);
|
|
|
|
if (!empty($info)) {
|
|
$user->info()->update([
|
|
'nickname' => $info['nickName'],
|
|
'country' => $info['country'],
|
|
'address' => $info['province'] . ' ' . $info['city'],
|
|
'avatar' => $info['avatarUrl'],
|
|
'sex' => $info['gender'],
|
|
]);
|
|
}
|
|
|
|
$token = Auth::guard('api')->login($user);
|
|
|
|
return $this->success($this->withToken($token));
|
|
} else {
|
|
return $this->failed('未识别的CODE');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 返回登录token
|
|
* @Author:<C.Jason>
|
|
* @Date:2019-04-15T09:20:31+0800
|
|
* @param [type] $token [description]
|
|
* @return [type] [description]
|
|
*/
|
|
protected function withToken($token)
|
|
{
|
|
return [
|
|
'access_token' => $token,
|
|
'access_type' => 'Bearer',
|
|
'expires_in' => Auth::guard('api')->factory()->getTTL() * 60,
|
|
];
|
|
}
|
|
}
|