点赞,收藏,消息,分类图标
This commit is contained in:
@@ -7,6 +7,7 @@ use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\common\service\UserService;
|
||||
use app\common\service\WechatService;
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
|
||||
class UserController extends BaseController
|
||||
{
|
||||
@@ -143,51 +144,30 @@ class UserController extends BaseController
|
||||
|
||||
|
||||
|
||||
|
||||
public function wechatLogin1($request)
|
||||
/**
|
||||
* 小程序登录
|
||||
*/
|
||||
public function miniappLogin(Request $request): Response
|
||||
{
|
||||
$loginCode = $request->post('login_code');
|
||||
$phoneCode = $request->post('phone_code');
|
||||
|
||||
if (!$loginCode || !$phoneCode) {
|
||||
return json(['code'=>0, 'msg'=>'缺少参数']);
|
||||
try {
|
||||
$result = $this->service->miniappLogin($request->all());
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 1) code2Session
|
||||
$session = $this->code2Session($loginCode);
|
||||
if (!isset($session['openid'])) {
|
||||
return json(['code'=>0, 'msg'=>'登录失败', 'data'=>$session]);
|
||||
|
||||
/**
|
||||
* 获取手机号
|
||||
*/
|
||||
public function miniappPhoneNumber(Request $request): Response
|
||||
{
|
||||
try {
|
||||
$result = $this->service->miniappPhoneNumber($request->all());
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
|
||||
$openid = $session['openid'];
|
||||
|
||||
// 2) access_token
|
||||
$tokenData = $this->getAccessToken();
|
||||
$token = $tokenData['access_token'];
|
||||
|
||||
// 3) 换手机号
|
||||
$phoneData = $this->getPhoneNumber($token, $phoneCode);
|
||||
|
||||
if (!isset($phoneData['phone_info']['phoneNumber'])) {
|
||||
return json(['code'=>0, 'msg'=>'获取手机号失败', 'data'=>$phoneData]);
|
||||
}
|
||||
|
||||
$phone = $phoneData['phone_info']['phoneNumber'];
|
||||
|
||||
// 4) 写入数据库或登录逻辑
|
||||
// 比如自动注册
|
||||
$user = User::firstOrCreate(['openid'=>$openid], [
|
||||
'phone' => $phone
|
||||
]);
|
||||
|
||||
return json([
|
||||
'code' => 1,
|
||||
'msg' => '登录成功',
|
||||
'data' => [
|
||||
'openid' => $openid,
|
||||
'phone' => $phone,
|
||||
'token' => md5($openid.time()), // 你自己的登录 token
|
||||
]
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user