YzyController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Components\Helpers;
  4. use App\Http\Controllers\Controller;
  5. use App\Http\Models\Goods;
  6. use App\Http\Models\GoodsLabel;
  7. use App\Http\Models\Order;
  8. use App\Http\Models\Payment;
  9. use App\Http\Models\PaymentCallback;
  10. use App\Http\Models\SsNode;
  11. use App\Http\Models\SsNodeLabel;
  12. use App\Http\Models\User;
  13. use App\Http\Models\UserLabel;
  14. use App\Mail\sendUserInfo;
  15. use DB;
  16. use Hash;
  17. use Illuminate\Http\Request;
  18. use Log;
  19. use Mail;
  20. /**
  21. * 有赞云支付消息推送接收
  22. *
  23. * Class YzyController
  24. *
  25. * @package App\Http\Controllers
  26. */
  27. class YzyController extends Controller
  28. {
  29. protected static $systemConfig;
  30. function __construct()
  31. {
  32. self::$systemConfig = Helpers::systemConfig();
  33. }
  34. // 接收GET请求
  35. public function index(Request $request)
  36. {
  37. \Log::info("【有赞云】回调接口[GET]:" . var_export($request->all(), true) . '[' . getClientIp() . ']');
  38. exit("【有赞云】接口正常");
  39. }
  40. // 接收POST请求
  41. public function store(Request $request)
  42. {
  43. \Log::info("【有赞云】回调接口[POST]:" . var_export($request->all(), true));
  44. $json = file_get_contents('php://input');
  45. $data = json_decode($json, true);
  46. if (!$data) {
  47. Log::info('YZY-POST:回调数据无法解析,可能是非法请求[' . getClientIp() . ']');
  48. exit();
  49. }
  50. // 判断消息是否合法
  51. $msg = $data['msg'];
  52. $sign_string = self::$systemConfig['youzan_client_id'] . "" . $msg . "" . self::$systemConfig['youzan_client_secret'];
  53. $sign = md5($sign_string);
  54. if ($sign != $data['sign']) {
  55. Log::info('本地签名:' . $sign_string . ' | 远程签名:' . $data['sign']);
  56. Log::info('YZY-POST:回调数据签名错误,可能是非法请求[' . getClientIp() . ']');
  57. exit();
  58. } else {
  59. // 返回请求成功标识给有赞
  60. var_dump(["code" => 0, "msg" => "success"]);
  61. }
  62. // 容错
  63. if (!isset($data['kdt_name'])) {
  64. Log::info("【有赞云】回调数据解析错误,请检查有赞支付设置是否与有赞控制台中的信息保持一致。如果还出现此提示,请执行一遍php artisan cache:clear命令");
  65. exit();
  66. }
  67. // 先写入回调日志
  68. $this->callbackLog($data['client_id'], $data['id'], $data['kdt_id'], $data['kdt_name'], $data['mode'], $data['msg'], $data['sendCount'], $data['sign'], $data['status'], $data['test'], $data['type'], $data['version']);
  69. // msg内容经过 urlencode 编码,进行解码
  70. $msg = json_decode(urldecode($msg), true);
  71. switch ($data['type']) {
  72. case 'trade_TradePaid':
  73. $this->tradePaid($msg);
  74. break;
  75. case 'trade_TradeCreate':
  76. $this->tradeCreate($msg);
  77. break;
  78. case 'trade_TradeClose':
  79. $this->tradeClose($msg);
  80. break;
  81. case 'trade_TradeSuccess':
  82. $this->tradeSuccess($msg);
  83. break;
  84. case 'trade_TradePartlySellerShip':
  85. $this->tradePartlySellerShip($msg);
  86. break;
  87. case 'trade_TradeSellerShip':
  88. $this->tradeSellerShip($msg);
  89. break;
  90. case 'trade_TradeBuyerPay':
  91. $this->tradeBuyerPay($msg);
  92. break;
  93. case 'trade_TradeMemoModified':
  94. $this->tradeMemoModified($msg);
  95. break;
  96. default:
  97. Log::info('【有赞云】回调无法识别,可能是没有启用[交易消息V3]接口,请到有赞云控制台启用消息推送服务');
  98. exit();
  99. }
  100. exit();
  101. }
  102. // 交易支付
  103. private function tradePaid($msg)
  104. {
  105. Log::info('【有赞云】回调交易支付');
  106. $payment = Payment::query()->with(['order', 'order.goods'])->where('qr_id', $msg['qr_info']['qr_id'])->first();
  107. if (!$payment) {
  108. Log::info('【有赞云】回调订单不存在');
  109. exit();
  110. }
  111. if ($payment->status != '0') {
  112. Log::info('【有赞云】回调订单状态不正确');
  113. exit();
  114. }
  115. // 处理订单
  116. DB::beginTransaction();
  117. try {
  118. // 如果支付单中没有用户信息则创建一个用户
  119. if (!$payment->user_id) {
  120. // 生成一个可用端口
  121. $port = self::$systemConfig['is_rand_port'] ? Helpers::getRandPort() : Helpers::getOnlyPort();
  122. $user = new User();
  123. $user->username = '自动生成-' . $payment->order->email;
  124. $user->password = Hash::make(makeRandStr());
  125. $user->port = $port;
  126. $user->passwd = makeRandStr();
  127. $user->vmess_id = createGuid();
  128. $user->enable = 1;
  129. $user->method = Helpers::getDefaultMethod();
  130. $user->protocol = Helpers::getDefaultProtocol();
  131. $user->obfs = Helpers::getDefaultObfs();
  132. $user->usage = 1;
  133. $user->transfer_enable = 1; // 新创建的账号给1,防止定时任务执行时发现u + d >= transfer_enable被判为流量超限而封禁
  134. $user->enable_time = date('Y-m-d');
  135. $user->expire_time = date('Y-m-d', strtotime("+" . $payment->order->goods->days . " days"));
  136. $user->reg_ip = getClientIp();
  137. $user->referral_uid = 0;
  138. $user->traffic_reset_day = 0;
  139. $user->status = 1;
  140. $user->save();
  141. if ($user->id) {
  142. Order::query()->where('oid', $payment->oid)->update(['user_id' => $user->id]);
  143. }
  144. }
  145. // 更新支付单
  146. $payment->pay_way = $msg['full_order_info']['order_info']['pay_type_str'] == 'WEIXIN_DAIXIAO' ? 1 : 2; // 1-微信、2-支付宝
  147. $payment->status = 1;
  148. $payment->save();
  149. // 更新订单
  150. $order = Order::query()->with(['user'])->where('oid', $payment->oid)->first();
  151. $order->status = 2;
  152. $order->save();
  153. $goods = Goods::query()->where('id', $order->goods_id)->first();
  154. // 商品为流量或者套餐
  155. if ($goods->type <= 2) {
  156. // 如果买的是套餐,则先将之前购买的所有套餐置都无效,并扣掉之前所有套餐的流量,重置用户已用流量为0
  157. if ($goods->type == 2) {
  158. $existOrderList = Order::query()
  159. ->with(['goods'])
  160. ->whereHas('goods', function ($q) {
  161. $q->where('type', 2);
  162. })
  163. ->where('user_id', $order->user_id)
  164. ->where('oid', '<>', $order->oid)
  165. ->where('is_expire', 0)
  166. ->where('status', 2)
  167. ->get();
  168. foreach ($existOrderList as $vo) {
  169. Order::query()->where('oid', $vo->oid)->update(['is_expire' => 1]);
  170. // 先判断,防止手动扣减过流量的用户流量被扣成负数
  171. if ($order->user->transfer_enable - $vo->goods->traffic * 1048576 <= 0) {
  172. // 写入用户流量变动记录
  173. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, 0, 0, '[在线支付]用户购买套餐,先扣减之前套餐的流量(扣完)');
  174. User::query()->where('id', $order->user_id)->update(['u' => 0, 'd' => 0, 'transfer_enable' => 0]);
  175. } else {
  176. // 写入用户流量变动记录
  177. $user = User::query()->where('id', $order->user_id)->first(); // 重新取出user信息
  178. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, $user->transfer_enable, ($user->transfer_enable - $vo->goods->traffic * 1048576), '[在线支付]用户购买套餐,先扣减之前套餐的流量(未扣完)');
  179. User::query()->where('id', $order->user_id)->update(['u' => 0, 'd' => 0]);
  180. User::query()->where('id', $order->user_id)->decrement('transfer_enable', $vo->goods->traffic * 1048576);
  181. }
  182. }
  183. }
  184. // 写入用户流量变动记录
  185. $user = User::query()->where('id', $order->user_id)->first(); // 重新取出user信息
  186. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, $user->transfer_enable, ($user->transfer_enable + $goods->traffic * 1048576), '[在线支付]用户购买商品,加上流量');
  187. // 计算账号过期时间
  188. if ($order->user->expire_time < date('Y-m-d', strtotime("+" . $goods->days . " days"))) {
  189. $expireTime = date('Y-m-d', strtotime("+" . $goods->days . " days"));
  190. } else {
  191. $expireTime = $order->user->expire_time;
  192. }
  193. // 把商品的流量加到账号上
  194. User::query()->where('id', $order->user_id)->increment('transfer_enable', $goods->traffic * 1048576);
  195. // 套餐就改流量重置日,流量包不改
  196. if ($goods->type == 2) {
  197. if (date('m') == 2 && date('d') == 29) {
  198. $traffic_reset_day = 28;
  199. } else {
  200. $traffic_reset_day = date('d') == 31 ? 30 : abs(date('d'));
  201. }
  202. User::query()->where('id', $order->user_id)->update(['traffic_reset_day' => $traffic_reset_day, 'expire_time' => $expireTime, 'enable' => 1]);
  203. } else {
  204. User::query()->where('id', $order->user_id)->update(['expire_time' => $expireTime, 'enable' => 1]);
  205. }
  206. // 写入用户标签
  207. if ($goods->label) {
  208. // 用户默认标签
  209. $defaultLabels = [];
  210. if (self::$systemConfig['initial_labels_for_user']) {
  211. $defaultLabels = explode(',', self::$systemConfig['initial_labels_for_user']);
  212. }
  213. // 取出现有的标签
  214. $userLabels = UserLabel::query()->where('user_id', $order->user_id)->pluck('label_id')->toArray();
  215. $goodsLabels = GoodsLabel::query()->where('goods_id', $order->goods_id)->pluck('label_id')->toArray();
  216. // 标签去重
  217. $newUserLabels = array_values(array_unique(array_merge($userLabels, $goodsLabels, $defaultLabels)));
  218. // 删除用户所有标签
  219. UserLabel::query()->where('user_id', $order->user_id)->delete();
  220. // 生成标签
  221. foreach ($newUserLabels as $vo) {
  222. $obj = new UserLabel();
  223. $obj->user_id = $order->user_id;
  224. $obj->label_id = $vo;
  225. $obj->save();
  226. }
  227. }
  228. // 写入返利日志
  229. if ($order->user->referral_uid) {
  230. $this->addReferralLog($order->user_id, $order->user->referral_uid, $order->oid, $order->amount, $order->amount * self::$systemConfig['referral_percent']);
  231. }
  232. // 取消重复返利
  233. User::query()->where('id', $order->user_id)->update(['referral_uid' => 0]);
  234. } elseif ($goods->type == 3) { // 商品为在线充值
  235. User::query()->where('id', $order->user_id)->increment('balance', $goods->price * 100);
  236. // 余额变动记录日志
  237. $this->addUserBalanceLog($order->user_id, $order->oid, $order->user->balance, $order->user->balance + $goods->price, $goods->price, '用户在线充值');
  238. }
  239. // 自动提号机:如果order的email值不为空
  240. if ($order->email) {
  241. $title = '自动发送账号信息';
  242. $content = [
  243. 'order_sn' => $order->order_sn,
  244. 'goods_name' => $order->goods->name,
  245. 'goods_traffic' => flowAutoShow($order->goods->traffic * 1048576),
  246. 'port' => $order->user->port,
  247. 'passwd' => $order->user->passwd,
  248. 'method' => $order->user->method,
  249. //'protocol' => $order->user->protocol,
  250. //'protocol_param' => $order->user->protocol_param,
  251. //'obfs' => $order->user->obfs,
  252. //'obfs_param' => $order->user->obfs_param,
  253. 'created_at' => $order->created_at->toDateTimeString(),
  254. 'expire_at' => $order->expire_at
  255. ];
  256. // 获取可用节点列表
  257. $labels = UserLabel::query()->where('user_id', $order->user_id)->get()->pluck('label_id');
  258. $nodeIds = SsNodeLabel::query()->whereIn('label_id', $labels)->get()->pluck('node_id');
  259. $nodeList = SsNode::query()->whereIn('id', $nodeIds)->orderBy('sort', 'desc')->orderBy('id', 'desc')->get()->toArray();
  260. $content['serverList'] = $nodeList;
  261. $logId = Helpers::addEmailLog($order->email, $title, json_encode($content));
  262. Mail::to($order->email)->send(new sendUserInfo($logId, $content));
  263. }
  264. DB::commit();
  265. } catch (\Exception $e) {
  266. DB::rollBack();
  267. Log::info('【有赞云】回调更新支付单和订单异常:' . $e->getMessage());
  268. }
  269. exit();
  270. }
  271. // 创建交易
  272. private function tradeCreate($msg)
  273. {
  274. Log::info('【有赞云】回调创建交易');
  275. exit();
  276. }
  277. // 关闭交易(无视,系统自带15分钟自动关闭未支付订单的定时任务)
  278. private function tradeClose($msg)
  279. {
  280. Log::info('【有赞云】回调关闭交易');
  281. exit();
  282. }
  283. // 交易成功
  284. private function tradeSuccess($msg)
  285. {
  286. Log::info('【有赞云】回调交易成功');
  287. exit();
  288. }
  289. // 卖家部分发货
  290. private function tradePartlySellerShip($msg)
  291. {
  292. Log::info('【有赞云】回调卖家部分发货');
  293. exit();
  294. }
  295. // 卖家发货
  296. private function tradeSellerShip($msg)
  297. {
  298. Log::info('【有赞云】回调卖家发货');
  299. exit();
  300. }
  301. // 买家付款
  302. private function tradeBuyerPay($msg)
  303. {
  304. Log::info('【有赞云】回调买家付款');
  305. exit();
  306. }
  307. // 卖家修改交易备注
  308. private function tradeMemoModified($msg)
  309. {
  310. Log::info('【有赞云】回调卖家修改交易备注');
  311. exit();
  312. }
  313. public function show(Request $request)
  314. {
  315. exit('show');
  316. }
  317. // 写入回调请求日志
  318. private function callbackLog($client_id, $yz_id, $kdt_id, $kdt_name, $mode, $msg, $sendCount, $sign, $status, $test, $type, $version)
  319. {
  320. $obj = new PaymentCallback();
  321. $obj->client_id = $client_id;
  322. $obj->yz_id = $yz_id;
  323. $obj->kdt_id = $kdt_id;
  324. $obj->kdt_name = $kdt_name;
  325. $obj->mode = $mode;
  326. $obj->msg = urldecode($msg);
  327. $obj->sendCount = $sendCount;
  328. $obj->sign = $sign;
  329. $obj->status = $status;
  330. $obj->test = $test;
  331. $obj->type = $type;
  332. $obj->version = $version;
  333. $obj->save();
  334. return $obj->id;
  335. }
  336. }