allocatr/application/services/WorkerService.php
2025-04-01 20:56:11 +08:00

141 lines
3.7 KiB
PHP

<?php
namespace app\services;
use app\common\library\Token;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\MiniProgram\Application;
class WorkerService extends BaseService
{
/**
* 绑定手机号
* @param string $code
* @param string $vendorToken
*/
public function bindPhoneNumber(string $code, string $vendorToken)
{
$phone = $this->getPhoneNumber($code);
$worker = $this->getWorkerService()->getByTel($phone);
$this->tryBindPhoneNumber($worker);
$tokenData = Token::get($vendorToken);
if (!$tokenData) {
$this->apiError('vendor_token 无效');
}
$workerVendor = $this->getWorkerVendorModel()->find($tokenData['user_id']);
if ($workerVendor->worker_id) {
$this->apiError('绑定失败,该微信已绑定手机号');
}
//绑定手机号
$workerVendor->worker_id = $worker->id;
$workerVendor->save();
Token::delete($vendorToken);
return $worker->id;
}
/**
* 微信登录
* @param string $code
* @return array
*/
public function login(string $code)
{
$app = $this->getMiniProgramApp();
try {
$info = $app->auth->session($code);
} catch (InvalidConfigException $e) {
$this->apiError('登录失败', $e);
}
if (isset($info['errcode']) && $info['errcode'] !== 0) {
$this->apiError('登录失败', 0, $info);
}
$workerVendor = $this->getWorkerVendorService()->getVendorByOpenid($info['openid']);
//创建
if (empty($workerVendor)) {
try {
$this->getWorkerVendorService()->createWechatMpVendor($info['openid']);
} catch (\Exception $e) {
$this->apiError('登录失败', $e, $info);
}
$workerVendor = $this->getWorkerVendorService()->getVendorByOpenid($info['openid']);
}
return $workerVendor->toArray();
}
/**
* 获取小程序 App
* @return Application
*/
private function getMiniProgramApp(): Application
{
$config = [
'app_id' => config('mini_program.app_id'),
'secret' => config('mini_program.secret'),
];
return Factory::miniProgram($config);
}
/**
* 解密微信手机号
* @param string $code
* @return mixed
*/
public function getPhoneNumber(string $code)
{
//getPhoneNumber 方法通过魔术方法 __call 获取
$phoneInfo = $this->getMiniProgramApp()->getPhoneNumber($code);
if (empty($phoneInfo)) {
$this->apiError('获取手机号失败', 0, $phoneInfo);
}
if ($phoneInfo['errcode'] !== 0) {
$this->apiError('获取手机号失败', 0, $phoneInfo);
}
return $phoneInfo['phone_info']['phoneNumber'];
}
/**
* 通过手机号查询师傅信息
* @param string $phone
*/
private function getByTel(string $phone)
{
return $this->getWorkerModel()->where('tel', $phone)->find();
}
/**
* 尝试绑定手机号
* @param $worker
* @return true
*/
private function tryBindPhoneNumber($worker)
{
if (empty($worker)) {
$this->apiError('绑定失败,该手机号未注册');
}
if ($worker->status === 0) {
$this->apiError('绑定失败,您的账号不可用');
}
$workerVendor = $this->getWorkerVendorService()->getByWorkerIdAndPlatform($worker->id, 'WechatMp');
if ($workerVendor) {
$this->apiError('绑定失败,当前手机号已被其他微信绑定');
}
return true;
}
}