CoinsRepository.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. /**
  3. * 金币仓库.
  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\OrderConstrant;
  11. use App\Model\CoinsLogModel;
  12. use App\Model\CoinsModel;
  13. use App\Model\CoinsOrderModel;
  14. use App\Model\CollectionsModel;
  15. use App\Model\UserModel;
  16. use App\Repositories\Service\CommonService;
  17. use App\Repositories\Service\PaymentService;
  18. use App\Repositories\Service\QueueService;
  19. use Carbon\Carbon;
  20. use Hyperf\Database\Model\Builder;
  21. use Hyperf\DbConnection\Db;
  22. use KZ2\Repositories\Model\Repository;
  23. use Psr\SimpleCache\CacheInterface;
  24. use App\Constants\CommonConstant;
  25. class CoinsRepository extends Repository
  26. {
  27. /**
  28. * @return Builder|mixed
  29. */
  30. public function model()
  31. {
  32. return CoinsModel::class;
  33. }
  34. /**
  35. * 定义金币记录类型
  36. * @return array
  37. */
  38. public function getCoinsTypeArr()
  39. {
  40. return array(
  41. 1 => '购买金币',
  42. 2 => '购买会员', //金币购买会员
  43. );
  44. }
  45. /**
  46. * 增加用户金币,在外层调用业务中使用事物、否则会存在事物套事物的情况
  47. * @param array|int $user 用户 数组 or 用户id
  48. * @param float $amount 金额 大于0
  49. * @param int $type 类型
  50. * @param string $orderSn 流水号 如果是因为订单之类的、可以传订单流水号进来、方便后期查询
  51. * @return bool
  52. */
  53. public function addCoins($userCode, $amount, $type, $collectionsData = [], $orderId = '')
  54. {
  55. if (!$userCode || !$amount || !$type || $amount <= 0) {
  56. return false;
  57. }
  58. $user = UserModel::where('code', $userCode)->first();
  59. if (!$user) {
  60. return false;
  61. }
  62. $user = $user->toArray();
  63. //增加用户金币
  64. $result1 = UserModel::where('id', $user['id'])->increment('coins', $amount);
  65. if ($result1) {
  66. // 帐变记录
  67. $changeData = [
  68. 'user_uid' => $userCode,
  69. 'currency_type' => ChangeLogConstant::CHANGE_COIN,
  70. 'amount' => $amount,
  71. 'way' => ChangeLogConstant::WAY_1,
  72. 'type' => ChangeLogConstant::TYPE_1,
  73. ];
  74. make(QueueService::class)->saveChangeLogJob($changeData);
  75. // 写收款单据
  76. $collectionsData['device_type'] = $user['device_type'];
  77. CollectionsModel::create($collectionsData);
  78. $jobData = CoinsOrderModel::query()->where('id', $orderId)->first()->toArray();
  79. $jobData['user_info'] = $user;
  80. make(QueueService::class)->agentOrderIncJob($jobData);
  81. return true;
  82. }
  83. return false;
  84. }
  85. /**
  86. * 减少用户金币,在外层调用业务中使用事物、否则会存在事物套事物的情况
  87. * @param array|int $user 用户 数组 or 用户id
  88. * @param float $amount 金额 小于0
  89. * @param int $type 类型
  90. * @param string $orderSn 流水号 如果是因为订单之类的、可以传订单流水号进来、方便后期查询
  91. * @return bool
  92. */
  93. public function reduceCoins($user, $amount, $type, $orderSn = '')
  94. {
  95. if (!$user || !$amount || !$type || $amount >= 0) {
  96. return false;
  97. }
  98. if (is_numeric($user)) {
  99. $user = UserModel::where('id', $user)->first()->toArray();
  100. }
  101. if (!$user) {
  102. return false;
  103. }
  104. if (empty($orderSn)) {
  105. $orderSn = make(CommonService::class)->createOrderSn('C');
  106. }
  107. //增加用户金币
  108. $result1 = UserModel::where('id', $user['id'])->increment('coins', $amount);
  109. //写金币日志
  110. $amountLog = $user['coins'] + $amount;
  111. $logData = array(
  112. 'user_id' => $user['id'],
  113. 'user_code' => $user['code'],
  114. 'amount' => $amount,
  115. 'amount_log' => $amountLog,
  116. 'coin_type' => $type,
  117. 'order_sn' => $orderSn,
  118. );
  119. $result2 = CoinsLogModel::create($logData);
  120. if ($result1 && $result2) {
  121. return true;
  122. }
  123. return false;
  124. }
  125. /**
  126. * 获取所有能使用的金币套餐
  127. * @return array
  128. */
  129. public function getCanUseCoinsList()
  130. {
  131. $result = make(CacheInterface::class)->remember(
  132. 'user_coins_list',
  133. 60 * 60,
  134. function () {
  135. $tempData = array();
  136. $tempResult = CoinsModel::query()
  137. ->where('status', 1)
  138. ->orderBy('sort', 'DESC')
  139. ->get()
  140. ->toArray();
  141. if ($tempResult) {
  142. foreach ($tempResult as $tempItem) {
  143. $tempData[$tempItem['id']] = $tempItem;
  144. }
  145. }
  146. return $tempData;
  147. }
  148. );
  149. return $result;
  150. }
  151. /**
  152. * 删除金币套餐缓存 后台相关操作的时候调用此方法
  153. * @return bool
  154. */
  155. public function delUserCoinsCache()
  156. {
  157. make(CacheInterface::class)
  158. ->deleteMultiple(array('user_coins_list'));
  159. return true;
  160. }
  161. /**
  162. * 获取用户金币套餐信息
  163. * @return array
  164. */
  165. public function getUserCoinsPackageData($deviceType = '')
  166. {
  167. $result = array();
  168. $vipList = $this->getCanUseCoinsList();
  169. $paymentList = make(PaymentService::class)->getAllPayments();
  170. if ($vipList) {
  171. $buyNotice = make(ConfigRepoistory::class)->get('coins_intro', 'rule', '');
  172. foreach ($vipList as $item) {
  173. $payment = make(PaymentService::class)->getPayGatewayByAmount($item['real_price'], $deviceType, $paymentList);
  174. $tempItem = array(
  175. 'id'=>$item['id'],
  176. 'coins'=>$item['coins'].'',
  177. 'price'=>round(floatval($item['price'])).'',
  178. 'real_price' => round(floatval($item['real_price'])).'',
  179. 'intro'=>$item['title_desc'],
  180. 'buy_notice'=>$buyNotice,
  181. 'payment'=>$payment,
  182. );
  183. $result []= $tempItem;
  184. }
  185. }
  186. return $result;
  187. }
  188. /**
  189. * 生成金币订单
  190. * @param array $requestData
  191. * @return int
  192. */
  193. public function createCoinsOrder($requestData)
  194. {
  195. if (empty($requestData['pay_id']) || empty($requestData['user_id']) || empty($requestData['coin_id'])) {
  196. throw new \App\Exception\ApiException('参数错误');
  197. }
  198. $userInfo = make(UserRepository::class)->getUserInfoFromCache($requestData['user_id']);
  199. if (!$userInfo) {
  200. throw new \App\Exception\ApiException('账号异常');
  201. }
  202. $coinList = $this->getCanUseCoinsList();
  203. if (!isset($coinList[$requestData['coin_id']])) {
  204. throw new \App\Exception\ApiException('套餐不存在');
  205. }
  206. $coinItem = $coinList[$requestData['coin_id']];
  207. //次数控制 一分钟内同支付方式只允许一单
  208. $queryTime = Carbon::now()->modify('-1 minute')->toDateTimeString();
  209. $orderNum = make(CoinsOrderModel::class)
  210. ->where('user_id', '=', $userInfo['id'])
  211. // ->where('payment_id', '=', $payment['id'])
  212. ->where('created_at', '>', $queryTime)
  213. ->count();
  214. if ($orderNum > 0) {
  215. throw new \App\Exception\ApiException('亲,麻烦歇一会呢');
  216. }
  217. //生成订单
  218. Db::beginTransaction();
  219. try {
  220. $orderSn = make(CommonService::class)->createOrderSn(CommonConstant::APP_SHORT_NAME);
  221. $insertData = array(
  222. 'order_sn' => $orderSn,
  223. 'user_id' => $userInfo['id'],
  224. 'user_code' => $userInfo['code'],
  225. 'user_parent_id' => $userInfo['parent_uid'] ?: 0,
  226. 'user_channel_id' => $userInfo['channel_id'],
  227. 'coins_id' => $requestData['coin_id'],
  228. 'coins' => $coinItem['coins'],
  229. 'order_amount' => $coinItem['price'],
  230. 'real_amount' => $coinItem['real_price'],
  231. 'payment_name' => OrderConstrant::$messages[$requestData['pay_type']] ?? '官方通道',
  232. 'status' => 3,
  233. 'trade_no' => $orderSn,
  234. 'package_info' => json_encode($coinItem),
  235. );
  236. $result = CoinsOrderModel::create($insertData);
  237. if ($result) {
  238. Db::commit();
  239. $jobData = clone $result;
  240. $jobData = $jobData->toArray();
  241. $jobData['user_info'] = $userInfo;
  242. // 代理系统异步订单
  243. make(QueueService::class)->agentOrderIncJob($jobData);
  244. return $result;
  245. }
  246. } catch (\Exception $e) {
  247. logger($e->getMessage());
  248. }
  249. Db::rollBack();
  250. return 0;
  251. }
  252. /**
  253. * 金额回调
  254. * @param int $orderId 订单id
  255. * @param string $tradeNo 交易单号
  256. * @param float $payMoney 支付金额
  257. * @return bool
  258. */
  259. public function doBuy($orderId, $tradeNo, $payMoney)
  260. {
  261. if (!$orderId || !$tradeNo || !$payMoney) {
  262. return false;
  263. }
  264. Db::beginTransaction();
  265. try {
  266. $orderItem = CoinsOrderModel::where('id', $orderId)->first()->toArray();
  267. if (!$orderItem || $orderItem['status'] == 1) {
  268. Db::rollBack();
  269. return false;
  270. }
  271. //金额校验
  272. $orderMoney = floatval($orderItem['real_amount']);
  273. $payMoney = floatval($payMoney);
  274. $minusMoney = floatval($orderMoney - $payMoney);
  275. $minusMoney = abs(round($minusMoney, 2));
  276. if ($minusMoney > 2) {
  277. //只允许订单金额和付款金额相差2元内
  278. Db::rollBack();
  279. return false;
  280. }
  281. //修改订单状态
  282. $updateData = array(
  283. 'real_amount' => $payMoney,
  284. 'status' => 1,
  285. 'pay_time' => Carbon::now()->toDateTimeString(),
  286. 'trade_no' => $tradeNo,
  287. );
  288. $result1 = CoinsOrderModel::where('id', $orderId)->update($updateData);
  289. //写收款单
  290. $collectionsData = array(
  291. 'user_id' => $orderItem['user_id'],
  292. 'user_code' => $orderItem['user_code'],
  293. 'order_sn' => $orderItem['order_sn'],
  294. 'trade_sn' => $tradeNo,
  295. 'order_amount' => $orderMoney,
  296. 'real_amount' => $payMoney,
  297. 'type' => 2,
  298. );
  299. //加金币
  300. $result3 = $this->addCoins($orderItem['user_code'], $orderItem['coins'], 2, $collectionsData, $orderId);
  301. if ($result1 && $result3) {
  302. Db::commit();
  303. make(UserRepository::class)->delUserCache($orderItem['user_code']);
  304. return true;
  305. }
  306. } catch (\Exception $e) {
  307. Db::rollBack();
  308. return false;
  309. }
  310. Db::rollBack();
  311. return false;
  312. }
  313. }