Initial commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
use app\common\model\Accounts;
|
||||
use app\common\model\User;
|
||||
use EasyWeChat\Factory;
|
||||
use app\common\traits\ServiceTrait;
|
||||
|
||||
class UserService
|
||||
{
|
||||
use ServiceTrait;
|
||||
|
||||
/** @var User */
|
||||
public static $Model = User::class;
|
||||
|
||||
const GENDER_MAP = ['未知', '男', '女'];
|
||||
|
||||
const ROLE_DEV = 'dev'; //开发者
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public static function wxLogin($code)
|
||||
{
|
||||
// 微信配置
|
||||
$wechatConfig = config('common.wechat');
|
||||
$app = Factory::miniProgram($wechatConfig);
|
||||
$result = $app->auth->session($code);
|
||||
if (isset($result['errcode'])) {
|
||||
throw new \Exception('微信登录失败:' . $result['errmsg']);
|
||||
}
|
||||
|
||||
$openid = $result['openid'];
|
||||
$user = self::$Model::where('openid', $openid)->field('id,username,nickname,avatar,role')->find();
|
||||
if (!$user) {
|
||||
// 新用户自动注册
|
||||
$user = new User;
|
||||
$user->openid = $openid;
|
||||
$user->nickname = '微信用户' . mt_rand(10000, 99999);
|
||||
$user->account = new Accounts();
|
||||
$res = $user->together('account')->save();
|
||||
}
|
||||
$account = Accounts::where('user_id', $user->id ?? 0)->find();
|
||||
if (!$account) {
|
||||
$acRes = $user->account()->save([]);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user