feat: 用户端与师傅端双小程序架构解耦,新增师傅独立认证及超时自动关单机制
1. 账号体系与数据库解耦: - 师傅表 fa_master 解除对 fa_user.id 的外键依赖,升级为独立认证账号主表; - 新增师傅端独立支撑表:fa_master_security、fa_master_token、fa_master_wechat、fa_master_agreement_read; - 新增工单超时未接单自动关闭与原路退款配置(order_unaccepted_close_days)。 2. 服务端(Server): - 新增师傅端独立 API 控制器与认证库(MasterAuth, MasterBase, MasterMessage, MasterSecurity, MasterToken); - WxLogin 支持双小程序端(user/master)独立换取 session_key、openid 与 access_token; - 新增控制台调度命令 php think order:autoclose,支持订单超时自动关闭与售后退款闭环; - 修复 PHP 8.5 兼容性问题(Request.php 的 (bool) 强制转换); - 系统业务配置全面收敛至数据库 fa_config 及 site.php。 3. 小程序端: - yjyf-app(用户端):彻底剥离师傅端路由、组件及静态资源,增加隐私授权弹窗与评价模块; - yjyf-master-app(师傅端):全新独立微信小程序工程(wx140d90ceda786107),实现工作台、接单大厅、资质认证、工单协同与钱包提现完整闭环。
这个提交包含在:
@@ -178,7 +178,7 @@ class AgreementService
|
||||
/**
|
||||
* 按前端请求的 type 读取单条启用协议(API 使用,含变更首看高亮判断)
|
||||
*/
|
||||
public static function getByType(string $type, int $userId = 0): ?array
|
||||
public static function getByType(string $type, int $subjectId = 0, string $side = 'user'): ?array
|
||||
{
|
||||
$rawType = trim($type);
|
||||
$code = self::canonicalCode($rawType);
|
||||
@@ -217,8 +217,8 @@ class AgreementService
|
||||
$hasDiff = ($revision > 1 && trim($diffContent) !== '');
|
||||
$showDiff = false;
|
||||
if ($hasDiff) {
|
||||
if ($userId > 0) {
|
||||
$readRevision = self::getUserReadRevision($userId, $code);
|
||||
if ($subjectId > 0) {
|
||||
$readRevision = self::getUserReadRevision($subjectId, $code, $side);
|
||||
$showDiff = ($readRevision < $revision);
|
||||
} else {
|
||||
// 未登录游客由前端结合本机已阅修订版本进行首看门控
|
||||
@@ -270,18 +270,25 @@ class AgreementService
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询登录用户已查看过的协议最高修订序号
|
||||
* 查询登录用户或师傅已查看过的协议最高修订序号
|
||||
*/
|
||||
public static function getUserReadRevision(int $userId, string $code): int
|
||||
public static function getUserReadRevision(int $subjectId, string $code, string $side = 'user'): int
|
||||
{
|
||||
if ($userId <= 0 || $code === '') {
|
||||
if ($subjectId <= 0 || $code === '') {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
$rev = Db::name('agreement_read')
|
||||
->where('user_id', $userId)
|
||||
->where('agreement_code', $code)
|
||||
->value('read_revision');
|
||||
if ($side === 'master') {
|
||||
$rev = Db::name('master_agreement_read')
|
||||
->where('master_id', $subjectId)
|
||||
->where('agreement_code', $code)
|
||||
->value('read_revision');
|
||||
} else {
|
||||
$rev = Db::name('agreement_read')
|
||||
->where('user_id', $subjectId)
|
||||
->where('agreement_code', $code)
|
||||
->value('read_revision');
|
||||
}
|
||||
return $rev ? (int)$rev : 0;
|
||||
} catch (\Throwable $e) {
|
||||
return 0;
|
||||
@@ -289,9 +296,9 @@ class AgreementService
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记登录用户已首次查看当前变更版协议,防止后续打开重复高亮
|
||||
* 标记登录用户或师傅已首次查看当前变更版协议,防止后续打开重复高亮
|
||||
*/
|
||||
public static function markUserRead(int $userId, string $type, int $revision = 0): array
|
||||
public static function markUserRead(int $subjectId, string $type, int $revision = 0, string $side = 'user'): array
|
||||
{
|
||||
$code = self::canonicalCode($type);
|
||||
$currentRev = 1;
|
||||
@@ -305,7 +312,7 @@ class AgreementService
|
||||
}
|
||||
|
||||
$targetRevision = ($revision > 0 && $revision <= $currentRev) ? $revision : $currentRev;
|
||||
if ($userId <= 0) {
|
||||
if ($subjectId <= 0) {
|
||||
return [
|
||||
'recorded' => false,
|
||||
'code' => $code,
|
||||
@@ -315,14 +322,16 @@ class AgreementService
|
||||
|
||||
$now = time();
|
||||
$prefix = (string)Config::get('database.prefix');
|
||||
$table = $prefix . 'agreement_read';
|
||||
$isMaster = ($side === 'master');
|
||||
$table = $prefix . ($isMaster ? 'master_agreement_read' : 'agreement_read');
|
||||
$idCol = $isMaster ? 'master_id' : 'user_id';
|
||||
Db::execute(
|
||||
"INSERT INTO `{$table}` (`user_id`, `agreement_code`, `read_revision`, `read_time`, `createtime`, `updatetime`) "
|
||||
. "VALUES (:uid, :code, :rev, :rtime, :ctime, :utime) "
|
||||
"INSERT INTO `{$table}` (`{$idCol}`, `agreement_code`, `read_revision`, `read_time`, `createtime`, `updatetime`) "
|
||||
. "VALUES (:sid, :code, :rev, :rtime, :ctime, :utime) "
|
||||
. "ON DUPLICATE KEY UPDATE `read_revision` = GREATEST(`read_revision`, VALUES(`read_revision`)), "
|
||||
. "`read_time` = VALUES(`read_time`), `updatetime` = VALUES(`updatetime`)",
|
||||
[
|
||||
'uid' => $userId,
|
||||
'sid' => $subjectId,
|
||||
'code' => $code,
|
||||
'rev' => $targetRevision,
|
||||
'rtime' => $now,
|
||||
@@ -334,7 +343,7 @@ class AgreementService
|
||||
return [
|
||||
'recorded' => true,
|
||||
'code' => $code,
|
||||
'read_revision' => self::getUserReadRevision($userId, $code),
|
||||
'read_revision' => self::getUserReadRevision($subjectId, $code, $side),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use fast\Random;
|
||||
use think\Db;
|
||||
use think\Exception;
|
||||
|
||||
/**
|
||||
* 师傅端独立认证服务(基于 fa_master 与 fa_master_token,完全不依赖 fa_user)
|
||||
*/
|
||||
class MasterAuth
|
||||
{
|
||||
protected static $instance = null;
|
||||
protected $_error = '';
|
||||
protected $_logined = false;
|
||||
protected $_master = null;
|
||||
protected $_token = '';
|
||||
protected $keeptime = 2592000;
|
||||
|
||||
public static function instance()
|
||||
{
|
||||
if (is_null(self::$instance)) {
|
||||
self::$instance = new static();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function id()
|
||||
{
|
||||
return $this->_master ? (int)$this->_master['id'] : 0;
|
||||
}
|
||||
|
||||
public function getMaster()
|
||||
{
|
||||
return $this->_master;
|
||||
}
|
||||
|
||||
public function isLogin()
|
||||
{
|
||||
return $this->_logined;
|
||||
}
|
||||
|
||||
public function getToken()
|
||||
{
|
||||
return $this->_token;
|
||||
}
|
||||
|
||||
public function getError()
|
||||
{
|
||||
return $this->_error;
|
||||
}
|
||||
|
||||
public function setError($error)
|
||||
{
|
||||
$this->_error = (string)$error;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getEncryptPassword($password, $salt = '')
|
||||
{
|
||||
return md5(md5((string)$password) . (string)$salt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Token 初始化师傅登录态
|
||||
*/
|
||||
public function init($token)
|
||||
{
|
||||
if ($this->_logined) {
|
||||
return true;
|
||||
}
|
||||
if ($this->_error) {
|
||||
return false;
|
||||
}
|
||||
$data = MasterToken::get($token);
|
||||
if (!$data) {
|
||||
return false;
|
||||
}
|
||||
$masterId = (int)$data['master_id'];
|
||||
if ($masterId <= 0) {
|
||||
$this->setError('请先登录师傅账号');
|
||||
return false;
|
||||
}
|
||||
$master = Db::name('master')->where('id', $masterId)->find();
|
||||
if (!$master) {
|
||||
$this->setError('师傅账号不存在');
|
||||
return false;
|
||||
}
|
||||
if (isset($master['status']) && $master['status'] !== 'normal') {
|
||||
$this->setError('师傅账号已被禁用');
|
||||
return false;
|
||||
}
|
||||
$this->_master = $master;
|
||||
$this->_logined = true;
|
||||
$this->_token = $token;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接登录指定师傅账号(签发独立师傅 Token)
|
||||
*/
|
||||
public function direct($masterId)
|
||||
{
|
||||
$master = Db::name('master')->where('id', (int)$masterId)->find();
|
||||
if (!$master) {
|
||||
$this->setError('师傅账号不存在');
|
||||
return false;
|
||||
}
|
||||
if (isset($master['status']) && $master['status'] !== 'normal') {
|
||||
$this->setError('师傅账号已被禁用');
|
||||
return false;
|
||||
}
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$now = time();
|
||||
$ip = request()->ip();
|
||||
$update = [
|
||||
'prevtime' => $master['logintime'] ?: $now,
|
||||
'logintime' => $now,
|
||||
'loginip' => $ip,
|
||||
'loginfailure' => 0,
|
||||
'updatetime' => $now,
|
||||
];
|
||||
Db::name('master')->where('id', (int)$master['id'])->update($update);
|
||||
$master = array_merge($master, $update);
|
||||
$this->_master = $master;
|
||||
$this->_token = $this->generateToken((int)$master['id']);
|
||||
$this->_logined = true;
|
||||
MasterSecurity::ensure((int)$master['id']);
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
$this->setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号 + 密码注册并登录独立师傅账号(默认 verify_status=draft)
|
||||
*/
|
||||
public function register($mobile, $password)
|
||||
{
|
||||
$mobile = trim((string)$mobile);
|
||||
if (Db::name('master')->where('mobile', $mobile)->find()) {
|
||||
$this->setError('该手机号已注册师傅账号');
|
||||
return false;
|
||||
}
|
||||
$now = time();
|
||||
$ip = request()->ip();
|
||||
$salt = Random::alnum();
|
||||
$encrypt = $this->getEncryptPassword($password, $salt);
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$masterId = (int)Db::name('master')->insertGetId([
|
||||
'mobile' => $mobile,
|
||||
'nickname' => '师傅' . substr($mobile, -4),
|
||||
'realname' => '',
|
||||
'password' => $encrypt,
|
||||
'salt' => $salt,
|
||||
'verify_status' => 'draft',
|
||||
'work_status' => 'off',
|
||||
'status' => 'normal',
|
||||
'level' => 1,
|
||||
'score' => 5.00,
|
||||
'accept_rate' => 100.00,
|
||||
'ontime_rate' => 100.00,
|
||||
'serve_radius' => 10,
|
||||
'money' => 0.00,
|
||||
'frozen_money' => 0.00,
|
||||
'prevtime' => $now,
|
||||
'logintime' => $now,
|
||||
'loginip' => $ip,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
MasterSecurity::ensure($masterId);
|
||||
$this->_master = Db::name('master')->where('id', $masterId)->find();
|
||||
$this->_token = $this->generateToken($masterId);
|
||||
$this->_logined = true;
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
$this->setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
if (!$this->_logined) {
|
||||
$this->setError('尚未登录');
|
||||
return false;
|
||||
}
|
||||
$this->_logined = false;
|
||||
MasterToken::delete($this->_token);
|
||||
$this->_master = null;
|
||||
$this->_token = '';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改登录密码
|
||||
*/
|
||||
public function changepwd($newpassword, $oldpassword = '', $ignoreOld = false)
|
||||
{
|
||||
if (!$this->_logined || !$this->_master) {
|
||||
$this->setError('请先登录');
|
||||
return false;
|
||||
}
|
||||
$masterId = (int)$this->_master['id'];
|
||||
if (!$ignoreOld) {
|
||||
if ($this->_master['password'] !== $this->getEncryptPassword($oldpassword, $this->_master['salt'])) {
|
||||
$this->setError('原登录密码不正确');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Db::startTrans();
|
||||
try {
|
||||
$salt = Random::alnum();
|
||||
$encrypted = $this->getEncryptPassword($newpassword, $salt);
|
||||
Db::name('master')->where('id', $masterId)->update([
|
||||
'loginfailure' => 0,
|
||||
'password' => $encrypted,
|
||||
'salt' => $salt,
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
MasterToken::clear($masterId);
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
$this->setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新当前内存缓存的师傅行
|
||||
*/
|
||||
public function reload()
|
||||
{
|
||||
if ($this->id() > 0) {
|
||||
$this->_master = Db::name('master')->where('id', $this->id())->find();
|
||||
}
|
||||
return $this->_master;
|
||||
}
|
||||
|
||||
private function generateToken($masterId)
|
||||
{
|
||||
$maxAttempts = 5;
|
||||
for ($i = 0; $i < $maxAttempts; $i++) {
|
||||
$token = Random::uuid();
|
||||
if (MasterToken::set($token, $masterId, $this->keeptime)) {
|
||||
return $token;
|
||||
}
|
||||
}
|
||||
throw new Exception('生成师傅登录令牌失败');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 师傅端独立安全凭证校验与防暴力破解锁定(读写 fa_master_security 与 fa_master)
|
||||
*/
|
||||
class MasterSecurity
|
||||
{
|
||||
public static function ensure($masterId)
|
||||
{
|
||||
$prefix = config('database.prefix');
|
||||
if (!preg_match('/^[A-Za-z0-9_]+$/', $prefix)) {
|
||||
throw new \RuntimeException('数据库配置错误');
|
||||
}
|
||||
Db::execute("INSERT IGNORE INTO `{$prefix}master_security` (`master_id`) VALUES (?)", [(int)$masterId]);
|
||||
}
|
||||
|
||||
public static function verify($masterId, $kind, $password)
|
||||
{
|
||||
if (!in_array($kind, ['login', 'payment'], true)) {
|
||||
throw new \InvalidArgumentException('验证类型错误');
|
||||
}
|
||||
$masterId = (int)$masterId;
|
||||
$attemptsField = $kind === 'payment' ? 'payment_failed_attempts' : 'failed_attempts';
|
||||
$lockedField = $kind === 'payment' ? 'payment_locked_until' : 'locked_until';
|
||||
|
||||
self::ensure($masterId);
|
||||
Db::startTrans();
|
||||
try {
|
||||
$row = Db::name('master_security')->where('master_id', $masterId)->lock(true)->find();
|
||||
if ((int)$row[$lockedField] > time()) {
|
||||
throw new \RuntimeException('密码错误次数过多,请15分钟后重试');
|
||||
}
|
||||
if ($kind === 'login') {
|
||||
$master = Db::name('master')->field('password,salt')->where('id', $masterId)->find();
|
||||
$correct = $master && $master['password'] !== '' && hash_equals((string)$master['password'], md5(md5($password) . $master['salt']));
|
||||
} else {
|
||||
if ($row['payment_password_hash'] === '') {
|
||||
throw new \RuntimeException('请先在账号安全中设置支付密码');
|
||||
}
|
||||
$correct = password_verify($password, $row['payment_password_hash']);
|
||||
}
|
||||
$failures = $correct ? 0 : (int)$row[$attemptsField] + 1;
|
||||
Db::name('master_security')->where('master_id', $masterId)->update([
|
||||
$attemptsField => $failures >= 5 ? 0 : $failures,
|
||||
$lockedField => $failures >= 5 ? time() + 900 : 0,
|
||||
]);
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
if (!$correct) {
|
||||
throw new \RuntimeException($failures >= 5 ? '密码错误次数过多,请15分钟后重试' : '密码不正确');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Config;
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 师傅端独立 Token 操作类(物理隔离于用户端 fa_user_token,读写 fa_master_token)
|
||||
*/
|
||||
class MasterToken
|
||||
{
|
||||
/**
|
||||
* 计算加密后的 Token
|
||||
*/
|
||||
protected static function encrypt($token)
|
||||
{
|
||||
$config = Config::get('token');
|
||||
$algo = !empty($config['hashalgo']) ? $config['hashalgo'] : 'ripemd160';
|
||||
$key = isset($config['key']) ? (string)$config['key'] : '';
|
||||
return hash_hmac($algo, (string)$token, $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期 Token(每天至多清理一次)
|
||||
*/
|
||||
protected static function gc()
|
||||
{
|
||||
$time = time();
|
||||
$lastGc = cache('master_tokentime');
|
||||
if (!$lastGc || $lastGc < $time - 86400) {
|
||||
cache('master_tokentime', $time);
|
||||
Db::name('master_token')->where('expiretime', '<', $time)->where('expiretime', '>', 0)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入师傅 Token
|
||||
*/
|
||||
public static function set($token, $masterId, $expire = 2592000)
|
||||
{
|
||||
self::gc();
|
||||
$encrypted = self::encrypt($token);
|
||||
$exists = Db::name('master_token')->where('token', $encrypted)->count();
|
||||
if ($exists) {
|
||||
return false;
|
||||
}
|
||||
$expiretime = !is_null($expire) && (int)$expire !== 0 ? time() + (int)$expire : 0;
|
||||
Db::name('master_token')->insert([
|
||||
'token' => $encrypted,
|
||||
'master_id' => (int)$masterId,
|
||||
'createtime' => time(),
|
||||
'expiretime' => $expiretime,
|
||||
]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取师傅 Token 数据
|
||||
*/
|
||||
public static function get($token)
|
||||
{
|
||||
if (!$token) {
|
||||
return [];
|
||||
}
|
||||
$data = Db::name('master_token')->where('token', self::encrypt($token))->find();
|
||||
if (!$data) {
|
||||
return [];
|
||||
}
|
||||
if (!$data['expiretime'] || (int)$data['expiretime'] > time()) {
|
||||
$data['token'] = $token;
|
||||
$data['expires_in'] = $data['expiretime'] ? max(0, (int)$data['expiretime'] - time()) : 365 * 86400;
|
||||
return $data;
|
||||
}
|
||||
self::delete($token);
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 Token 是否属于指定师傅
|
||||
*/
|
||||
public static function check($token, $masterId)
|
||||
{
|
||||
$data = self::get($token);
|
||||
return $data && (int)$data['master_id'] === (int)$masterId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除单个 Token
|
||||
*/
|
||||
public static function delete($token)
|
||||
{
|
||||
if (!$token) {
|
||||
return false;
|
||||
}
|
||||
Db::name('master_token')->where('token', self::encrypt($token))->delete();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除指定师傅全部 Token
|
||||
*/
|
||||
public static function clear($masterId)
|
||||
{
|
||||
if ((int)$masterId <= 0) {
|
||||
return false;
|
||||
}
|
||||
Db::name('master_token')->where('master_id', (int)$masterId)->delete();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 超时未接单订单自动关闭服务
|
||||
*/
|
||||
class OrderAutoCloseService
|
||||
{
|
||||
/** 允许自动关闭的未接单状态集合 */
|
||||
const CLOSEABLE_STATUSES = [
|
||||
OrderStatus::PENDING_PAY,
|
||||
OrderStatus::PENDING_ACCEPT,
|
||||
OrderStatus::QUOTING,
|
||||
];
|
||||
|
||||
/**
|
||||
* 读取后台配置的超时未接单自动关闭天数(开关关闭或天数为 0 表示关闭该功能)
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function getCloseDays()
|
||||
{
|
||||
$switchVal = Db::name('config')->where('name', 'order_unaccepted_close_switch')->value('value');
|
||||
if ($switchVal === null || $switchVal === '') {
|
||||
$switchVal = config('site.order_unaccepted_close_switch');
|
||||
}
|
||||
if ($switchVal !== null && $switchVal !== '' && (int)$switchVal === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$val = Db::name('config')->where('name', 'order_unaccepted_close_days')->value('value');
|
||||
if ($val === null || $val === '') {
|
||||
$val = config('site.order_unaccepted_close_days');
|
||||
}
|
||||
return max(0, (int)$val);
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描并自动关闭超时未接单订单
|
||||
*
|
||||
* @param int $limit 单次最大处理条数
|
||||
* @param int|null $overrideDays 覆盖配置天数(主要用于测试或手动指定)
|
||||
* @return array
|
||||
*/
|
||||
public static function closeExpiredOrders($limit = 100, $overrideDays = null)
|
||||
{
|
||||
$days = $overrideDays !== null ? max(0, (int)$overrideDays) : self::getCloseDays();
|
||||
$result = [
|
||||
'days' => $days,
|
||||
'scanned' => 0,
|
||||
'closed' => 0,
|
||||
'refunded' => 0,
|
||||
'refund_failed' => 0,
|
||||
'details' => [],
|
||||
];
|
||||
|
||||
if ($days <= 0) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$threshold = $now - ($days * 86400);
|
||||
$limit = max(1, (int)$limit);
|
||||
|
||||
$orders = Db::name('order')
|
||||
->whereIn('status', self::CLOSEABLE_STATUSES)
|
||||
->where('master_id', 0)
|
||||
->where('createtime', '>', 0)
|
||||
->where('createtime', '<=', $threshold)
|
||||
->field('id')
|
||||
->order('id asc')
|
||||
->limit($limit)
|
||||
->select();
|
||||
|
||||
$result['scanned'] = count($orders);
|
||||
foreach ($orders as $row) {
|
||||
$itemResult = self::closeSingleOrder((int)$row['id'], $days, $threshold, $now);
|
||||
if ($itemResult['status'] === 'closed') {
|
||||
$result['closed']++;
|
||||
if ($itemResult['refund_state'] === 'success') {
|
||||
$result['refunded']++;
|
||||
} elseif ($itemResult['refund_state'] === 'failed') {
|
||||
$result['refund_failed']++;
|
||||
}
|
||||
}
|
||||
$result['details'][] = $itemResult;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭单笔超时未接单订单:事务内仅做状态流转与本地数据回滚,事务外执行退款与消息通知
|
||||
*
|
||||
* @param int $orderId
|
||||
* @param int $days
|
||||
* @param int $threshold
|
||||
* @param int $now
|
||||
* @return array
|
||||
*/
|
||||
public static function closeSingleOrder($orderId, $days, $threshold, $now)
|
||||
{
|
||||
$orderId = (int)$orderId;
|
||||
$reason = "下单超过{$days}天未有师傅接单,系统自动关闭";
|
||||
$lockedOrder = null;
|
||||
$needRefund = false;
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
|
||||
if (
|
||||
!$lockedOrder
|
||||
|| (int)$lockedOrder['master_id'] !== 0
|
||||
|| !in_array((int)$lockedOrder['status'], self::CLOSEABLE_STATUSES, true)
|
||||
|| !OrderStatus::can((int)$lockedOrder['status'], OrderStatus::CANCELLED)
|
||||
|| (int)$lockedOrder['createtime'] <= 0
|
||||
|| (int)$lockedOrder['createtime'] > $threshold
|
||||
) {
|
||||
Db::rollback();
|
||||
return ['order_id' => $orderId, 'status' => 'skipped', 'refund_state' => 'none'];
|
||||
}
|
||||
|
||||
if (isset($lockedOrder['invoice_status']) && in_array($lockedOrder['invoice_status'], ['wait', 'issued'], true)) {
|
||||
Db::rollback();
|
||||
Log::warning("[OrderAutoCloseService] 订单 #{$orderId} 处于开票流程中,跳过自动关闭");
|
||||
return ['order_id' => $orderId, 'status' => 'skipped', 'refund_state' => 'none'];
|
||||
}
|
||||
|
||||
$fromStatus = (int)$lockedOrder['status'];
|
||||
$updated = Db::name('order')
|
||||
->where('id', $orderId)
|
||||
->where('status', $fromStatus)
|
||||
->where('master_id', 0)
|
||||
->update([
|
||||
'status' => OrderStatus::CANCELLED,
|
||||
'cancel_reason' => mb_substr($reason, 0, 255),
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
if (!$updated) {
|
||||
Db::rollback();
|
||||
return ['order_id' => $orderId, 'status' => 'skipped', 'refund_state' => 'none'];
|
||||
}
|
||||
|
||||
// 退还已占用的优惠券
|
||||
if ((int)$lockedOrder['coupon_id'] > 0) {
|
||||
Db::name('user_coupon')
|
||||
->where('id', (int)$lockedOrder['coupon_id'])
|
||||
->where('user_id', (int)$lockedOrder['user_id'])
|
||||
->where('order_id', $orderId)
|
||||
->where('status', 'used')
|
||||
->update([
|
||||
'status' => 'unused',
|
||||
'use_time' => 0,
|
||||
'order_id' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
// 竞价单将等待中的报价标记为已过期
|
||||
if ($lockedOrder['price_type'] === 'quote') {
|
||||
Db::name('order_quote')
|
||||
->where('order_id', $orderId)
|
||||
->where('status', 'wait')
|
||||
->update(['status' => 'expired']);
|
||||
}
|
||||
|
||||
Db::name('order_log')->insert([
|
||||
'order_id' => $orderId,
|
||||
'status' => OrderStatus::CANCELLED,
|
||||
'remark' => $reason,
|
||||
'operator_type' => 'system',
|
||||
'operator_id' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
|
||||
$needRefund = ((int)$lockedOrder['pay_status'] === 1 && (float)$lockedOrder['pay_amount'] > 0);
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
Log::error("[OrderAutoCloseService] 关闭订单 #{$orderId} 异常:" . $e->getMessage());
|
||||
return [
|
||||
'order_id' => $orderId,
|
||||
'status' => 'error',
|
||||
'refund_state' => 'none',
|
||||
'error' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
|
||||
// 事务外执行原路退款与消息提醒
|
||||
$refundState = 'none';
|
||||
$userId = (int)$lockedOrder['user_id'];
|
||||
$orderNo = (string)$lockedOrder['order_no'];
|
||||
$payAmount = number_format((float)$lockedOrder['pay_amount'], 2, '.', '');
|
||||
|
||||
if ($needRefund) {
|
||||
try {
|
||||
PaymentService::refundOrder($orderId, $reason);
|
||||
PaymentService::syncCancelledOrderRefund($orderId);
|
||||
$refundState = 'success';
|
||||
self::notifyUser(
|
||||
$userId,
|
||||
$orderId,
|
||||
'订单超时自动关闭及退款通知',
|
||||
"您的订单 {$orderNo} 因下单超过 {$days} 天未有师傅接单已自动关闭,实付金额 ¥{$payAmount} 已发起原路退款,请注意查收。",
|
||||
$now
|
||||
);
|
||||
} catch (\Throwable $re) {
|
||||
$refundState = 'failed';
|
||||
Log::error("[OrderAutoCloseService] 订单 #{$orderId} 自动退款异常:" . $re->getMessage());
|
||||
try {
|
||||
PaymentService::syncCancelledOrderRefund($orderId);
|
||||
} catch (\Throwable $se) {
|
||||
Log::error("[OrderAutoCloseService] 订单 #{$orderId} 同步退款状态异常:" . $se->getMessage());
|
||||
}
|
||||
self::notifyUser(
|
||||
$userId,
|
||||
$orderId,
|
||||
'订单超时自动关闭通知',
|
||||
"您的订单 {$orderNo} 因下单超过 {$days} 天未有师傅接单已自动关闭,退款正在系统重试处理中,如有疑问请联系客服。",
|
||||
$now
|
||||
);
|
||||
}
|
||||
} else {
|
||||
self::notifyUser(
|
||||
$userId,
|
||||
$orderId,
|
||||
'订单超时自动关闭通知',
|
||||
"您的订单 {$orderNo} 因下单超过 {$days} 天未有师傅接单已自动关闭。",
|
||||
$now
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'order_id' => $orderId,
|
||||
'order_no' => $orderNo,
|
||||
'status' => 'closed',
|
||||
'refund_state' => $refundState,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送用户站内信提醒
|
||||
*/
|
||||
protected static function notifyUser($userId, $orderId, $title, $content, $now)
|
||||
{
|
||||
if ((int)$userId <= 0) {
|
||||
return;
|
||||
}
|
||||
Db::name('message')->insert([
|
||||
'receive_type' => 'user',
|
||||
'receive_id' => (int)$userId,
|
||||
'type' => 'order',
|
||||
'title' => mb_substr((string)$title, 0, 100),
|
||||
'content' => mb_substr((string)$content, 0, 500),
|
||||
'order_id' => (int)$orderId,
|
||||
'is_read' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,74 @@ class PaymentService
|
||||
throw new \InvalidArgumentException('未获取到当前微信授权信息(OpenID 缺失),请在微信小程序内打开并登录后再操作');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并严格校验当前操作师傅的师傅端小程序 OpenID(操作 fa_master_wechat,与用户端完全隔离)
|
||||
*
|
||||
* @param int $masterId 当前登录师傅 ID
|
||||
* @param string $wxCode 师傅端小程序实时获取的 wx.login code
|
||||
* @return string
|
||||
*/
|
||||
public static function resolveMasterOpenid($masterId, $wxCode = '')
|
||||
{
|
||||
$masterId = (int)$masterId;
|
||||
$wxCode = trim((string)$wxCode);
|
||||
|
||||
if ($wxCode !== '') {
|
||||
$wx = WxLogin::jscode2session($wxCode, 'master');
|
||||
if (!is_array($wx) || !empty($wx['error']) || empty($wx['openid'])) {
|
||||
$errMsg = (is_array($wx) && !empty($wx['error']))
|
||||
? (string)$wx['error']
|
||||
: '获取师傅端微信身份标识(OpenID)失败,请在师傅端小程序内重新登录后再试';
|
||||
Log::error("[PaymentService::resolveMasterOpenid] jscode2session 失败 master_id={$masterId}: {$errMsg}");
|
||||
throw new \RuntimeException($errMsg);
|
||||
}
|
||||
|
||||
$liveOpenid = trim((string)$wx['openid']);
|
||||
$unionid = isset($wx['unionid']) ? trim((string)$wx['unionid']) : '';
|
||||
$sessionKey = isset($wx['session_key']) ? trim((string)$wx['session_key']) : '';
|
||||
$now = time();
|
||||
|
||||
$existByOpenid = Db::name('master_wechat')->where('openid', $liveOpenid)->find();
|
||||
if ($existByOpenid) {
|
||||
$boundMid = (int)$existByOpenid['master_id'];
|
||||
if ($boundMid > 0 && $boundMid !== $masterId) {
|
||||
Log::error("[PaymentService::resolveMasterOpenid] OpenID归属冲突 current_mid={$masterId}, bound_mid={$boundMid}");
|
||||
throw new \InvalidArgumentException('当前微信号已绑定其他师傅账号(师傅ID:' . $boundMid . '),请确认登录账号与微信号一致后再操作');
|
||||
}
|
||||
Db::name('master_wechat')->where('id', (int)$existByOpenid['id'])->update([
|
||||
'master_id' => $masterId,
|
||||
'unionid' => $unionid !== '' ? $unionid : (string)$existByOpenid['unionid'],
|
||||
'session_key' => $sessionKey !== '' ? $sessionKey : (string)$existByOpenid['session_key'],
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
} else {
|
||||
Db::name('master_wechat')->insert([
|
||||
'master_id' => $masterId,
|
||||
'openid' => $liveOpenid,
|
||||
'unionid' => $unionid,
|
||||
'session_key' => $sessionKey,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
return $liveOpenid;
|
||||
}
|
||||
|
||||
if ($masterId > 0) {
|
||||
$bind = Db::name('master_wechat')
|
||||
->where('master_id', $masterId)
|
||||
->where('openid', '<>', '')
|
||||
->order('updatetime desc, id desc')
|
||||
->find();
|
||||
if ($bind && !empty($bind['openid'])) {
|
||||
return trim((string)$bind['openid']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('未获取到师傅端微信授权信息(OpenID 缺失),请在师傅端微信小程序内打开并登录后再操作');
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户端统一发起微信 JSAPI 支付(覆盖 order 首单支付 / quote 选师傅报价支付 / diff 施工增项补差价支付)
|
||||
*
|
||||
@@ -1219,11 +1287,11 @@ class PaymentService
|
||||
throw new \InvalidArgumentException('提现师傅档案不存在');
|
||||
}
|
||||
|
||||
// 解析收款师傅微信 OpenID(优先读提现单快照,其次查微信绑定表)
|
||||
// 解析收款师傅微信 OpenID(优先读提现单快照,其次查师傅端独立绑定表 fa_master_wechat)
|
||||
$openid = trim((string)($wd['openid'] ?? ''));
|
||||
if ($openid === '' && (int)$master['user_id'] > 0) {
|
||||
$bind = Db::name('user_wechat')
|
||||
->where('user_id', (int)$master['user_id'])
|
||||
if ($openid === '') {
|
||||
$bind = Db::name('master_wechat')
|
||||
->where('master_id', (int)$master['id'])
|
||||
->where('openid', '<>', '')
|
||||
->order('updatetime desc, id desc')
|
||||
->find();
|
||||
@@ -1232,7 +1300,7 @@ class PaymentService
|
||||
}
|
||||
}
|
||||
if ($openid === '') {
|
||||
$msg = '该师傅尚未绑定微信小程序授权(缺少收款 OpenID),请提醒师傅在微信小程序内登录打开「我的钱包」后再试';
|
||||
$msg = '该师傅尚未绑定师傅端微信小程序授权(缺少收款 OpenID),请提醒师傅在师傅端小程序内登录打开「我的钱包」后再试';
|
||||
self::recordWithdrawFailure($withdrawId, 'OPENID_MISSING', $msg);
|
||||
throw new \InvalidArgumentException($msg);
|
||||
}
|
||||
@@ -1269,9 +1337,9 @@ class PaymentService
|
||||
]);
|
||||
}
|
||||
|
||||
// 事务外调用微信支付 APIv3 发起商家转账(动态读取独立配置中心报备参数)
|
||||
// 事务外调用微信支付 APIv3 发起商家转账(使用师傅端 AppID 与配置)
|
||||
$wdCfg = FinanceConfigService::getWithdrawConfig();
|
||||
$wxSvc = new WxPayV3Service();
|
||||
$wxSvc = new WxPayV3Service(['side' => 'master']);
|
||||
try {
|
||||
$resp = $wxSvc->createTransferBill([
|
||||
'out_bill_no' => $outBillNo,
|
||||
@@ -1385,9 +1453,9 @@ class PaymentService
|
||||
$arrStr = number_format((float)$lockedWd['arrive_amount'], 2, '.', '');
|
||||
self::sendMasterAndUserMessage(
|
||||
(int)$master['id'],
|
||||
(int)$master['user_id'],
|
||||
0,
|
||||
'提现已汇出,请确认收款',
|
||||
"您的提现申请 ¥{$amtStr}(实际到账 ¥{$arrStr})已通过审核并发起微信转账,请在 24 小时内打开小程序「我的钱包」点击「确认收款」入账微信零钱。"
|
||||
"您的提现申请 ¥{$amtStr}(实际到账 ¥{$arrStr})已通过审核并发起微信转账,请在 24 小时内打开师傅端小程序「我的钱包」点击「确认收款」入账微信零钱。"
|
||||
);
|
||||
|
||||
Db::commit();
|
||||
@@ -1424,7 +1492,7 @@ class PaymentService
|
||||
}
|
||||
|
||||
if ($wxBillData === null) {
|
||||
$wxSvc = new WxPayV3Service();
|
||||
$wxSvc = new WxPayV3Service(['side' => 'master']);
|
||||
try {
|
||||
$wxBillData = $wxSvc->queryTransferBill($outBillNo);
|
||||
} catch (\Throwable $qe) {
|
||||
@@ -1512,7 +1580,7 @@ class PaymentService
|
||||
]);
|
||||
self::sendMasterAndUserMessage(
|
||||
$masterId,
|
||||
(int)$master['user_id'],
|
||||
0,
|
||||
'提现已到账微信零钱',
|
||||
'您的提现 ¥' . $amount . '(实到 ¥' . $lockedWd['arrive_amount'] . ')已成功确认收款并入账微信零钱。'
|
||||
);
|
||||
@@ -1565,7 +1633,7 @@ class PaymentService
|
||||
]);
|
||||
self::sendMasterAndUserMessage(
|
||||
$masterId,
|
||||
(int)$master['user_id'],
|
||||
0,
|
||||
'提现未完成退回余额通知',
|
||||
'您的提现申请 ¥' . $amount . ' 未完成入账(原因:' . $reasonText . '),资金已自动解冻退回您的钱包可用余额,可随时重新发起提现。'
|
||||
);
|
||||
@@ -1685,7 +1753,7 @@ class PaymentService
|
||||
]);
|
||||
self::sendMasterAndUserMessage(
|
||||
$masterId,
|
||||
(int)$master['user_id'],
|
||||
0,
|
||||
'提现申请已驳回',
|
||||
'您的提现申请 ¥' . $amount . ' 未通过财务审核:' . $auditMsg . ',申请金额已退回钱包余额。'
|
||||
);
|
||||
@@ -1699,7 +1767,7 @@ class PaymentService
|
||||
|
||||
// 2. 已存在商户转账单号时:先实时向微信查单,确认为已失败/已撤销/微信侧不存在后,方可解冻退款(严防双重资损)
|
||||
$outBillNo = (string)$wd['out_bill_no'];
|
||||
$wxSvc = new WxPayV3Service();
|
||||
$wxSvc = new WxPayV3Service(['side' => 'master']);
|
||||
try {
|
||||
$wxBill = $wxSvc->queryTransferBill($outBillNo);
|
||||
} catch (\Throwable $qe) {
|
||||
@@ -1818,7 +1886,7 @@ class PaymentService
|
||||
]);
|
||||
self::sendMasterAndUserMessage(
|
||||
$masterId,
|
||||
(int)$master['user_id'],
|
||||
0,
|
||||
'提现申请已退回余额',
|
||||
'您的提现申请 ¥' . $amount . ' 已驳回退回(批注:' . $auditMsg . '),申请金额已全额退回钱包可用余额。'
|
||||
);
|
||||
@@ -2146,12 +2214,27 @@ class PaymentService
|
||||
protected static function broadcastNewOrderToMasters(array $order)
|
||||
{
|
||||
try {
|
||||
$masters = Db::name('master')
|
||||
$excludeMobiles = [];
|
||||
$orderMobile = trim((string)($order['mobile'] ?? ''));
|
||||
if ($orderMobile !== '') {
|
||||
$excludeMobiles[] = $orderMobile;
|
||||
}
|
||||
if ((int)($order['user_id'] ?? 0) > 0) {
|
||||
$posterMobile = trim((string)Db::name('user')->where('id', (int)$order['user_id'])->value('mobile'));
|
||||
if ($posterMobile !== '') {
|
||||
$excludeMobiles[] = $posterMobile;
|
||||
}
|
||||
}
|
||||
$q = Db::name('master')
|
||||
->where('verify_status', 'pass')
|
||||
->where('work_status', 'on')
|
||||
->where('user_id', '<>', (int)$order['user_id'])
|
||||
->limit(20)
|
||||
->select();
|
||||
->where('status', 'normal');
|
||||
if (!empty($excludeMobiles)) {
|
||||
$q->where(function ($sub) use ($excludeMobiles) {
|
||||
$sub->whereNull('mobile')->whereOr('mobile', 'not in', array_values(array_unique($excludeMobiles)));
|
||||
});
|
||||
}
|
||||
$masters = $q->limit(20)->select();
|
||||
foreach ($masters as $m) {
|
||||
self::sendNotify('master', (int)$m['id'], '新工单就绪通知', '同城有新工单【' . $order['order_no'] . '】进入接单大厅,请尽快前往抢单!', 'order', (int)$order['id']);
|
||||
}
|
||||
@@ -2205,18 +2288,6 @@ class PaymentService
|
||||
'createtime' => $now,
|
||||
];
|
||||
}
|
||||
if ((int)$userId > 0) {
|
||||
$rows[] = [
|
||||
'receive_type' => 'user',
|
||||
'receive_id' => (int)$userId,
|
||||
'type' => 'system',
|
||||
'title' => mb_substr((string)$title, 0, 100),
|
||||
'content' => mb_substr((string)$content, 0, 500),
|
||||
'order_id' => 0,
|
||||
'is_read' => 0,
|
||||
'createtime' => $now,
|
||||
];
|
||||
}
|
||||
if ($rows) {
|
||||
Db::name('message')->insertAll($rows);
|
||||
}
|
||||
|
||||
@@ -14,26 +14,20 @@ class TencentVerifyService
|
||||
const DEFAULT_REGION = 'ap-guangzhou';
|
||||
|
||||
/**
|
||||
* 获取腾讯云 SecretId(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
* 获取腾讯云 SecretId(严格读取后台系统配置,不在源码或 .env 内配置)
|
||||
*/
|
||||
public static function getSecretId()
|
||||
{
|
||||
$id = class_exists('\\think\\Config') ? \think\Config::get('site.tencent_secret_id') : null;
|
||||
if (empty($id) && class_exists('\\think\\Env')) {
|
||||
$id = \think\Env::get('tencent.secret_id', '');
|
||||
}
|
||||
return trim((string)$id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取腾讯云 SecretKey(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
* 获取腾讯云 SecretKey(严格读取后台系统配置,不在源码或 .env 内配置)
|
||||
*/
|
||||
public static function getSecretKey()
|
||||
{
|
||||
$key = class_exists('\\think\\Config') ? \think\Config::get('site.tencent_secret_key') : null;
|
||||
if (empty($key) && class_exists('\\think\\Env')) {
|
||||
$key = \think\Env::get('tencent.secret_key', '');
|
||||
}
|
||||
return trim((string)$key);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,16 +12,12 @@ use think\Log;
|
||||
class TiandituService
|
||||
{
|
||||
/**
|
||||
* 获取天地图 Key(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
* 获取天地图 Key(严格读取后台系统配置,不在源码或 .env 内配置)
|
||||
* @return string
|
||||
*/
|
||||
public static function getKey()
|
||||
{
|
||||
$key = Config::get('site.tianditu_key');
|
||||
if (empty($key) && class_exists('\\think\\Env')) {
|
||||
$key = \think\Env::get('tianditu.key', '');
|
||||
}
|
||||
return trim((string)$key);
|
||||
return trim((string)Config::get('site.tianditu_key'));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -213,6 +213,7 @@ class Upload
|
||||
// user 维度分类:从请求 token 解析 user_id,路径插入 u{userid} 层级;common 维度或未登录不插入(后台会话无API token,自动落公共目录)
|
||||
$categoryMap = isset($this->config['category_map']) && is_array($this->config['category_map']) ? $this->config['category_map'] : [];
|
||||
$userId = 0;
|
||||
$masterId = 0;
|
||||
if (($categoryMap[$category] ?? 'common') === 'user' && request()->module() !== 'admin') {
|
||||
// 后台请求固定走公共目录:避免同域部署时管理员浏览器残留前台 token cookie 导致误插用户层
|
||||
$token = request()->server('HTTP_TOKEN', request()->request('token', \think\Cookie::get('token')));
|
||||
@@ -220,9 +221,15 @@ class Upload
|
||||
$tokenInfo = Token::get($token);
|
||||
if (!empty($tokenInfo['user_id'])) {
|
||||
$userId = (int)$tokenInfo['user_id'];
|
||||
} else {
|
||||
$masterTokenInfo = MasterToken::get($token);
|
||||
if (!empty($masterTokenInfo['master_id'])) {
|
||||
$masterId = (int)$masterTokenInfo['master_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$ownerSegment = $userId > 0 ? '/u' . $userId : ($masterId > 0 ? '/m' . $masterId : '');
|
||||
$replaceArr = [
|
||||
'{year}' => date("Y"),
|
||||
'{mon}' => date("m"),
|
||||
@@ -232,7 +239,7 @@ class Upload
|
||||
'{sec}' => date("s"),
|
||||
'{random}' => Random::alnum(16),
|
||||
'{random32}' => Random::alnum(32),
|
||||
'{category}' => $category . ($userId > 0 ? '/u' . $userId : ''),
|
||||
'{category}' => $category . $ownerSegment,
|
||||
'{filename}' => substr($filename, 0, 100),
|
||||
'{fileprefix}' => substr($fileprefix, 0, 100),
|
||||
'{suffix}' => $suffix,
|
||||
@@ -433,9 +440,11 @@ class Upload
|
||||
// 附件记录分类与存储路径共用同一注册表(normalizeCategory),不再依赖 site.attachmentcategory 字典校验
|
||||
$category = $this->normalizeCategory(request()->post('category'));
|
||||
$auth = Auth::instance();
|
||||
$masterAuth = MasterAuth::instance();
|
||||
$params = array(
|
||||
'admin_id' => (int)session('admin.id'),
|
||||
'user_id' => (int)$auth->id,
|
||||
'master_id' => (int)$masterAuth->id(),
|
||||
'filename' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
|
||||
'category' => $category,
|
||||
'filesize' => $this->fileInfo['size'],
|
||||
|
||||
@@ -15,12 +15,30 @@ class WxLogin
|
||||
* 小程序 code 换取 session
|
||||
* @return array|false 成功返回 ['openid'=>..,'session_key'=>..,'unionid'=>..]
|
||||
*/
|
||||
public static function jscode2session($code)
|
||||
public static function getMiniAppConfig($side = 'user')
|
||||
{
|
||||
$appid = trim((string)\think\Env::get('wechat.appid', ''));
|
||||
$secret = trim((string)\think\Env::get('wechat.secret', ''));
|
||||
$side = $side === 'master' ? 'master' : 'user';
|
||||
if ($side === 'master') {
|
||||
return [
|
||||
'appid' => trim((string)\think\Config::get('site.wechat_master_appid')),
|
||||
'secret' => trim((string)\think\Config::get('site.wechat_master_secret')),
|
||||
];
|
||||
}
|
||||
return [
|
||||
'appid' => trim((string)\think\Config::get('site.wechat_user_appid')),
|
||||
'secret' => trim((string)\think\Config::get('site.wechat_user_secret')),
|
||||
];
|
||||
}
|
||||
|
||||
public static function jscode2session($code, $side = 'user')
|
||||
{
|
||||
$side = $side === 'master' ? 'master' : 'user';
|
||||
$cfg = self::getMiniAppConfig($side);
|
||||
$appid = $cfg['appid'];
|
||||
$secret = $cfg['secret'];
|
||||
if ($appid === '' || $secret === '') {
|
||||
return ['error' => '微信登录参数未配置完整(请检查 server/.env 的 wechat.appid 与 wechat.secret)', 'errcode' => -1001];
|
||||
$label = $side === 'master' ? '师傅端' : '用户端';
|
||||
return ['error' => "{$label}微信登录参数未配置完整(请在后台「常规管理 -> 系统配置 -> 小程序与支付配置」填写 AppID 与 Secret)", 'errcode' => -1001];
|
||||
}
|
||||
$code = trim((string)$code);
|
||||
if ($code === '') {
|
||||
@@ -133,19 +151,23 @@ class WxLogin
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取微信 access_token (带缓存)
|
||||
* 获取微信 access_token (按端独立缓存,防止双小程序互相覆盖)
|
||||
* @param string $side user|master
|
||||
*/
|
||||
public static function getAccessToken()
|
||||
public static function getAccessToken($side = 'user')
|
||||
{
|
||||
$cached = \think\Cache::get('wechat_access_token');
|
||||
$side = $side === 'master' ? 'master' : 'user';
|
||||
$cacheKey = 'wechat_access_token_' . $side;
|
||||
$cached = \think\Cache::get($cacheKey);
|
||||
if ($cached) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$appid = \think\Env::get('wechat.appid');
|
||||
$secret = \think\Env::get('wechat.secret');
|
||||
$cfg = self::getMiniAppConfig($side);
|
||||
$appid = $cfg['appid'];
|
||||
$secret = $cfg['secret'];
|
||||
if (!$appid || !$secret) {
|
||||
return ['error' => '微信配置缺失'];
|
||||
return ['error' => ($side === 'master' ? '师傅端' : '用户端') . '微信配置缺失'];
|
||||
}
|
||||
|
||||
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
|
||||
@@ -156,21 +178,27 @@ class WxLogin
|
||||
}
|
||||
$data = json_decode($resp, true);
|
||||
if (empty($data['access_token'])) {
|
||||
return ['error' => isset($data['errmsg']) ? $data['errmsg'] : '获取 access_token 失败', 'errcode' => isset($data['errcode']) ? $data['errcode'] : 0];
|
||||
$ec = isset($data['errcode']) ? (int)$data['errcode'] : 0;
|
||||
$em = isset($data['errmsg']) ? (string)$data['errmsg'] : '获取 access_token 失败';
|
||||
\think\Log::error("[WxLogin::getAccessToken] side={$side}, errcode={$ec}, errmsg={$em}");
|
||||
return ['error' => '微信服务授权异常,请稍后重试', 'errcode' => $ec];
|
||||
}
|
||||
|
||||
$token = $data['access_token'];
|
||||
$expire = isset($data['expires_in']) ? max(60, (int)$data['expires_in'] - 200) : 6000;
|
||||
\think\Cache::set('wechat_access_token', $token, $expire);
|
||||
\think\Cache::set($cacheKey, $token, $expire);
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过手机号快速验证 code 换取用户真实手机号
|
||||
* 通过手机号快速验证 code 换取真实手机号
|
||||
* @param string $code
|
||||
* @param string $side user|master
|
||||
*/
|
||||
public static function getPhoneNumber($code)
|
||||
public static function getPhoneNumber($code, $side = 'user')
|
||||
{
|
||||
$token = self::getAccessToken();
|
||||
$side = $side === 'master' ? 'master' : 'user';
|
||||
$token = self::getAccessToken($side);
|
||||
if (is_array($token) && isset($token['error'])) {
|
||||
return $token;
|
||||
}
|
||||
@@ -193,11 +221,19 @@ class WxLogin
|
||||
$data = json_decode($resp, true);
|
||||
if (empty($data) || !isset($data['errcode']) || (int)$data['errcode'] !== 0 || empty($data['phone_info'])) {
|
||||
$ec = isset($data['errcode']) ? (int)$data['errcode'] : -1;
|
||||
$em = isset($data['errmsg']) ? $data['errmsg'] : '换取手机号失败';
|
||||
$em = isset($data['errmsg']) ? (string)$data['errmsg'] : '换取手机号失败';
|
||||
if ($ec === 40001 || $ec === 42001) {
|
||||
\think\Cache::rm('wechat_access_token');
|
||||
\think\Cache::rm('wechat_access_token_' . $side);
|
||||
}
|
||||
return ['error' => $em, 'errcode' => $ec];
|
||||
\think\Log::error("[WxLogin::getPhoneNumber] side={$side}, errcode={$ec}, errmsg={$em}");
|
||||
$hint = [
|
||||
40029 => '手机号授权凭证已失效,请重新点击登录',
|
||||
40163 => '手机号授权凭证已被使用,请重新点击登录',
|
||||
40001 => '微信登录凭证已刷新,请重试',
|
||||
42001 => '微信登录凭证已刷新,请重试',
|
||||
45011 => '操作过于频繁,请稍后再试',
|
||||
];
|
||||
return ['error' => isset($hint[$ec]) ? $hint[$ec] : '获取微信手机号失败,请重试', 'errcode' => $ec];
|
||||
}
|
||||
return $data['phone_info'];
|
||||
}
|
||||
@@ -264,4 +300,149 @@ class WxLogin
|
||||
return ['user_id' => $userId, 'is_new' => $isNew];
|
||||
}
|
||||
|
||||
/**
|
||||
* 师傅端:按 openid 落库(fa_master + fa_master_wechat),幂等
|
||||
* @return array ['master_id' => int, 'is_new' => 0|1]
|
||||
*/
|
||||
public static function provisionMaster($openid, $unionid = '', $sessionKey = '', $nickname = '', $avatar = '')
|
||||
{
|
||||
$openid = (string)$openid;
|
||||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||||
$masterId = $bind ? (int)$bind['master_id'] : 0;
|
||||
|
||||
if ($masterId > 0 && !Db::name('master')->where('id', $masterId)->find()) {
|
||||
$masterId = 0;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$isNew = 0;
|
||||
if ($masterId === 0) {
|
||||
$isNew = 1;
|
||||
$masterId = (int)Db::name('master')->insertGetId([
|
||||
'mobile' => null,
|
||||
'nickname' => $nickname !== '' ? mb_substr($nickname, 0, 20) : ('师傅' . substr($openid, -4)),
|
||||
'realname' => '',
|
||||
'avatar' => $avatar,
|
||||
'verify_status' => 'draft',
|
||||
'work_status' => 'off',
|
||||
'status' => 'normal',
|
||||
'level' => 1,
|
||||
'score' => 5.00,
|
||||
'accept_rate' => 100.00,
|
||||
'ontime_rate' => 100.00,
|
||||
'serve_radius' => 10,
|
||||
'money' => 0.00,
|
||||
'frozen_money' => 0.00,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
MasterSecurity::ensure($masterId);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'master_id' => $masterId,
|
||||
'openid' => $openid,
|
||||
'unionid' => (string)$unionid,
|
||||
'session_key' => (string)$sessionKey,
|
||||
'updatetime' => $now,
|
||||
];
|
||||
if ($nickname !== '') {
|
||||
$data['nickname'] = mb_substr($nickname, 0, 64);
|
||||
}
|
||||
if ($avatar !== '') {
|
||||
$data['avatar'] = $avatar;
|
||||
}
|
||||
|
||||
if ($bind) {
|
||||
Db::name('master_wechat')->where('id', $bind['id'])->update($data);
|
||||
} else {
|
||||
$data['createtime'] = $now;
|
||||
Db::name('master_wechat')->insert($data);
|
||||
}
|
||||
|
||||
$masterUpdate = ['updatetime' => $now];
|
||||
if ($nickname !== '') {
|
||||
$masterUpdate['nickname'] = mb_substr($nickname, 0, 20);
|
||||
}
|
||||
if ($avatar !== '') {
|
||||
$masterUpdate['avatar'] = $avatar;
|
||||
}
|
||||
Db::name('master')->where('id', $masterId)->update($masterUpdate);
|
||||
|
||||
return ['master_id' => $masterId, 'is_new' => $isNew];
|
||||
}
|
||||
|
||||
/**
|
||||
* 师傅端:按手机号结合 openid 注册或登录独立师傅账号(fa_master + fa_master_wechat,幂等合并)
|
||||
* @return array ['master_id' => int, 'is_new' => 0|1]
|
||||
*/
|
||||
public static function provisionMasterWithMobile($mobile, $openid = '', $unionid = '', $sessionKey = '')
|
||||
{
|
||||
$mobile = trim((string)$mobile);
|
||||
$openid = trim((string)$openid);
|
||||
$masterId = 0;
|
||||
$isNew = 0;
|
||||
$now = time();
|
||||
|
||||
// 1. 优先按手机号匹配已存在师傅账号
|
||||
$existMaster = Db::name('master')->where('mobile', $mobile)->find();
|
||||
if ($existMaster) {
|
||||
$masterId = (int)$existMaster['id'];
|
||||
}
|
||||
|
||||
// 2. 若手机号未查到,但有 openid,检查 fa_master_wechat 是否已绑定师傅
|
||||
if ($masterId === 0 && $openid !== '') {
|
||||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||||
if ($bind && Db::name('master')->where('id', $bind['master_id'])->find()) {
|
||||
$masterId = (int)$bind['master_id'];
|
||||
Db::name('master')->where('id', $masterId)->update(['mobile' => $mobile, 'updatetime' => $now]);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 师傅账号完全不存在,新建独立师傅账号(状态 draft,需提交实名入驻审核)
|
||||
if ($masterId === 0) {
|
||||
$isNew = 1;
|
||||
$masterId = (int)Db::name('master')->insertGetId([
|
||||
'mobile' => $mobile,
|
||||
'nickname' => '师傅' . substr($mobile, -4),
|
||||
'realname' => '',
|
||||
'avatar' => '',
|
||||
'verify_status' => 'draft',
|
||||
'work_status' => 'off',
|
||||
'status' => 'normal',
|
||||
'level' => 1,
|
||||
'score' => 5.00,
|
||||
'accept_rate' => 100.00,
|
||||
'ontime_rate' => 100.00,
|
||||
'serve_radius' => 10,
|
||||
'money' => 0.00,
|
||||
'frozen_money' => 0.00,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
MasterSecurity::ensure($masterId);
|
||||
|
||||
// 4. 若有 openid,建立或更新 fa_master_wechat 关联
|
||||
if ($openid !== '') {
|
||||
$bind = Db::name('master_wechat')->where('openid', $openid)->find();
|
||||
$bindData = [
|
||||
'master_id' => $masterId,
|
||||
'openid' => $openid,
|
||||
'unionid' => (string)$unionid,
|
||||
'session_key' => (string)$sessionKey,
|
||||
'updatetime' => $now,
|
||||
];
|
||||
if ($bind) {
|
||||
Db::name('master_wechat')->where('id', $bind['id'])->update($bindData);
|
||||
} else {
|
||||
$bindData['createtime'] = $now;
|
||||
Db::name('master_wechat')->insert($bindData);
|
||||
}
|
||||
}
|
||||
|
||||
return ['master_id' => $masterId, 'is_new' => $isNew];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Env;
|
||||
use think\Config;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
@@ -50,21 +50,27 @@ class WxPayV3Service
|
||||
|
||||
public function __construct(array $overrideConfig = [])
|
||||
{
|
||||
$this->appId = trim((string)($overrideConfig['appid'] ?? Env::get('wechat.appid', '')));
|
||||
$this->mchId = trim((string)($overrideConfig['mch_id'] ?? Env::get('wechat.mch_id', '')));
|
||||
$this->keyV3 = trim((string)($overrideConfig['key_v3'] ?? Env::get('wechat.key_v3', '')));
|
||||
$this->publicKeyId = trim((string)($overrideConfig['public_key_id'] ?? Env::get('wechat.public_key_id', '')));
|
||||
$side = isset($overrideConfig['side']) && $overrideConfig['side'] === 'master' ? 'master' : 'user';
|
||||
if (isset($overrideConfig['appid'])) {
|
||||
$this->appId = trim((string)$overrideConfig['appid']);
|
||||
} else {
|
||||
$miniCfg = WxLogin::getMiniAppConfig($side);
|
||||
$this->appId = $miniCfg['appid'];
|
||||
}
|
||||
$this->mchId = trim((string)($overrideConfig['mch_id'] ?? Config::get('site.wechat_mch_id')));
|
||||
$this->keyV3 = trim((string)($overrideConfig['key_v3'] ?? Config::get('site.wechat_key_v3')));
|
||||
$this->publicKeyId = trim((string)($overrideConfig['public_key_id'] ?? Config::get('site.wechat_public_key_id')));
|
||||
|
||||
$certRel = trim((string)($overrideConfig['cert_client'] ?? (Env::get('wechat.cert_client', '') ?: '/addons/epay/certs/apiclient_cert.pem')));
|
||||
$keyRel = trim((string)($overrideConfig['cert_key'] ?? (Env::get('wechat.cert_key', '') ?: '/addons/epay/certs/apiclient_key.pem')));
|
||||
$pubRel = trim((string)($overrideConfig['public_key'] ?? (Env::get('wechat.public_key', '') ?: '/addons/epay/certs/public_key.pem')));
|
||||
$certRel = trim((string)($overrideConfig['cert_client'] ?? '/addons/epay/certs/apiclient_cert.pem'));
|
||||
$keyRel = trim((string)($overrideConfig['cert_key'] ?? '/addons/epay/certs/apiclient_key.pem'));
|
||||
$pubRel = trim((string)($overrideConfig['public_key'] ?? '/addons/epay/certs/public_key.pem'));
|
||||
|
||||
$this->certClientPath = $this->resolveCertPath($certRel);
|
||||
$this->certKeyPath = $this->resolveCertPath($keyRel);
|
||||
$this->publicKeyPath = $this->resolveCertPath($pubRel);
|
||||
|
||||
$this->notifyDomain = rtrim(trim((string)($overrideConfig['notify_domain'] ?? Env::get('wechat.notify_domain', ''))), '/');
|
||||
$this->transferSceneId = trim((string)($overrideConfig['transfer_scene_id'] ?? (Env::get('wechat.transfer_scene_id', '') ?: '1005')));
|
||||
$this->notifyDomain = rtrim(trim((string)($overrideConfig['notify_domain'] ?? Config::get('site.wechat_notify_domain'))), '/');
|
||||
$this->transferSceneId = trim((string)($overrideConfig['transfer_scene_id'] ?? (Config::get('site.wechat_transfer_scene_id') ?: '1005')));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
在新工单中引用
屏蔽一个用户