Notify.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\service\UserService;
  5. use kjpay\kjpay;
  6. use think\Request;
  7. use think\Db;
  8. use addons\epay\library\Service;
  9. /**
  10. * 支付回调
  11. */
  12. class Notify extends Api
  13. {
  14. protected $noNeedLogin = ['wechatnotify', 'alipaynotify', 'wechatkjnotify'];
  15. protected $noNeedRight = ['*'];
  16. /**
  17. * 支付回调
  18. */
  19. public function wechatnotify()
  20. {
  21. $paytype = "wechat";
  22. $pay = Service::checkNotify($paytype);
  23. if (!$pay) {
  24. echo '签名错误';
  25. return;
  26. }
  27. $data = $pay->verify();
  28. Db::startTrans();
  29. try {
  30. /*$orderModel = new \app\common\model\RecharOrder();
  31. $out_trade_no = $data['out_trade_no'];
  32. $orderinfo = $orderModel->where(["order_no" => $out_trade_no])->find();
  33. if(empty($orderinfo)){
  34. Db::rollback();
  35. echo $pay->success();
  36. exit;
  37. }
  38. if($orderinfo['status'] != 0)
  39. {
  40. Db::rollback();
  41. echo $pay->success();
  42. exit;
  43. }*/
  44. $this->payhandel($data);
  45. Db::commit();
  46. } catch (ValidateException $e) {
  47. Db::rollback();
  48. $this->error($e->getMessage());
  49. } catch (PDOException $e) {
  50. Db::rollback();
  51. $this->error($e->getMessage());
  52. } catch (Exception $e) {
  53. Db::rollback();
  54. $this->error($e->getMessage());
  55. }
  56. echo $pay->success();
  57. }
  58. /**
  59. * 支付回调
  60. */
  61. public function alipaynotify()
  62. {
  63. $paytype = "alipay";
  64. $notify_file = $this->notify_log_start($paytype);
  65. $pay = Service::checkNotify($paytype);
  66. if (!$pay) {
  67. echo '签名错误';
  68. return;
  69. }
  70. $data = $pay->verify();
  71. /*$dataStr = '{
  72. "s": "\/api\/notify\/alipaynotify",
  73. "gmt_create": "2023-07-12 09:37:14",
  74. "charset": "utf-8",
  75. "seller_email": "ixiaoqiuqiu@qq.com",
  76. "subject": "充值钻石",
  77. "sign": "SzP5OgA9Z+qD8mSzMbAbKFsYOyB6fiH\/8itILn6YqX0Aloa5FnOxUHXEKCFlv5k3ya+OORjZPDq5mt7eZ3FvwJUasSWnMgDlSa6zWLGhlkKE3HXVAe777tkM5UgnVw53uJEr\/Ur2UsLpI+qEcrZAXhNAhA2nNNWhwkvrA1Fyc3iZERnbtJ3XNT\/8nnxGMBjhS3TWlr3VDZ\/bb26fvC1qHQ9Y6GGz8gvj3z30Fo7\/DlLFvH2HFSi6wky+33vWEtgug+klsqh6ziOWaVJhJKvnt2H+ltINiKLCshYVhu8ZBc856sV8noEwMmxPoFTW4CoG7ut\/3PKLjglygSOZblyf4Q==",
  78. "buyer_id": "2088702050034935",
  79. "invoice_amount": "0.01",
  80. "notify_id": "2023071201222093714034931493558779",
  81. "fund_bill_list": "[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]",
  82. "notify_type": "trade_status_sync",
  83. "trade_status": "TRADE_SUCCESS",
  84. "receipt_amount": "0.01",
  85. "app_id": "2021004103620776",
  86. "buyer_pay_amount": "0.01",
  87. "sign_type": "RSA2",
  88. "seller_id": "2088641467220712",
  89. "gmt_payment": "2023-07-12 09:37:14",
  90. "notify_time": "2023-07-12 09:37:14",
  91. "version": "1.0",
  92. "out_trade_no": "20230712093707239053",
  93. "total_amount": "0.01",
  94. "trade_no": "2023071222001434931415906799",
  95. "auth_app_id": "2021004103620776",
  96. "buyer_logon_id": "136****5934",
  97. "point_amount": "0.00"
  98. }';
  99. $data = json_decode($dataStr,true);*/
  100. Db::startTrans();
  101. try {
  102. $orderModel = new \app\common\model\RecharOrder();
  103. $out_trade_no = $data['out_trade_no'];
  104. $orderinfo = $orderModel->where(["order_no" => $out_trade_no])->find();
  105. if(empty($orderinfo)){
  106. Db::rollback();
  107. echo $pay->success();
  108. exit;
  109. }
  110. if($orderinfo['status'] != 0)
  111. {
  112. Db::rollback();
  113. echo $pay->success();
  114. exit;
  115. }
  116. $this->payhandel($data);
  117. Db::commit();
  118. } catch (ValidateException $e) {
  119. Db::rollback();
  120. $this->error($e->getMessage());
  121. } catch (PDOException $e) {
  122. Db::rollback();
  123. $this->error($e->getMessage());
  124. } catch (Exception $e) {
  125. Db::rollback();
  126. $this->error($e->getMessage());
  127. }
  128. echo $pay->success();
  129. }
  130. /**
  131. * 支付处理方法
  132. * @return void
  133. */
  134. private function payhandel($params = [])
  135. {
  136. $payamount = $params['total_amount'];
  137. $out_trade_no = $params['out_trade_no'];
  138. $trade_no = $params['trade_no'];
  139. $orderModel = new \app\common\model\RecharOrder();
  140. $userModel = new \app\common\model\User();
  141. $jewellogModel = new \app\common\model\UserJewelLog();
  142. $rechargelogModel = new \app\common\model\UserRechargeLog();
  143. $orderInfo = $orderModel->where(["order_no" => $out_trade_no])->find();
  144. $userInfo = $userModel->where(["id" => $orderInfo["user_id"]])->find();
  145. $time = time();
  146. // 修改订单状态
  147. $res1 = $orderModel->update(["status" => 1,'transaction_id' => $trade_no,'paytime'=>$time], ["order_no" => $out_trade_no]);
  148. // 修改用户钻石余额
  149. $res2 = $userModel->where(["id" => $orderInfo["user_id"]])->setInc("jewel", $orderInfo["jewel"]);
  150. //判断是否首充
  151. $jewellogWhere['user_id'] = $orderInfo["user_id"];
  152. $jewellogWhere['type'] = 1;
  153. $userJewelLog = $jewellogModel->where($jewellogWhere)->find();
  154. $isFirst = 1;
  155. if (!empty($userJewelLog)) {
  156. $isFirst = 0;
  157. }
  158. $preUserId = $userInfo['pre_userid'];
  159. // 添加钻石流水记录
  160. $detail = "钻石充值";
  161. $res3 = $jewellogModel->addUserJewelLog($userInfo["id"], $orderInfo["jewel"], "+", $userInfo["jewel"], $detail, 1);
  162. // 添加充值记录
  163. $res4 = $rechargelogModel->addRecord($userInfo["id"], $orderInfo["jewel"], $payamount, bcadd($userInfo["jewel"], $orderInfo["jewel"], 2), $userInfo["money"], $orderInfo["platform"], 2,$isFirst,$preUserId);
  164. if ($res1 && $res2 && $res3 && $res4) {
  165. // 添加统计
  166. $userInfo->chargecount = $userInfo->chargecount + $payamount;
  167. $userInfo->chargetime = time();
  168. $userInfo->save();
  169. $userService = new UserService();//邀请赠送奖励
  170. $userService->inviteMoney(['user_id'=>$orderInfo["user_id"]]);
  171. // +EXP 充值任意金额
  172. \app\common\model\TaskLog::tofinish($orderInfo["user_id"], "5EMwg7la", 1);
  173. // 查询今日充值记录
  174. $today = strtotime(date("Y-m-d 00:00:00"));
  175. $rechargeMoney = \app\common\model\RecharOrder::where(["user_id" => $orderInfo["user_id"], "createtime" => ["gt", $today]])->sum("money");
  176. if ($rechargeMoney >= 100) {
  177. // +EXP 充值超过100
  178. \app\common\model\TaskLog::tofinish($orderInfo["user_id"], "DaCVgOLu", 1);
  179. }
  180. } else {
  181. $res1 = $orderModel->update(["status" => -1], ["order_no" => $out_trade_no]);
  182. if (!$res1) {
  183. throw new Exception('更新充值状态失败:'.$out_trade_no);
  184. }
  185. }
  186. }
  187. /**
  188. * 支付回调
  189. */
  190. public function wechatkjnotify()
  191. {
  192. $input = file_get_contents("php://input"); // 主题信息
  193. $dataArr = explode("&", urldecode($input));
  194. $data = [];
  195. if ($dataArr) foreach ($dataArr as $k => $v) {
  196. $vv = explode("=", $v);
  197. $data[$vv[0]] = $vv[1];
  198. }
  199. // 实例化支付类
  200. $kjpay = new kjpay();
  201. // 获取公共参数
  202. $config = config("kjPay");
  203. //密钥
  204. $key = $config["key"];
  205. $sign = $data['sign'];
  206. unset($data['sign']);
  207. if ($kjpay->local_sign($data, $key) == $sign) {
  208. //验签成功后,开始业务逻辑
  209. try {
  210. $payamount = $data['amount'];
  211. $out_trade_no = $data['merchant_order_no'];
  212. $pay_channel = $data['pay_channel'];
  213. Db::startTrans();
  214. try {
  215. $orderModel = new \app\common\model\RecharOrder();
  216. $userModel = new \app\common\model\User();
  217. $jewellogModel = new \app\common\model\UserJewelLog();
  218. $rechargelogModel = new \app\common\model\UserRechargeLog();
  219. $orderInfo = $orderModel->where(["order_no" => $out_trade_no])->find();
  220. $userInfo = $userModel->where(["id" => $orderInfo["user_id"]])->find();
  221. // 修改订单状态
  222. $res1 = $orderModel->update(["status" => 1], ["order_no" => $out_trade_no]);
  223. // 修改用户钻石余额
  224. $res2 = $userModel->where(["id" => $orderInfo["user_id"]])->setInc("jewel", $orderInfo["jewel"]);
  225. // 添加钻石流水记录
  226. $detail = "砖石充值";
  227. $res3 = $jewellogModel->addUserJewelLog($userInfo["id"], $orderInfo["jewel"], "+", $userInfo["jewel"], $detail, 1);
  228. // 添加充值记录
  229. $rechargeCount = $rechargelogModel->where('user_id',$orderInfo["user_id"])->count();
  230. $isFirstRecharge = $rechargeCount > 0 ? 0 : 1;
  231. $platformArr = ["wx_app_pay" => 1, "ali_wap_pay" => 2, "wx_public_pay" => 3];
  232. $res4 = $rechargelogModel->addRecord($userInfo["id"], $orderInfo["jewel"], $payamount, bcadd($userInfo["jewel"], $orderInfo["jewel"], 2), $userInfo["money"], $orderInfo["platform"], $platformArr[$pay_channel], $isFirstRecharge, $userInfo["pre_userid"]);
  233. if ($res1 && $res2 && $res3 && $res4) {
  234. // 添加统计
  235. $time = time();
  236. (new \app\common\model\User)->execute("update hx_user set chargecount = chargecount + $payamount,chargetime = $time where id = " . $userInfo["id"]);
  237. // \app\common\model\Test::update(["content"=>"update hx_user set chargecount = chargecount + $payamount,chargetime = $time where id = ".$userInfo["id"]],["id"=>1]);
  238. // 首充赠送
  239. $userInfo = \app\common\model\User::get($orderInfo["user_id"]);
  240. if ($userInfo->is_recharge == 0) { // 首充
  241. Db::startTrans();
  242. try {
  243. // 赠送消息尾灯
  244. $res1 = \app\common\model\AttireBack::addToMyBack(15, $orderInfo["user_id"]);
  245. $userInfo->is_recharge = 1;
  246. $res2 = $userInfo->save();
  247. if ($res1 && $res2) Db::commit();
  248. } catch (ValidateException $e) {
  249. Db::rollback();
  250. $this->error($e->getMessage());
  251. }
  252. }
  253. $this->rebate($orderInfo["user_id"], $data['amount']);
  254. // +EXP
  255. \app\common\model\TaskLog::tofinish($orderInfo["user_id"], "5EMwg7la", 1);
  256. // 查询今日充值记录
  257. $today = strtotime(date("Y-m-d 00:00:00"));
  258. $rechargeMoney = \app\common\model\RecharOrder::where(["user_id" => $orderInfo["user_id"], "createtime" => ["gt", $today]])->sum("money");
  259. if ($rechargeMoney >= 100) {
  260. // +EXP
  261. \app\common\model\TaskLog::tofinish($orderInfo["user_id"], "DaCVgOLu", 1);
  262. }
  263. // 查询新人礼包
  264. $this->addBagGift($orderInfo["user_id"], $data['amount']);
  265. Db::commit();
  266. echo "success";
  267. exit;
  268. }
  269. } catch (ValidateException $e) {
  270. Db::rollback();
  271. $this->error($e->getMessage());
  272. } catch (PDOException $e) {
  273. Db::rollback();
  274. $this->error($e->getMessage());
  275. } catch (Exception $e) {
  276. Db::rollback();
  277. $this->error($e->getMessage());
  278. }
  279. //你可以在此编写订单逻辑
  280. } catch (Exception $e) {
  281. }
  282. }
  283. }
  284. /**
  285. * 银联提现回调
  286. */
  287. public function cashoutNotify()
  288. {
  289. }
  290. /**
  291. * 更新新人礼包
  292. */
  293. private function addBagGift($user_id, $amount)
  294. {
  295. if (!$user_id || !$amount) return false;
  296. // 先看该用户是否有新人礼包特权
  297. $have = \app\common\model\NewBagHave::where(["user_id" => $user_id])->find();
  298. // print_r($have);exit;
  299. if ($have && time() - $have->createtime <= 7 * 86400) {
  300. $where = [];
  301. $where["value"] = ["elt", $amount];
  302. $bagInfo = \app\common\model\NewBag::where($where)->order("value", "desc")->select();
  303. if (!$bagInfo) return false;
  304. $res1 = false;
  305. foreach ($bagInfo as $k => $v) {
  306. // 查询完成情况
  307. $bagfinish = \app\common\model\NewBagFinish::where(["user_id" => $user_id, "bag_id" => $v["id"]])->find();
  308. if (!$bagfinish || $bagfinish->status <= 0) {
  309. if ($bagfinish) {
  310. $bagfinish->status = 1;
  311. $bagfinish->updatetime = time();
  312. $res1 = $bagfinish->save();
  313. } else {
  314. $res1 = \app\common\model\NewBagFinish::insert(["user_id" => $user_id, "bag_id" => $v["id"], "status" => 1, "updatetime" => time()]);
  315. }
  316. break;
  317. }
  318. }
  319. return $res1;
  320. }
  321. }
  322. /**
  323. * 充值返利
  324. */
  325. private function rebate($user_id, $money)
  326. {
  327. // // 获取配置信息
  328. // $config = \app\common\model\RebateConfig::where(["recharge"=>$money])->find();
  329. // if(!$config) return true;
  330. // 找到当前用户的上级和上上级
  331. $userInfo = \app\common\model\User::get($user_id);
  332. if ($userInfo->pre_userid > 0) {
  333. $preUserInfo = \app\common\model\User::where(["id" => $userInfo->pre_userid])->find();// 上一级用户
  334. $this->addRebateMoney($preUserInfo->id, $user_id, $money, 1);
  335. if ($preUserInfo->pre_userid > 0) {
  336. $this->addRebateMoney($preUserInfo->pre_userid, $user_id, $money, 2);
  337. } else {
  338. return true;
  339. }
  340. } else {
  341. return true;
  342. }
  343. }
  344. /**
  345. * 添加返利金额
  346. */
  347. private function addRebateMoney($preUserId, $user_id, $money, $type)
  348. {
  349. Db::startTrans();
  350. try {
  351. // 添加返利记录表
  352. $data = [];
  353. $data["user_id"] = $preUserId;
  354. $data["by_user_id"] = $user_id;
  355. $data["money"] = $money;
  356. $data["rebate_money"] = 0.00;
  357. $data["rebate_type"] = $type;
  358. $data["createtime"] = time();
  359. $res1 = \app\common\model\RebateLog::insertGetId($data);
  360. // $res2 = (new \app\common\model\RebateLog)->execute("update hx_rebate_log set rebate_money = $rebatemoney where id = $res1");
  361. if ($res1) {
  362. Db::commit();
  363. }
  364. } catch (ValidateException $e) {
  365. Db::rollback();
  366. $this->error($e->getMessage());
  367. } catch (PDOException $e) {
  368. Db::rollback();
  369. $this->error($e->getMessage());
  370. } catch (Exception $e) {
  371. Db::rollback();
  372. $this->error($e->getMessage());
  373. }
  374. }
  375. //异步日志
  376. private function notify_log_start($paytype = 'wechat'){
  377. //记录支付回调数据
  378. ignore_user_abort(); // run script in background
  379. set_time_limit(30);
  380. // 日志文件 start
  381. $log_base_dir = '../paylog/'.$paytype.'/';
  382. if (!is_dir($log_base_dir))
  383. {
  384. mkdir($log_base_dir, 0770, true);
  385. @chmod($log_base_dir, 0770);
  386. }
  387. $notify_file = $log_base_dir.'notify.txt';
  388. if(!file_exists($notify_file)) {
  389. @touch($notify_file);
  390. @chmod($notify_file, 0770);
  391. }
  392. if(filesize($notify_file)>5242880)//大于5M自动切换
  393. {
  394. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  395. }
  396. if(!file_exists($notify_file)) {
  397. @touch($notify_file);
  398. @chmod($notify_file, 0770);
  399. }
  400. // 日志文件 end
  401. //开始写入
  402. $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
  403. if($_REQUEST && $paytype == 'alipay') {
  404. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
  405. } else {
  406. $xml = file_get_contents("php://input");
  407. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  408. $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  409. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);
  410. }
  411. ini_set('display_errors','On');
  412. return $notify_file;
  413. }
  414. }