PaymentConfiguration.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\OperationAudit;
  6. use App\Models\PaymentCollectionChannel;
  7. use App\Models\PaymentDirectRecharge;
  8. use App\Models\PaymentGateway;
  9. use App\Models\RechargeChannel;
  10. use App\Models\RechargeChannelGroup;
  11. use App\Services\OperationAuditService;
  12. use App\Services\PaymentChannelLinkService;
  13. use App\Services\Payment\PaymentProviderCatalog;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Validation\Rule;
  17. use Illuminate\Validation\ValidationException;
  18. use Throwable;
  19. class PaymentConfiguration extends Controller
  20. {
  21. private PaymentChannelLinkService $channelLinks;
  22. public function __construct(PaymentChannelLinkService $channelLinks)
  23. {
  24. parent::__construct();
  25. $this->channelLinks = $channelLinks;
  26. }
  27. public function options()
  28. {
  29. return $this->run(function () {
  30. $filters = request()->validate([
  31. 'kind' => ['nullable', Rule::in(['deposit', 'withdraw', 'collection_scan', 'collection_third_party'])],
  32. 'payment_company' => ['nullable', Rule::in(PaymentProviderCatalog::codes())],
  33. 'provider_name' => ['nullable', Rule::in(PaymentProviderCatalog::codes())],
  34. 'payment_method' => ['nullable', 'string', 'max:64'],
  35. 'collection_method' => ['nullable', 'string', 'max:64'],
  36. ]);
  37. return (new PaymentProviderCatalog())->options(
  38. RechargeChannel::query()->orderBy('data_type')->orderBy('sort')->orderBy('id')->get()->toArray(),
  39. RechargeChannelGroup::query()->orderBy('id')->get()->toArray(),
  40. $filters
  41. );
  42. });
  43. }
  44. public function directList()
  45. {
  46. return $this->run(function () {
  47. $params = request()->validate($this->listRules([
  48. 'name' => ['nullable', 'string', 'max:100'],
  49. 'recharge_channel_id' => ['nullable', 'integer'],
  50. 'group_id' => ['nullable', 'integer'],
  51. 'status' => ['nullable', Rule::in([0, 1])],
  52. 'start_date' => ['nullable', 'date_format:Y-m-d'],
  53. 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  54. ]));
  55. $query = PaymentDirectRecharge::query()->with('rechargeChannel');
  56. $this->applyDateAndLike($query, $params, 'name');
  57. $this->applyChannelFilters($query, $params);
  58. return $this->paginatePayment($query->orderByDesc('id'), $params);
  59. });
  60. }
  61. public function directSave()
  62. {
  63. return $this->run(function () {
  64. $params = request()->validate([
  65. 'id' => ['nullable', 'integer'],
  66. 'recharge_channel_id' => ['required', 'integer'],
  67. 'recharge_channel_group_ids' => ['required', 'array', 'min:1'],
  68. 'recharge_channel_group_ids.*' => ['integer'],
  69. 'recharge_code' => ['required', 'string', 'max:64'],
  70. 'name' => ['required', 'string', 'max:100'],
  71. 'amount' => ['required', 'numeric', 'gt:0'],
  72. 'status' => ['nullable', Rule::in([0, 1])],
  73. ]);
  74. [, $params['recharge_channel_group_ids']] = $this->channelLinks->validate(
  75. (int)$params['recharge_channel_id'],
  76. $params['recharge_channel_group_ids'],
  77. 1
  78. );
  79. $id = (int)($params['id'] ?? 0);
  80. $duplicate = PaymentDirectRecharge::query()->where('recharge_code', $params['recharge_code']);
  81. if ($id) $duplicate->where('id', '<>', $id);
  82. if ($duplicate->exists()) throw new \RuntimeException('充值ID已存在');
  83. return $this->saveModel(PaymentDirectRecharge::class, $params, 'payment_direct_recharge');
  84. });
  85. }
  86. public function directStatus()
  87. {
  88. return $this->setStatus(PaymentDirectRecharge::class, 'payment_direct_recharge');
  89. }
  90. public function directDelete()
  91. {
  92. return $this->deleteModel(PaymentDirectRecharge::class, 'payment_direct_recharge');
  93. }
  94. public function gatewayList()
  95. {
  96. return $this->run(function () {
  97. $params = request()->validate($this->listRules([
  98. 'kind' => ['required', Rule::in(['deposit', 'withdraw'])],
  99. 'recharge_channel_id' => ['nullable', 'integer'],
  100. 'group_id' => ['nullable', 'integer'],
  101. 'payment_company' => ['nullable', 'string', 'max:100'],
  102. 'payment_method' => ['nullable', 'string', 'max:64'],
  103. 'status' => ['nullable', Rule::in([0, 1])],
  104. ]));
  105. $query = PaymentGateway::query()->with('rechargeChannel')->where('kind', $params['kind']);
  106. foreach (['payment_company', 'payment_method', 'status'] as $field) {
  107. if (array_key_exists($field, $params) && $params[$field] !== null && $params[$field] !== '') {
  108. $query->where($field, $params[$field]);
  109. }
  110. }
  111. $this->applyChannelFilters($query, $params);
  112. return $this->paginatePayment($query->orderByDesc('id'), $params);
  113. });
  114. }
  115. public function gatewaySave()
  116. {
  117. return $this->run(function () {
  118. $params = request()->validate([
  119. 'id' => ['nullable', 'integer'],
  120. 'recharge_channel_id' => ['required', 'integer'],
  121. 'recharge_channel_group_ids' => ['required', 'array', 'min:1'],
  122. 'recharge_channel_group_ids.*' => ['integer'],
  123. 'kind' => ['required', Rule::in(['deposit', 'withdraw'])],
  124. 'currency' => ['nullable', 'string', 'max:16'],
  125. 'payment_company' => ['required', Rule::in(PaymentProviderCatalog::codes())],
  126. 'merchant_no' => ['required', 'string', 'max:128'],
  127. 'payment_method' => ['required', 'string', 'max:64'],
  128. 'channel_code' => ['nullable', 'string', 'max:64'],
  129. 'channel_name' => ['nullable', 'string', 'max:100'],
  130. 'withdrawal_secret' => ['nullable', 'string', 'max:10000'],
  131. 'deposit_secret' => ['nullable', 'string', 'max:10000'],
  132. 'status' => ['nullable', Rule::in([0, 1])],
  133. ]);
  134. $expectedDataType = $params['kind'] === 'withdraw' ? 2 : 1;
  135. [$channel, $params['recharge_channel_group_ids']] = $this->channelLinks->validate(
  136. (int)$params['recharge_channel_id'],
  137. $params['recharge_channel_group_ids'],
  138. $expectedDataType
  139. );
  140. PaymentProviderCatalog::validateSelection($channel->toArray(), $params['payment_company'], $params['payment_method'], $expectedDataType);
  141. return $this->saveModel(PaymentGateway::class, $params, 'payment_gateway');
  142. });
  143. }
  144. public function gatewayStatus()
  145. {
  146. return $this->setStatus(PaymentGateway::class, 'payment_gateway');
  147. }
  148. public function gatewayDelete()
  149. {
  150. return $this->deleteModel(PaymentGateway::class, 'payment_gateway');
  151. }
  152. public function collectionList()
  153. {
  154. return $this->run(function () {
  155. $params = request()->validate($this->listRules([
  156. 'kind' => ['required', Rule::in(['collection_scan', 'collection_third_party'])],
  157. 'recharge_channel_id' => ['nullable', 'integer'],
  158. 'group_id' => ['nullable', 'integer'],
  159. 'provider_name' => ['nullable', 'string', 'max:100'],
  160. 'collection_method' => ['nullable', 'string', 'max:64'],
  161. 'status' => ['nullable', Rule::in([0, 1])],
  162. ]));
  163. $query = PaymentCollectionChannel::query()->with('rechargeChannel')->where('kind', $params['kind']);
  164. foreach (['provider_name', 'collection_method', 'status'] as $field) {
  165. if (array_key_exists($field, $params) && $params[$field] !== null && $params[$field] !== '') {
  166. $query->where($field, $params[$field]);
  167. }
  168. }
  169. $this->applyChannelFilters($query, $params);
  170. return $this->paginatePayment($query->orderByDesc('id'), $params);
  171. });
  172. }
  173. public function collectionSave()
  174. {
  175. return $this->run(function () {
  176. $params = request()->validate([
  177. 'id' => ['nullable', 'integer'],
  178. 'recharge_channel_id' => ['required', 'integer'],
  179. 'recharge_channel_group_ids' => ['required', 'array', 'min:1'],
  180. 'recharge_channel_group_ids.*' => ['integer'],
  181. 'kind' => ['required', Rule::in(['collection_scan', 'collection_third_party'])],
  182. 'currency' => ['nullable', 'string', 'max:16'],
  183. 'provider_name' => ['required', Rule::in(PaymentProviderCatalog::codes())],
  184. 'group_name' => ['required', 'string', 'max:100'],
  185. 'collection_method' => ['required', 'string', 'max:64'],
  186. 'channel_code' => ['required', 'string', 'max:64'],
  187. 'channel_name' => ['required', 'string', 'max:100'],
  188. 'status' => ['nullable', Rule::in([0, 1])],
  189. ]);
  190. [$channel, $params['recharge_channel_group_ids']] = $this->channelLinks->validate(
  191. (int)$params['recharge_channel_id'],
  192. $params['recharge_channel_group_ids'],
  193. 1
  194. );
  195. PaymentProviderCatalog::validateSelection($channel->toArray(), $params['provider_name'], $params['collection_method'], 1);
  196. return $this->saveModel(PaymentCollectionChannel::class, $params, 'payment_collection_channel');
  197. });
  198. }
  199. public function collectionStatus()
  200. {
  201. return $this->setStatus(PaymentCollectionChannel::class, 'payment_collection_channel');
  202. }
  203. public function collectionDelete()
  204. {
  205. return $this->deleteModel(PaymentCollectionChannel::class, 'payment_collection_channel');
  206. }
  207. public function logs()
  208. {
  209. return $this->run(function () {
  210. $params = request()->validate($this->listRules([
  211. 'resource_type' => ['required', Rule::in([
  212. 'payment_direct_recharge', 'payment_gateway', 'payment_collection_channel',
  213. ])],
  214. 'resource_id' => ['required', 'integer'],
  215. 'operator_name' => ['nullable', 'string', 'max:100'],
  216. 'start_date' => ['nullable', 'date_format:Y-m-d'],
  217. 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  218. ]));
  219. $query = OperationAudit::query()
  220. ->where('resource_type', $params['resource_type'])
  221. ->where('resource_id', $params['resource_id']);
  222. if (!empty($params['operator_name'])) $query->where('operator_name', 'like', '%' . $params['operator_name'] . '%');
  223. if (!empty($params['start_date'])) $query->where('created_at', '>=', $params['start_date'] . ' 00:00:00');
  224. if (!empty($params['end_date'])) $query->where('created_at', '<=', $params['end_date'] . ' 23:59:59');
  225. return $this->paginate($query->orderByDesc('id'), $params);
  226. });
  227. }
  228. private function saveModel(string $modelClass, array $params, string $resourceType): array
  229. {
  230. return DB::transaction(function () use ($modelClass, $params, $resourceType) {
  231. $id = (int)($params['id'] ?? 0);
  232. unset($params['id']);
  233. $params += OperationAuditService::actor();
  234. $model = $id ? $modelClass::query()->lockForUpdate()->findOrFail($id) : new $modelClass();
  235. if ($model instanceof PaymentGateway) $params = $this->gatewayCredentials($model, $params);
  236. $before = $model->exists ? $model->replicate()->setRawAttributes($model->getRawOriginal()) : [];
  237. $model->fill($params);
  238. $model->save();
  239. OperationAuditService::record($resourceType, (int)$model->id, $id ? 'update' : 'create', $before, $model);
  240. return $this->channelLinks->formatOne($model->fresh()->load('rechargeChannel'));
  241. });
  242. }
  243. private function setStatus(string $modelClass, string $resourceType)
  244. {
  245. return $this->run(function () use ($modelClass, $resourceType) {
  246. $params = request()->validate(['id' => ['required', 'integer'], 'status' => ['required', Rule::in([0, 1])]]);
  247. return DB::transaction(function () use ($modelClass, $resourceType, $params) {
  248. $model = $modelClass::query()->lockForUpdate()->findOrFail($params['id']);
  249. $before = $model->toArray();
  250. $model->fill(['status' => $params['status']] + OperationAuditService::actor())->save();
  251. OperationAuditService::record($resourceType, (int)$model->id, 'status', $before, $model);
  252. return $this->channelLinks->formatOne($model->fresh()->load('rechargeChannel'));
  253. });
  254. });
  255. }
  256. private function gatewayCredentials(PaymentGateway $model, array $params): array
  257. {
  258. if ($model->exists && $model->kind !== $params['kind']) {
  259. throw ValidationException::withMessages(['kind' => '网关类型创建后不能修改']);
  260. }
  261. $secretField = $params['kind'] === 'deposit' ? 'deposit_secret' : 'withdrawal_secret';
  262. $otherField = $params['kind'] === 'deposit' ? 'withdrawal_secret' : 'deposit_secret';
  263. $hasSecret = !empty($model->getRawOriginal($secretField));
  264. $identityChanged = $model->exists && ($model->payment_company !== $params['payment_company']
  265. || $model->merchant_no !== $params['merchant_no']);
  266. $newSecret = $params[$secretField] ?? null;
  267. if ($newSecret === null || $newSecret === '') {
  268. if (!$hasSecret || $identityChanged) {
  269. throw ValidationException::withMessages([$secretField => '新增商户或切换公司/商户号时必须填写签名密钥']);
  270. }
  271. unset($params[$secretField]);
  272. }
  273. $params[$otherField] = null;
  274. return $params;
  275. }
  276. private function deleteModel(string $modelClass, string $resourceType)
  277. {
  278. return $this->run(function () use ($modelClass, $resourceType) {
  279. $params = request()->validate(['id' => ['required', 'integer']]);
  280. return DB::transaction(function () use ($modelClass, $resourceType, $params) {
  281. $model = $modelClass::query()->lockForUpdate()->findOrFail($params['id']);
  282. $before = $model->toArray();
  283. $model->delete();
  284. OperationAuditService::record($resourceType, (int)$model->id, 'delete', $before, []);
  285. return [];
  286. });
  287. });
  288. }
  289. private function listRules(array $extra): array
  290. {
  291. return ['page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:200']] + $extra;
  292. }
  293. private function paginate(Builder $query, array $params): array
  294. {
  295. $page = (int)($params['page'] ?? 1);
  296. $limit = (int)($params['limit'] ?? 20);
  297. return ['total' => (clone $query)->count(), 'data' => $query->forPage($page, $limit)->get()];
  298. }
  299. private function paginatePayment(Builder $query, array $params): array
  300. {
  301. $page = (int)($params['page'] ?? 1);
  302. $limit = (int)($params['limit'] ?? 20);
  303. $total = (clone $query)->count();
  304. $models = $query->forPage($page, $limit)->get();
  305. return ['total' => $total, 'data' => $this->channelLinks->formatMany($models)];
  306. }
  307. private function applyChannelFilters(Builder $query, array $params): void
  308. {
  309. if (!empty($params['recharge_channel_id'])) {
  310. $query->where('recharge_channel_id', (int)$params['recharge_channel_id']);
  311. }
  312. if (!empty($params['group_id'])) {
  313. $query->whereJsonContains('recharge_channel_group_ids', (int)$params['group_id']);
  314. }
  315. if (array_key_exists('status', $params) && $params['status'] !== null && $params['status'] !== '') {
  316. $query->where('status', (int)$params['status']);
  317. }
  318. }
  319. private function applyDateAndLike(Builder $query, array $params, string $likeField): void
  320. {
  321. if (!empty($params[$likeField])) $query->where($likeField, 'like', '%' . $params[$likeField] . '%');
  322. if (!empty($params['start_date'])) $query->where('created_at', '>=', $params['start_date'] . ' 00:00:00');
  323. if (!empty($params['end_date'])) $query->where('created_at', '<=', $params['end_date'] . ' 23:59:59');
  324. }
  325. private function run(callable $callback)
  326. {
  327. try {
  328. return $this->success($callback());
  329. } catch (ValidationException $e) {
  330. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  331. } catch (Throwable $e) {
  332. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  333. }
  334. }
  335. }