You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.8 KiB
71 lines
1.8 KiB
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Agent;
|
|
use App\Models\User;
|
|
use EasyWeChat\Factory;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
/**
|
|
* 小程序登录
|
|
* Class Login
|
|
* @package App\Http\Controllers\Api
|
|
*/
|
|
class LoginController extends Controller
|
|
{
|
|
public function login()
|
|
{
|
|
$appid = request()->header('appid');
|
|
if (!$appid) {
|
|
return $this->error('appid缺失');
|
|
}
|
|
$agent_id = Agent::where('appid', $appid)->value('id');
|
|
if (!$agent_id) {
|
|
return $this->error('appid无效');
|
|
}
|
|
|
|
$code = request()->input('code');
|
|
if (!$code) {
|
|
return $this->error('Invalid 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);
|
|
}
|
|
|
|
// TODO 登录部分待优化
|
|
$userModel = new User();
|
|
$userModel->firstOrCreate([
|
|
'openid' => $res['openid'],
|
|
'unionid' => $res['unionid'],
|
|
'agent_id' => $agent_id
|
|
], [
|
|
'nickname' => '未设置昵称',
|
|
'avatar' => '/static/images/avatar.png'
|
|
]);
|
|
|
|
//保存session_key
|
|
Cache::put('session_key_' . $userModel->id, $res['session_key']);
|
|
|
|
// TODO 用于测试
|
|
$token_key = md5($userModel->id);
|
|
Cache::put($token_key, 1);
|
|
Cache::put($agent['appid'], $agent['id']);
|
|
// 测试代码结束
|
|
return $this->success(['token' => md5($userModel->id)]);
|
|
}
|
|
}
|