Browse Source

优化登录相关逻辑及相关提示信息

dev
李可松 5 years ago
parent
commit
33ad66726e
  1. 34
      app/Http/Controllers/Api/LoginController.php

34
app/Http/Controllers/Api/LoginController.php

@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Illuminate\Support\Facades\Cache;
/**
@ -19,42 +20,43 @@ class LoginController extends Controller
{
$appid = request()->header('appid');
if (!$appid) {
return $this->error('appid缺失');
return $this->error('appid参数缺失');
}
$agent_id = Agent::where('appid', $appid)->value('id');
if (!$agent_id) {
return $this->error('appid无效');
$agent = Agent::query()->firstWhere('appid', $appid); //代理商数据
if (!$agent) {
return $this->error('找不到该appid相关记录');
}
$code = request()->input('code');
if (!$code) {
return $this->error('Invalid code!');
return $this->error('code参数缺失');
}
$agent = Agent::select(['id', 'appid', 'appsecret'])->find($agent_id); //代理商数据
$config = config('wechat.mini_program.default');
$config = array_merge($config, [
'app_id' => $agent['appid'],
'secret' => $agent['appsecret'],
]);
$app = Factory::miniProgram($config);
$res = $app->auth->session($code);
if (!isset($res['errcode']) || $res['errcode'] != 0 || empty($res['openid']) || empty($res['unionid'])) {
$msg = $res['errcode'] ? $res['errcode'] . ': ' : '';
$msg .= $res['errmsg'] ?? '登录失败';
return $this->error($msg);
try {
$res = $app->auth->session($code);
if (!empty($res['errcode']) || empty($res['openid']) && empty($res['unionid'])) {
$msg = $res['errmsg'] ?? '登录失败';
return $this->error($msg);
}
} catch (InvalidConfigException $e) {
return $this->error($e->getMessage());
}
// TODO 登录部分待优化
$userModel = new User();
$userModel->firstOrCreate([
'openid' => $res['openid'],
'unionid' => $res['unionid'],
'agent_id' => $agent_id
'openid' => $res['openid'] ?? '',
'unionid' => $res['unionid'] ?? '',
'agent_id' => $agent->id,
], [
'nickname' => '未设置昵称',
'nickname' => substr(session_create_id(), 0, 10),
'avatar' => '/static/images/avatar.png'
]);

Loading…
Cancel
Save