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.
|
|
<?php
namespace App\Http\Controllers\Api;
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;
/** * 小程序登录 * 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 = Agent::query()->firstWhere('appid', $appid); //代理商数据
if (!$agent) { return $this->error('找不到该appid相关记录'); }
$code = request()->input('code'); if (!$code) { return $this->error('code参数缺失'); }
$config = config('wechat.mini_program.default'); $config = array_merge($config, [ 'app_id' => $agent['appid'], 'secret' => $agent['appsecret'], ]); $app = Factory::miniProgram($config);
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, ], [ 'nickname' => substr(session_create_id(), 0, 10), '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)]); }}
|