StarPayCashierLogic.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\Constant\Payment;
  4. use App\dao\Estatisticas\RechargeWithDraw;
  5. use App\Http\helper\NumConfig;
  6. use App\Inter\CashierInterFace;
  7. use App\Models\PrivateMail;
  8. use App\Models\RecordUserDataStatistics;
  9. use App\Services\PayConfig;
  10. use App\Services\StarPayService;
  11. use App\Services\StoredProcedure;
  12. use App\Util;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. class StarPayCashierLogic implements CashierInterFace
  17. {
  18. /**
  19. * 代付渠道标识,对应 agent.dbo.admin_configs.config_value(type=cash)。
  20. * 使用前请在后台配置同名渠道值。
  21. */
  22. const AGENT = 107;
  23. /**
  24. * 创建 StarPay 代付订单。
  25. */
  26. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  27. {
  28. // 查询提现订单
  29. $query = DB::connection('write')
  30. ->table('QPAccountsDB.dbo.OrderWithDraw')
  31. ->where('RecordID', $RecordID)
  32. ->first();
  33. if (!$query) {
  34. Util::WriteLog('StarPay', 'withdraw order not found: '.$RecordID);
  35. return 'fail';
  36. }
  37. $config = (new PayConfig())->getConfig('StarPayOut');
  38. $service = new StarPayService($config);
  39. // 账户号:优先 PixNum,其次 BankNO
  40. $account = $PixNum ?: $BankNO;
  41. if (!$account) {
  42. Util::WriteLog('StarPay_error', 'missing account for withdraw: '.$OrderId);
  43. return 'fail';
  44. }
  45. // 银行编号:优先 BankNO(如果看作 bankId),否则使用配置默认
  46. $bankId = $BranchBank;
  47. if ($bankId === '') {
  48. Util::WriteLog('StarPay_error', 'missing bankId for withdraw: '.$OrderId);
  49. return 'fail';
  50. }
  51. // 提现金额是以分存储,转成两位小数金额
  52. $orderAmount = number_format($amount / 100, 2, '.', '');
  53. $bankList = config('games.mex_bank_list');
  54. try {
  55. $data = $service->cash($OrderId, $orderAmount, $bankId, $bankList[$bankId] ?? '', $account, $accountName);
  56. if ($data === false) {
  57. return 'fail';
  58. }
  59. } catch (\Throwable $e) {
  60. Util::WriteLog('StarPay_error', 'payout request exception: '.$e->getMessage());
  61. return '';
  62. }
  63. // 文档示例:code=200 且 data.transactionStatus = "00" 表示下单成功
  64. if (isset($data['code']) && (string)$data['code'] === '0') {
  65. $transactionStatus = $data['data']['orderStatus'] ?? -99;
  66. if ($transactionStatus >= 0) {
  67. return $data;
  68. }
  69. if ($transactionStatus == -4 || $transactionStatus == -99) {
  70. return $data;
  71. }
  72. }
  73. // 同步下单失败:如果订单在处理中(State=5),退回资金并标记失败
  74. if ((int)$query->State === 5) {
  75. $msg = $data['msg'] ?? 'StarPay payout failed';
  76. $WithDraw = $query->WithDraw + $query->ServiceFee;
  77. $bonus = '30000,'.$WithDraw;
  78. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  79. $withdraw_data = [
  80. 'State' => 6,
  81. 'agent' => self::AGENT,
  82. 'finishDate' => now(),
  83. 'remark' => json_encode($data),
  84. ];
  85. DB::connection('write')
  86. ->table('QPAccountsDB.dbo.OrderWithDraw')
  87. ->where('OrderId', $query->OrderId)
  88. ->update($withdraw_data);
  89. $RecordData = ['after_state' => 6, 'update_at' => now()];
  90. DB::connection('write')
  91. ->table('QPAccountsDB.dbo.AccountsRecord')
  92. ->where('type', 1)
  93. ->where('RecordID', $RecordID)
  94. ->update($RecordData);
  95. }
  96. return 'fail';
  97. }
  98. /**
  99. * StarPay代付回调。
  100. *
  101. * @param array<string,mixed>|string $post
  102. */
  103. public function notify($post)
  104. {
  105. if (!is_array($post)) {
  106. $post = \GuzzleHttp\json_decode($post, true);
  107. }
  108. Util::WriteLog('StarPay', 'payout notify: '.json_encode($post, JSON_UNESCAPED_UNICODE));
  109. $config = (new PayConfig())->getConfig('StarPayOut');
  110. $service = new StarPayService($config);
  111. // 验签
  112. if (!$service->verifySign($post)) {
  113. Util::WriteLog('StarPay_error', 'notify sign invalid');
  114. return 'fail';
  115. }
  116. $res = $service->cashNotify($post);
  117. if (in_array($res->status, [Payment::STATUS_UNKNOWN, Payment::STATUS_IN_PROGRESS])) {
  118. Util::WriteLog('StarPay', 'ignore non-payout notify');
  119. return 'success';
  120. }
  121. $OrderId = $post['merOrderNo'] ?? '';
  122. if ($OrderId === '') {
  123. Util::WriteLog('StarPay_error', 'notify missing merOrderId');
  124. return 'fail';
  125. }
  126. $query = DB::connection('write')
  127. ->table('QPAccountsDB.dbo.OrderWithDraw')
  128. ->where('OrderId', $OrderId)
  129. ->first();
  130. if (!$query) {
  131. Util::WriteLog('StarPay_error', 'withdraw order not found in notify: '.$OrderId);
  132. return 'success';
  133. }
  134. // 只处理 State=5 或 7 的订单,避免重复
  135. if (!in_array((int)$query->State, [5, 7], true)) {
  136. Util::WriteLog('StarPay', 'withdraw already handled: '.$OrderId);
  137. return 'success';
  138. }
  139. $agentID = DB::connection('write')
  140. ->table('agent.dbo.admin_configs')
  141. ->where('config_value', self::AGENT)
  142. ->where('type', 'cash')
  143. ->value('id') ?? '';
  144. $now = now();
  145. $UserID = $query->UserID;
  146. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  147. // Supefina 回调里带有 amount/fee 和 realityAmount/realityFee
  148. // 提醒:这里仍以我们订单金额为准做账,仅将真实金额用于日志,可根据需要扩展到统计侧。
  149. $realityAmount = isset($post['amount']) ? (float)$post['amount'] : null;
  150. $realityFee = isset($post['tradeCharge']) ? (float)$post['tradeCharge'] : null;
  151. Util::WriteLog('StarPay', 'payout reality: amount='.$realityAmount.', fee='.$realityFee.', orderId='.$OrderId);
  152. $withdraw_data = [];
  153. switch ($res->status) {
  154. case Payment::STATUS_SUCCESS: // 提现成功
  155. $withdraw_data = [
  156. 'State' => 2,
  157. 'agent' => $agentID,
  158. 'finishDate' => $now,
  159. 'withdraw_fee' => $realityFee * NumConfig::NUM_VALUE,
  160. ];
  161. // 增加提现记录
  162. $first = DB::connection('write')
  163. ->table('QPAccountsDB.dbo.UserTabData')
  164. ->where('UserID', $UserID)
  165. ->first();
  166. if ($first) {
  167. DB::connection('write')
  168. ->table('QPAccountsDB.dbo.UserTabData')
  169. ->where('UserID', $UserID)
  170. ->increment('TakeMoney', $TakeMoney);
  171. } else {
  172. DB::connection('write')
  173. ->table('QPAccountsDB.dbo.UserTabData')
  174. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  175. try {
  176. PrivateMail::praiseSendMail($UserID);
  177. } catch (\Throwable $e) {
  178. // 忽略邮件发送失败
  179. }
  180. }
  181. // 免审记录
  182. $withdrawal_position_log = DB::connection('write')
  183. ->table('agent.dbo.withdrawal_position_log')
  184. ->where('order_sn', $OrderId)
  185. ->first();
  186. if ($withdrawal_position_log) {
  187. DB::connection('write')
  188. ->table('agent.dbo.withdrawal_position_log')
  189. ->where('order_sn', $OrderId)
  190. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  191. }
  192. try {
  193. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  194. } catch (\Throwable $exception) {
  195. Util::WriteLog('StoredProcedure', $exception->getMessage());
  196. }
  197. $ServiceFee = $query->ServiceFee;
  198. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  199. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $realityFee * NumConfig::NUM_VALUE, $ServiceFee);
  200. $redis = Redis::connection();
  201. $redis->incr('draw_'.date('Ymd').$UserID);
  202. break;
  203. case Payment::STATUS_FAIL: // 提现失败
  204. $msg = $post['msg'] ?? 'Withdraw rejected';
  205. $bonus = '30000,'.$TakeMoney;
  206. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  207. Util::WriteLog('SupefinaSpeiEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  208. $withdraw_data = [
  209. 'State' => 6,
  210. 'agent' => $agentID,
  211. 'remark' => $msg,
  212. ];
  213. break;
  214. case Payment::STATUS_REFUND:
  215. Log::error('代付订单退款', ['data' => $post]);
  216. return 'success';
  217. }
  218. $RecordData = [
  219. 'before_state' => $query->State,
  220. 'after_state' => $withdraw_data['State'] ?? 0,
  221. 'RecordID' => $query->RecordID,
  222. 'update_at' => date('Y-m-d H:i:s'),
  223. ];
  224. DB::connection('write')
  225. ->table('QPAccountsDB.dbo.AccountsRecord')
  226. ->updateOrInsert(
  227. ['RecordID' => $query->RecordID, 'type' => 1],
  228. $RecordData
  229. );
  230. DB::connection('write')
  231. ->table('QPAccountsDB.dbo.OrderWithDraw')
  232. ->where('OrderId', $OrderId)
  233. ->update($withdraw_data);
  234. if (isset($withdraw_data['State']) && (int)$withdraw_data['State'] === 2) {
  235. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  236. }
  237. return 'success';
  238. }
  239. }