VipRepository.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. /**
  3. * VIP套餐仓库.
  4. * @author jim <jim458734573@gmail.com>
  5. * @date 2020-01-29 10:10:06
  6. */
  7. declare(strict_types=1);
  8. namespace App\Repositories;
  9. use App\Constants\ChangeLogConstant;
  10. use App\Constants\CommonConstant;
  11. use App\Exception\ApiException;
  12. use App\Model\CoinsLogModel;
  13. use App\Model\CollectionsModel;
  14. use App\Model\UserModel;
  15. use App\Model\VipCardModel;
  16. use App\Model\VipOrderModel;
  17. use App\Repositories\Service\CommonService;
  18. use App\Repositories\Service\PaymentService;
  19. use App\Repositories\Service\QueueService;
  20. use App\Repositories\UserRepository;
  21. use Carbon\Carbon;
  22. use Hyperf\DbConnection\Db;
  23. use KZ2\Repositories\Model\Repository;
  24. use Psr\SimpleCache\CacheInterface;
  25. use App\Repositories\Utils\M3u8CacheRepository;
  26. class VipRepository extends Repository
  27. {
  28. public function model()
  29. {
  30. return VipCardModel::class;
  31. }
  32. /**
  33. * 获取vip套餐信息
  34. * @return array
  35. */
  36. public function getCanUseVipList($id = 0)
  37. {
  38. $list = make(CacheInterface::class)
  39. ->remember(
  40. 'vip_list',
  41. 60 * 60,
  42. function () {
  43. $arrItems = [];
  44. $items = VipCardModel::query()
  45. ->where('status', 1)
  46. ->orderByDesc('sort')
  47. ->get()->keyBy('id');
  48. if ($items->count()) {
  49. $arrItems = $items->toArray();
  50. foreach ($arrItems as $k => $v) {
  51. $arrJson = [];
  52. if (!empty($v['jdata'])) {
  53. $arrJson = json_decode($v['jdata'], true);
  54. }
  55. $arrItems[$k]['jdata'] = $arrJson;
  56. }
  57. }
  58. return $arrItems;
  59. }
  60. );
  61. if ($id) {
  62. return isset($list[$id]) ? $list[$id] : [];
  63. } else {
  64. return $list;
  65. }
  66. }
  67. /**
  68. * 删除vip套餐缓存 后台相关操作的时候调用此方法
  69. * @return bool
  70. */
  71. public function delUserVipCache()
  72. {
  73. return make(CacheInterface::class)->delete('vip_list');
  74. }
  75. /**
  76. * 获取vip套餐信息
  77. * @return array
  78. */
  79. public function getVipPackageData()
  80. {
  81. $result = array();
  82. $vipList = $this->getCanUseVipList();
  83. if ($vipList) {
  84. foreach ($vipList as $item) {
  85. $item['true_price'] = floatval($item['true_price']);
  86. $payment = make(PaymentService::class)
  87. ->getPayGatewayByAmount($item['true_price']);
  88. $tempItem = array(
  89. 'id' => $item['id'],
  90. 'title' => $item['title'],
  91. 'remark' => $item['remark'],
  92. 'day' => $item['day'] >= 9999 ? '永久无限' : $item['day'] . '天',
  93. 'price' => round($item['true_price']) . '',
  94. 'payment' => $payment,
  95. 'color' => $item['color'] ?? '',
  96. 'jdata' => $item['jdata'],
  97. 'intro' => $item['intro'] ?? '',
  98. 'mark' => $item['mark'] ?? '',
  99. 'is_super' => $item['is_super'] ?? 0,
  100. 'send_type' => $item['send_type'] ?? 0,
  101. 'send_num' => $item['send_num'] ?? 0,
  102. 'send_remark' => $item['send_remark'] ?? '',
  103. );
  104. $result [] = $tempItem;
  105. }
  106. }
  107. return $result;
  108. }
  109. /**
  110. * 获取vip套餐信息(大鲨鱼版)
  111. * @return array
  112. */
  113. public function getVipPackage($coins = 0, $deviceType = '')
  114. {
  115. $result = array();
  116. $vipList = $this->getCanUseVipList();
  117. $paymentList = make(PaymentService::class)->getAllPayments();
  118. if ($vipList) {
  119. $price_array = [];
  120. foreach ($vipList as $item) {
  121. $item['true_price'] = floatval($item['true_price']);
  122. $price_array[] = $item['true_price'];
  123. $truePrice = (float)$item['true_price'];
  124. $price = (float)$item['price'];
  125. $payment = make(PaymentService::class)
  126. ->getPayGatewayByAmount($item['true_price'], $deviceType, $paymentList);
  127. if ($coins >= $item['true_price']) {
  128. $cotnType = [
  129. 'id' => 1,
  130. 'name' => '金币',
  131. 'img' => M3u8CacheRepository::getImageUrl('f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/pay_type/4_144x144.ceb'),
  132. 'pay_type' => 4
  133. ];
  134. array_push($payment, $cotnType);
  135. }
  136. $tempItem = array(
  137. 'id' => $item['id'],
  138. 'title' => $item['title'],
  139. 'remark' => $item['remark'],
  140. 'day' => $item['day'] >= 9999 ? '永久无限' : $item['day'] . '天',
  141. 'price' => $price,
  142. 'true_price' => $truePrice,
  143. 'payment' => $payment,
  144. 'color' => $item['color'] ?? '',
  145. 'jdata' => $item['jdata'],
  146. 'intro' => $item['intro'] ?? '',
  147. 'mark' => $item['mark'] ?? '',
  148. 'is_super' => $item['is_super'] ?? 0,
  149. 'send_type' => $item['send_type'] ?? 0,
  150. 'send_num' => $item['send_num'] ?? 0,
  151. 'send_remark' => $item['send_remark'] ?? '',
  152. 'coins' => $item['coins'] ?? 0,
  153. 'coin_remark' => $item['coin_remark'] ?? '', // 花金币购买促销描述,例如文案:金币支付优惠20元
  154. );
  155. $result[] = $tempItem;
  156. }
  157. /*$payment = [
  158. [
  159. 'pay_type' => 'ali',
  160. 'gatway' => 'ali:ys',
  161. 'pay_name' => '支付宝',
  162. 'img' => 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/pay_type/ali_144x144.ceb',
  163. ],
  164. [
  165. 'pay_type' => 'wx',
  166. 'gatway' => 'wx:hf',
  167. 'pay_name' => '微信',
  168. 'img' => 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/pay_type/wx_144x144.ceb',
  169. ],
  170. [
  171. 'pay_type' => 'union',
  172. 'gatway' => 'union:ys',
  173. 'pay_name' => '银联',
  174. 'img' => 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/pay_type/union_144x144.ceb',
  175. ],
  176. [
  177. 'pay_type' => 'coin',
  178. 'gatway' => 'coin:coin',
  179. 'pay_name' => '金币',
  180. 'img' => 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/pay_type/coin_144x144.ceb',
  181. ],
  182. ];*/
  183. }
  184. return $result;
  185. }
  186. /**
  187. * 创建vip订单
  188. * @param array $requestData 请求参数
  189. * @return mixed
  190. */
  191. public function createVipOrder($requestData)
  192. {
  193. $userInfo = make(UserRepository::class)
  194. ->getUserInfoFromCache($requestData['user_id']);
  195. if (!$userInfo) {
  196. throw new ApiException('账号异常');
  197. }
  198. $vipItem = $this->getCanUseVipList($requestData['vip_id']);
  199. if (!$vipItem) {
  200. throw new ApiException('vip套餐不存在');
  201. }
  202. $vipItem['true_price'] = floatval($vipItem['true_price']);
  203. //次数控制 十秒钟内同支付方式只允许一单
  204. $queryTime = Carbon::now()->modify('-10 second')->toDateTimeString();
  205. $orderNum = VipOrderModel::query()
  206. ->where('user_id', '=', $userInfo['id'])
  207. ->where('created_at', '>', $queryTime)->count();
  208. if ($orderNum > 0) {
  209. throw new ApiException('亲,麻烦歇一会呢');
  210. }
  211. //生成订单
  212. $orderSn = make(CommonService::class)->createOrderSn(CommonConstant::APP_SHORT_NAME);
  213. $insertData = array(
  214. 'order_sn' => $orderSn,
  215. 'order_type' => $requestData['order_type'],
  216. 'user_id' => $userInfo['id'],
  217. 'user_code' => $userInfo['code'],
  218. 'user_parent_id' => $userInfo['parent_uid'] ?: 0,
  219. 'user_channel_id' => $userInfo['channel_id'],
  220. 'vip_title' => $vipItem['title'],
  221. 'vip_id' => $requestData['vip_id'],
  222. 'vip_days' => $vipItem['day'],
  223. 'pay_type' => $requestData['pay_type'],
  224. 'device_type' => $userInfo['device_type'],
  225. 'order_amount' => $vipItem['true_price'],
  226. 'real_amount' => $vipItem['true_price'],
  227. 'package_info' => json_encode($vipItem),
  228. 'trade_no' => $orderSn,
  229. 'status'=>3,
  230. );
  231. $result = VipOrderModel::query()->create($insertData);
  232. $jobData = clone $result;
  233. if (empty($result)) {
  234. return [];
  235. }
  236. $jobData = $jobData->toArray();
  237. $jobData['user_info'] = $userInfo;
  238. // 代理系统异步订单
  239. make(QueueService::class)->agentOrderIncJob($jobData);
  240. return $result;
  241. }
  242. /**
  243. * 金币购买vip
  244. *
  245. * @param $requestData
  246. * @return bool
  247. */
  248. public function createCoinVipOrder($requestData)
  249. {
  250. $userInfo = make(UserRepository::class)->findBy('code', $requestData['user_id']);
  251. if (!$userInfo) {
  252. throw new ApiException('账号异常');
  253. }
  254. $vipItem = $this->getCanUseVipList($requestData['vip_id']);
  255. if (!$vipItem) {
  256. throw new ApiException('vip套餐不存在');
  257. }
  258. if ($userInfo->coins < $vipItem['coins']) {
  259. throw new ApiException('金币不足,请充值金币后购买会员');
  260. }
  261. //次数控制 一分钟内同支付方式只允许一单
  262. $queryTime = Carbon::now()->modify('-1 minute')->toDateTimeString();
  263. $orderNum = VipOrderModel::query()
  264. ->where('user_id', '=', $userInfo['id'])
  265. ->where('created_at', '>', $queryTime)->count();
  266. if ($orderNum > 0) {
  267. throw new ApiException('亲,麻烦歇一会呢');
  268. }
  269. Db::beginTransaction();
  270. //订单号
  271. $orderSn = make(CommonService::class)->createOrderSn(CommonConstant::APP_SHORT_NAME);
  272. $orderData = [
  273. 'order_sn' => $orderSn,
  274. 'order_type' => $requestData['order_type'],
  275. 'user_id' => $userInfo['id'],
  276. 'user_code' => $userInfo['code'],
  277. 'user_parent_id' => $userInfo['parent_uid'] ?: 0,
  278. 'user_channel_id' => $userInfo['channel_id'],
  279. 'vip_title' => $vipItem['title'],
  280. 'vip_id' => $requestData['vip_id'],
  281. 'vip_days' => $vipItem['day'],
  282. 'pay_type' => $requestData['pay_type'], //4 金币类型
  283. 'device_type' => $userInfo['device_type'],
  284. 'order_amount' => $vipItem['true_price'],
  285. 'real_amount' => $vipItem['true_price'],
  286. 'status' => 1,
  287. 'pay_time' => Carbon::now()->toDateTimeString(),
  288. 'trade_no' => $orderSn,
  289. 'package_info' => json_encode($vipItem),
  290. ];
  291. $result = VipOrderModel::query()->create($orderData);
  292. if (!$result) {
  293. Db::rollBack();
  294. throw new ApiException('亲,麻烦歇一会呢');
  295. }
  296. //写收款单
  297. // $collectionsData = [
  298. // 'user_id' => $userInfo['id'],
  299. // 'user_code' => $userInfo['code'],
  300. // 'order_sn' => $orderSn,
  301. // 'type' => $requestData['order_type'],
  302. // 'pay_type' => $requestData['pay_type'],
  303. // 'device_type' => $userInfo['device_type'],
  304. // 'channel' => $userInfo['channel_id'],
  305. // 'trade_sn' => $orderSn,
  306. // 'order_amount' => $vipItem['true_price'],
  307. // 'real_amount' => $vipItem['true_price'],
  308. // ];
  309. // $result1 = CollectionsModel::query()->create($collectionsData);
  310. //加会员天数
  311. $userInfoCache = make(UserRepository::class)
  312. ->getUserInfoFromCache($userInfo['code']);
  313. if ($userInfoCache['is_vip'] == 'y') {
  314. $vipTime = Carbon::parse($userInfoCache['vip_expired'])
  315. ->addDays($vipItem['day'])
  316. ->toDateTimeString();
  317. } else {
  318. $vipTime = Carbon::now()
  319. ->addDays($vipItem['day'])
  320. ->toDateTimeString();
  321. }
  322. $houseCount = 0;
  323. $userCoins = 0;
  324. foreach ($vipItem['jdata']['feature'] as $packVal) {
  325. switch ($packVal['type']) {
  326. case 'house':
  327. $houseCount = $packVal['count'];
  328. break;
  329. }
  330. }
  331. if ($vipItem['send_type'] == 2) {
  332. $userCoins = $vipItem['send_num'];
  333. }
  334. //扣除金币 todo 这个地方不用考虑并发问题,加金币和买会员不会同时进行
  335. $coin = $userInfo->coins - $vipItem['coins'] + $userCoins;
  336. $houseCount = $userInfo['max_open_house'] + $houseCount;
  337. $result2 = UserModel::query()
  338. ->where('id', $userInfo['id'])
  339. ->update(['vip_expired' => $vipTime, 'vip_level' => $vipItem['id'], 'coins' => $coin, 'max_open_house' => $houseCount]);
  340. if ($result2) {
  341. Db::commit();
  342. // 送金币帐变记录
  343. if ($userCoins > 0) {
  344. $changeData = [
  345. 'user_uid' => $userInfo->code,
  346. 'currency_type' => ChangeLogConstant::CHANGE_COIN,
  347. 'amount' => $userCoins,
  348. 'way' => ChangeLogConstant::WAY_1,
  349. 'type' => ChangeLogConstant::TYPE_23,
  350. ];
  351. make(QueueService::class)->saveChangeLogJob($changeData);
  352. }
  353. // 帐变记录
  354. $changeData = [
  355. 'user_uid' => $userInfo->code,
  356. 'currency_type' => ChangeLogConstant::CHANGE_COIN,
  357. 'amount' => $vipItem['coins'],
  358. 'way' => ChangeLogConstant::WAY_2,
  359. 'type' => ChangeLogConstant::TYPE_2,
  360. ];
  361. make(QueueService::class)->saveChangeLogJob($changeData);
  362. make(UserRepository::class)->delUserCache($userInfo['code']);
  363. return true;
  364. }
  365. Db::rollBack();
  366. return false;
  367. }
  368. /**
  369. * 处理支付回调
  370. * @param int $orderId
  371. * @param string $tradeNo
  372. * @param float $payMoney
  373. * @param int $orderType
  374. * @return bool
  375. */
  376. public function doBuy($orderId, $tradeNo, $payMoney, $orderType)
  377. {
  378. if (!$orderId || !$tradeNo || !$payMoney || !$orderType) {
  379. return false;
  380. }
  381. Db::beginTransaction();
  382. try {
  383. $orderItem = VipOrderModel::query()->where('id', $orderId)
  384. ->first();
  385. if (!$orderItem || $orderItem['status'] == 1) {
  386. logger('订单状态异常:', [$orderItem['status']]);
  387. Db::rollBack();
  388. return false;
  389. }
  390. $orderItem = $orderItem->toArray();
  391. //金额校验
  392. $orderMoney = floatval($orderItem['order_amount']);
  393. $payMoney = floatval($payMoney);
  394. $minusMoney = $orderMoney - $payMoney;
  395. $minusMoney = abs(round($minusMoney, 2));
  396. if ($minusMoney > 2) {
  397. //只允许订单金额和付款金额相差2元内
  398. Db::rollBack();
  399. return false;
  400. }
  401. //修改订单状态
  402. $updateData = array(
  403. 'real_amount' => $payMoney,
  404. 'status' => 1,
  405. 'pay_time' => Carbon::now()->toDateTimeString(),
  406. 'trade_no' => $tradeNo,
  407. );
  408. $result1 = VipOrderModel::query()
  409. ->where('id', $orderId)
  410. ->update($updateData);
  411. //写收款单
  412. $collectionsData = array(
  413. 'user_id' => $orderItem['user_id'],
  414. 'user_code' => $orderItem['user_code'],
  415. 'order_sn' => $orderItem['order_sn'],
  416. 'type' => $orderType,
  417. 'pay_type' => $orderItem['pay_type'],
  418. 'device_type' => $orderItem['device_type'],
  419. 'channel' => $orderItem['user_channel_id'],
  420. 'trade_sn' => $tradeNo,
  421. 'order_amount' => $orderMoney,
  422. 'real_amount' => $payMoney,
  423. );
  424. $result2 = CollectionsModel::query()->create($collectionsData);
  425. //加会员天数
  426. $userInfo = make(UserRepository::class)
  427. ->getUserInfoFromCache($orderItem['user_code']);
  428. if ($userInfo['is_vip'] == 'y') {
  429. $vipTime = Carbon::parse($userInfo['vip_expired'])
  430. ->addDays($orderItem['vip_days'])
  431. ->toDateTimeString();
  432. } else {
  433. $vipTime = Carbon::now()
  434. ->addDays($orderItem['vip_days'])
  435. ->toDateTimeString();
  436. }
  437. $package = json_decode($orderItem['package_info'], true);
  438. $houseCount = 0;
  439. $userCoins = 0;
  440. foreach ($package['jdata']['feature'] as $packVal) {
  441. switch ($packVal['type']) {
  442. case 'house':
  443. $houseCount = $packVal['count'];
  444. break;
  445. }
  446. }
  447. if ($package['send_type'] == 2) {
  448. $userCoins = $package['send_num'];
  449. }
  450. $houseCount = $userInfo['max_open_house'] + $houseCount;
  451. $coins = $userInfo['coins'] + $userCoins;
  452. $result3 = UserModel::query()
  453. ->where('id', $orderItem['user_id'])
  454. ->update(['vip_expired' => $vipTime, 'vip_level' => $orderItem['vip_id'], 'max_open_house' => $houseCount, 'coins' => $coins]);
  455. if ($result1 && $result2 && $result3) {
  456. Db::commit();
  457. $queue = make(QueueService::class);
  458. //返佣计算 异步
  459. $queue->rebateTwoUserJob(['amount' => $orderMoney, 'user_id' =>$orderItem['user_code']]);
  460. // 帐变记录
  461. if ($userCoins > 0) {
  462. // 帐变记录
  463. $changeData = [
  464. 'user_uid' => $orderItem['user_code'],
  465. 'currency_type' => ChangeLogConstant::CHANGE_COIN,
  466. 'amount' => $userCoins,
  467. 'way' => ChangeLogConstant::WAY_1,
  468. 'type' => ChangeLogConstant::TYPE_23,
  469. ];
  470. $queue->saveChangeLogJob($changeData);
  471. }
  472. // 代理系统异步订单
  473. $jobData = VipOrderModel::query()->where('id', $orderId)->first()->toArray();
  474. $jobData['user_info'] = UserModel::query()->find($orderItem['user_id'])->toArray();
  475. $queue->agentOrderIncJob($jobData);
  476. make(UserRepository::class)->delUserCache($orderItem['user_code']);
  477. return true;
  478. }
  479. } catch (\Exception $e) {
  480. logger('支付回调失败:', [$e->getMessage()]);
  481. }
  482. Db::rollBack();
  483. return false;
  484. }
  485. }