PaymentProviderConfig.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. namespace App\Services\Payment;
  3. use App\Models\PaymentProvider;
  4. use App\Models\PaymentOrder;
  5. use App\Services\OperationAuditService;
  6. use App\Services\PaymentOrderService;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Validation\ValidationException;
  10. use InvalidArgumentException;
  11. use RuntimeException;
  12. use Throwable;
  13. /**
  14. * 支付公司商户配置。后台保存到 payment_providers.config(加密),未保存的字段回退到 .env。
  15. * 每次操作读取完整快照、不做进程缓存:后续操作使用后台最新配置。
  16. */
  17. class PaymentProviderConfig
  18. {
  19. // type: text 普通文本,secret 密钥(只写不回显),url 网关地址,user_ids 逗号分隔用户ID(留空=全部用户)
  20. private const FIELDS = [
  21. 'sanjin' => [
  22. 'mch_id' => ['label' => '商户号', 'type' => 'text', 'env' => 'app.tree_pay_mch_id'],
  23. 'key' => ['label' => '商户密钥', 'type' => 'secret', 'env' => 'app.tree_pay_key'],
  24. 'gateway' => ['label' => '接口地址', 'type' => 'url', 'default' => 'https://jkapi-sanjin.jkcbb.com/'],
  25. ],
  26. 'qianbao' => [
  27. 'merchant_id' => ['label' => '商户号', 'type' => 'text', 'env' => 'app.tree_payment_merchant_id'],
  28. 'secret' => ['label' => '商户密钥', 'type' => 'secret', 'env' => 'app.tree_payment_secret'],
  29. 'gateway' => ['label' => '接口地址', 'type' => 'url', 'default' => 'https://api.qbdf13.com/'],
  30. ],
  31. 'jd' => [
  32. 'mch_id' => ['label' => '商户号', 'type' => 'text', 'env' => 'app.jd_pay_mch_id'],
  33. 'key' => ['label' => '商户密钥', 'type' => 'secret', 'env' => 'app.jd_pay_key'],
  34. 'pay_gateway' => ['label' => '充值下单地址', 'type' => 'url', 'env' => 'app.jd_pay_gateway'],
  35. 'pay_query_gateway' => ['label' => '充值查询地址', 'type' => 'url', 'env' => 'app.jd_pay_query_gateway'],
  36. 'remit_gateway' => ['label' => '代付下单地址', 'type' => 'url', 'env' => 'app.jd_remit_gateway'],
  37. 'remit_query_gateway' => ['label' => '代付查询地址', 'type' => 'url', 'env' => 'app.jd_remit_query_gateway'],
  38. 'balance_gateway' => ['label' => '余额查询地址', 'type' => 'url', 'env' => 'app.jd_balance_gateway'],
  39. 'recharge_user_ids' => ['label' => '充值白名单用户ID', 'type' => 'user_ids', 'env' => 'app.jd_pay_recharge_user_ids'],
  40. ],
  41. 'no' => [
  42. 'deposit_mch_id' => ['label' => '充值商户号', 'type' => 'text', 'env' => 'app.no_pay_deposit_mch_id'],
  43. 'deposit_key' => ['label' => '充值密钥', 'type' => 'secret', 'env' => 'app.no_pay_deposit_key'],
  44. 'withdraw_mch_id' => ['label' => '提现商户号', 'type' => 'text', 'env' => 'app.no_pay_withdraw_mch_id'],
  45. 'withdraw_key' => ['label' => '提现密钥', 'type' => 'secret', 'env' => 'app.no_pay_withdraw_key'],
  46. 'deposit_gateway' => ['label' => '充值下单地址', 'type' => 'url', 'env' => 'app.no_pay_deposit_gateway'],
  47. 'deposit_query_gateway' => ['label' => '充值查询地址', 'type' => 'url', 'env' => 'app.no_pay_deposit_query_gateway'],
  48. 'withdraw_gateway' => ['label' => '提现下单地址', 'type' => 'url', 'env' => 'app.no_pay_withdraw_gateway'],
  49. 'recharge_user_ids' => ['label' => '充值白名单用户ID', 'type' => 'user_ids', 'env' => 'app.no_pay_recharge_user_ids'],
  50. ],
  51. 'zimu' => [
  52. 'app_id' => ['label' => '商户AppID', 'type' => 'text', 'env' => 'app.zimu_pay_app_id'],
  53. 'key' => ['label' => '商户密钥', 'type' => 'secret', 'env' => 'app.zimu_pay_key'],
  54. 'pay_gateway' => ['label' => '充值下单地址', 'type' => 'url', 'env' => 'app.zimu_pay_gateway'],
  55. 'pay_query_gateway' => ['label' => '充值查询地址', 'type' => 'url', 'env' => 'app.zimu_pay_query_gateway'],
  56. 'balance_gateway' => ['label' => '余额查询地址', 'type' => 'url', 'env' => 'app.zimu_balance_gateway'],
  57. 'withdraw_gateway' => ['label' => '账户提现下单地址', 'type' => 'url', 'env' => 'app.zimu_withdraw_gateway'],
  58. 'withdraw_query_gateway' => ['label' => '账户提现查询地址', 'type' => 'url', 'env' => 'app.zimu_withdraw_query_gateway'],
  59. 'cash_gateway' => ['label' => '人民币代付下单地址', 'type' => 'url', 'env' => 'app.zimu_cash_gateway'],
  60. 'cash_query_gateway' => ['label' => '人民币代付查询地址', 'type' => 'url', 'env' => 'app.zimu_cash_query_gateway'],
  61. 'recharge_user_ids' => ['label' => '充值白名单用户ID', 'type' => 'user_ids', 'env' => 'app.zimu_pay_recharge_user_ids'],
  62. ],
  63. ];
  64. public static function fields(string $code): array
  65. {
  66. if (!isset(self::FIELDS[$code])) throw new InvalidArgumentException('支付公司不存在');
  67. return self::FIELDS[$code];
  68. }
  69. /** 运行时取值:后台已保存的值优先,否则回退 .env / 默认值。 */
  70. public static function get(string $code, string $field): string
  71. {
  72. if (!isset(self::fields($code)[$field])) throw new InvalidArgumentException("未知支付配置 {$code}.{$field}");
  73. return self::snapshot($code)[$field];
  74. }
  75. /** 同一次下单、查询或验签复用该数组,避免不同字段跨配置版本读取。 */
  76. public static function snapshot(string $code): array
  77. {
  78. $fields = self::fields($code);
  79. $stored = self::stored($code);
  80. return self::resolve($fields, $stored);
  81. }
  82. public static function userIds(string $code): array
  83. {
  84. return array_values(array_filter(array_map('trim', explode(',', self::get($code, 'recharge_user_ids')))));
  85. }
  86. /** 后台展示:密钥只返回是否已配置和尾号,不回显明文。 */
  87. public function show(string $code): array
  88. {
  89. $stored = self::stored($code);
  90. $rows = [];
  91. foreach (self::fields($code) as $field => $definition) {
  92. $fromDb = array_key_exists($field, $stored);
  93. $value = $fromDb ? (string)$stored[$field] : self::fallback($definition);
  94. $row = [
  95. 'field' => $field, 'label' => $definition['label'], 'type' => $definition['type'],
  96. 'source' => $fromDb ? 'admin' : ($value === '' ? 'empty' : 'env'),
  97. ];
  98. if ($definition['type'] === 'secret') {
  99. $row['value'] = '';
  100. $row['has_value'] = $value !== '';
  101. $row['masked'] = $value === '' ? '' : '******' . mb_substr($value, -4);
  102. } else {
  103. $row['value'] = $value;
  104. }
  105. $rows[] = $row;
  106. }
  107. return [
  108. 'payment_company' => $code,
  109. 'payment_company_label' => PaymentProviderCatalog::label($code),
  110. 'fields' => $rows,
  111. ];
  112. }
  113. /**
  114. * 保存后台配置。仅提交的字段会被写入;密钥留空表示不修改。
  115. * 首次保存时其余字段仍按 .env 回退,不会被清空。
  116. */
  117. public function save(string $code, array $input): array
  118. {
  119. $fields = self::fields($code);
  120. $unknown = array_diff(array_keys($input), array_keys($fields));
  121. if ($unknown) throw ValidationException::withMessages(['config' => '未知配置项:' . implode(',', $unknown)]);
  122. $values = [];
  123. foreach ($input as $field => $value) {
  124. if ($value !== null && !is_scalar($value)) throw ValidationException::withMessages([$field => $fields[$field]['label'] . '格式错误']);
  125. $value = trim((string)$value);
  126. $type = $fields[$field]['type'];
  127. if ($type === 'secret' && $value === '') continue;
  128. if ($type === 'url' && filter_var($value, FILTER_VALIDATE_URL) === false) {
  129. throw ValidationException::withMessages([$field => $fields[$field]['label'] . '必须是有效的网址']);
  130. }
  131. if ($type === 'user_ids') {
  132. if (!preg_match('/^[0-9,\s]*$/', $value)) {
  133. throw ValidationException::withMessages([$field => $fields[$field]['label'] . '只能填写数字ID,多个用英文逗号分隔']);
  134. }
  135. $value = implode(',', array_values(array_filter(array_map('trim', explode(',', $value)), 'strlen')));
  136. }
  137. if (mb_strlen($value) > 10000) throw ValidationException::withMessages([$field => $fields[$field]['label'] . '过长']);
  138. $values[$field] = $value;
  139. }
  140. DB::transaction(function () use ($code, $values) {
  141. $provider = PaymentProvider::query()->where('code', $code)->lockForUpdate()->firstOrFail();
  142. $before = self::storedValues($provider, $code);
  143. $after = array_merge($before, $values);
  144. if ($after === $before) return;
  145. $definitions = self::fields($code);
  146. $oldValues = self::resolve($definitions, $before);
  147. $newValues = self::resolve($definitions, $after);
  148. foreach ($definitions as $field => $definition) {
  149. if (in_array($definition['type'], ['text', 'secret'], true) && $oldValues[$field] !== $newValues[$field]) {
  150. self::assertNoPendingOrders($code);
  151. break;
  152. }
  153. }
  154. $provider->config = $after;
  155. $provider->save();
  156. OperationAuditService::record('payment_company_config', (int)$provider->id, 'update', $before, $after);
  157. }, 3);
  158. return $this->show($code);
  159. }
  160. /** 固化当前服务器默认值:只补缺失字段,保留后台值和原始密钥,不返回明文。 */
  161. public function importDefaults(array $codes = [], bool $write = false): array
  162. {
  163. $codes = $codes ?: PaymentProviderCatalog::codes();
  164. foreach ($codes as $code) self::fields($code);
  165. // 固定加锁顺序,并去掉重复公司代码。
  166. $codes = array_values(array_intersect(PaymentProviderCatalog::codes(), $codes));
  167. return DB::transaction(function () use ($codes, $write) {
  168. $report = [];
  169. foreach ($codes as $code) {
  170. $query = PaymentProvider::query()->where('code', $code);
  171. $provider = ($write ? $query->lockForUpdate() : $query->sharedLock())->firstOrFail();
  172. $before = self::storedValues($provider, $code);
  173. $after = $before;
  174. $imported = $preserved = $empty = [];
  175. foreach (self::fields($code) as $field => $definition) {
  176. if (array_key_exists($field, $before)) {
  177. $preserved[] = $field;
  178. continue;
  179. }
  180. $value = self::fallback($definition);
  181. if ($value === '') {
  182. $empty[] = $field;
  183. continue;
  184. }
  185. $after[$field] = $value;
  186. $imported[] = $field;
  187. }
  188. if ($write && $imported !== []) {
  189. // 仅将当前回退值原样固化,实际生效的商户凭证不会发生变化。
  190. $provider->config = $after;
  191. $provider->save();
  192. OperationAuditService::record('payment_company_config', (int)$provider->id, 'import_env', $before, $after,
  193. actor: ['operator_id' => null, 'operator_name' => 'console:payment:config-import-env']);
  194. }
  195. $report[] = ['payment_company' => $code, 'label' => PaymentProviderCatalog::label($code),
  196. 'imported' => $imported, 'preserved' => $preserved, 'empty' => $empty];
  197. }
  198. return $report;
  199. }, 3);
  200. }
  201. private static function stored(string $code): array
  202. {
  203. try {
  204. // 共享锁与后台保存的排他锁互斥;多个支付读取仍可并行。
  205. // 若调用方已在事务内,共享锁保留到其提交,防止未提交订单被漏查。
  206. return DB::transaction(function () use ($code) {
  207. $provider = PaymentProvider::query()->where('code', $code)->sharedLock()->firstOrFail();
  208. return (array)($provider->config ?? []);
  209. });
  210. } catch (Throwable $e) {
  211. self::readFailed($code, $e);
  212. }
  213. }
  214. private static function storedValues(PaymentProvider $provider, string $code): array
  215. {
  216. try {
  217. return (array)($provider->config ?? []);
  218. } catch (Throwable $e) {
  219. self::readFailed($code, $e);
  220. }
  221. }
  222. private static function readFailed(string $code, Throwable $e): never
  223. {
  224. if (app()->bound('log')) Log::error('payment_provider_config_read_failed', ['payment_company' => $code, 'exception' => $e]);
  225. throw new RuntimeException('支付商户配置读取失败,请联系管理员', 0, $e);
  226. }
  227. private static function resolve(array $fields, array $stored): array
  228. {
  229. $values = [];
  230. foreach ($fields as $field => $definition) {
  231. $values[$field] = array_key_exists($field, $stored) ? (string)$stored[$field] : self::fallback($definition);
  232. }
  233. return $values;
  234. }
  235. private static function assertNoPendingOrders(string $code): void
  236. {
  237. $orders = PaymentOrder::query()->whereIn('type', [PaymentOrderService::TYPE_PAY, PaymentOrderService::TYPE_PAYOUT])
  238. ->whereNotIn('status', [PaymentOrderService::STATUS_SUCCESS, PaymentOrderService::STATUS_FAIL, PaymentOrderService::STATUS_CANCEL])
  239. ->lockForUpdate()->get(['type', 'channel']);
  240. foreach ($orders as $order) {
  241. if (PaymentProviderService::providerForRequest((string)$order->channel, (int)$order->type) === $code) {
  242. throw ValidationException::withMessages(['config' => '该支付公司存在未完成订单,暂不能修改商户号或密钥;请先停用公司并处理完订单']);
  243. }
  244. }
  245. }
  246. private static function fallback(array $definition): string
  247. {
  248. if (isset($definition['env'])) return (string)config($definition['env'], $definition['default'] ?? '');
  249. return (string)($definition['default'] ?? '');
  250. }
  251. }