Order.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace addons\unishop\behavior;
  3. use addons\unishop\extend\Ali;
  4. use addons\unishop\extend\Hashids;
  5. use addons\unishop\extend\Wechat;
  6. use addons\unishop\model\Address;
  7. use addons\unishop\model\Config;
  8. use addons\unishop\model\DeliveryRule as DeliveryRuleModel;
  9. use addons\unishop\model\OrderProduct;
  10. use addons\unishop\model\Product;
  11. use app\admin\model\unishop\Coupon;
  12. use think\Db;
  13. use think\Exception;
  14. /**
  15. * 订单相关行为
  16. * Class Order
  17. * @package addons\unishop\behavior
  18. */
  19. class Order
  20. {
  21. /**
  22. * 创建订单之后
  23. * 行为一:根据订单减少商品库存 增加"已下单未支付数量"
  24. * 行为二:如果选了购物车的就删除购物车的信息
  25. * 行为三:如果选了优惠券的就修改掉购物券的状态
  26. * @param array $params 商品属性
  27. * @param array $extra [specNumber] => ['spec1' => 'number1','spec2' => 'number2']
  28. */
  29. public function createOrderAfter(&$params, $extra)
  30. {
  31. // 行为一
  32. $key = 0;
  33. $productExtend = new \addons\unishop\extend\Product;
  34. $prefix = \think\Config::get('database.prefix');
  35. if (Config::isPessimism()) {
  36. // 悲观锁
  37. foreach ($extra['specNumber'] as $spec => $number) {
  38. $result = 0;
  39. if (is_numeric($spec) && $params[$key]['use_spec'] == Product::SPEC_OFF) {
  40. $result = Db::execute('UPDATE ' . $prefix . "unishop_product SET no_buy_yet = no_buy_yet+{$number}, real_sales = real_sales+{$number}, stock = stock-{$number} WHERE id = {$params[$key]['id']}");
  41. } else if ($params[$key]['use_spec'] == Product::SPEC_ON) {
  42. $info = $productExtend->getBaseData($params[$key], $spec);
  43. // mysql<5.7.13时用
  44. //if (mysql < 5.7.13) {
  45. $spec = str_replace(',', '","', $spec);
  46. $search = '"stock":"' . $info['stock'] . '","value":["' . $spec . '"]';
  47. $stock = $info['stock'] - $number;
  48. $replace = '"stock":\"' . $stock . '\","value":["' . $spec . '"]';
  49. $sql = 'UPDATE ' . $prefix . "unishop_product SET no_buy_yet = no_buy_yet+{$number}, stock = stock-{$number}, real_sales = real_sales+{$number} ,`specTableList` = REPLACE(specTableList,'$search','$replace') WHERE id = {$params[$key]['id']}";
  50. $result = Db::execute($sql);
  51. //}
  52. //下面语句直接操作JSON
  53. //if (mysql >= 5.7.13) {
  54. //$info['stock'] -= $number;
  55. //$result = Db::execute("UPDATE fa_unishop_product SET no_buy_yet = no_buy_yet+{$number}, real_sales = real_sales+{$number}, stock = stock-{$number},specTableList = JSON_REPLACE(specTableList, '$[{$info['key']}].stock', {$info['stock']}) WHERE id = {$params[$key]['id']}");
  56. //}
  57. }
  58. if ($result == 0) { // 锁生效
  59. throw new Exception('下单失败,请重试');
  60. }
  61. $key++;
  62. }
  63. } else {
  64. // 乐观锁
  65. foreach ($extra['specNumber'] as $spec => $number) {
  66. $result = 0;
  67. if (is_numeric($spec) && $params[$key]['use_spec'] == Product::SPEC_OFF) {
  68. $result = Db::execute('UPDATE ' . $prefix . "unishop_product SET no_buy_yet = no_buy_yet+{$number}, real_sales = real_sales+{$number}, stock = stock-{$number} WHERE id = {$params[$key]['id']} AND stock = {$params[$key]['stock']}");
  69. } else if ($params[$key]['use_spec'] == Product::SPEC_ON) {
  70. $info = $productExtend->getBaseData($params[$key], $spec);
  71. // mysql<5.7.13时用
  72. //if (mysql < 5.7.13) {
  73. $spec = str_replace(',', '","', $spec);
  74. $search = '"stock":"' . $info['stock'] . '","value":["' . $spec . '"]';
  75. $stock = $info['stock'] - $number;
  76. $replace = '"stock":\"' . $stock . '\","value":["' . $spec . '"]';
  77. $sql = 'UPDATE ' . $prefix . "unishop_product SET no_buy_yet = no_buy_yet+{$number}, real_sales = real_sales+{$number}, stock = stock-{$number},`specTableList` = REPLACE(specTableList,'$search','$replace') WHERE id = {$params[$key]['id']} AND stock = {$params[$key]['stock']}";
  78. $result = Db::execute($sql);
  79. //}
  80. //下面语句直接操作JSON
  81. //if (mysql >= 5.7.13) {
  82. //$info['stock'] -= $number;
  83. //$result = Db::execute("UPDATE fa_unishop_product SET no_buy_yet = no_buy_yet+{$number}, real_sales = real_sales+{$number}, stock = stock-{$number},specTableList = JSON_REPLACE(specTableList, '$[{$info['key']}].stock', {$info['stock']}) WHERE id = {$params[$key]['id']} AND stock = {$params[$key]['stock']}");
  84. //}
  85. }
  86. if ($result == 0) { // 锁生效
  87. throw new Exception('下单失败,请重试');
  88. }
  89. $key++;
  90. }
  91. }
  92. // 行为二
  93. if (!empty($extra['cart'])) {
  94. $cart = $extra['cart'];
  95. Db::execute('DELETE FROM ' . $prefix . "unishop_cart WHERE id IN ($cart) AND user_id = $extra[userId]");
  96. }
  97. // 行为三
  98. $coupon = $extra['coupon'];
  99. if (!empty($coupon)) {
  100. Db::name('unishop_coupon_user')->where('id',$coupon['cu_id'])->update(['status'=>1]);
  101. }
  102. // More ...
  103. }
  104. /**
  105. * 检查是否符合创建订单的条件
  106. * 条件1:商品是否存在
  107. * 条件2:商品库存情况
  108. * 条件3:收货地址是否在范围内
  109. * 条件4:是否使用优惠券,优惠券能否可用
  110. * @param array $params
  111. * @param array $extra
  112. * @throws Exception
  113. * @throws \think\exception\DbException
  114. */
  115. public function createOrderBefore(&$params, $extra)
  116. {
  117. $specs = explode(',', $extra['spec']);
  118. foreach ($specs as &$spec) {
  119. $spec = str_replace('|', ',', $spec);
  120. }
  121. $numbers = explode(',', $extra['number']);
  122. $productIds = explode(',', $extra['product_id']);
  123. if (count($specs) !== count($numbers) || count($specs) !== count($productIds)) {
  124. throw new Exception(__('Parameter error'));
  125. }
  126. // 订单价格
  127. $orderPrice = 0;
  128. // 条件一
  129. $products = [];
  130. foreach ($productIds as $key => &$productId) {
  131. $productId = Hashids::decodeHex($productId);
  132. $products[$key] = Db::name('unishop_product')
  133. ->where(['id' => $productId, 'switch' => Product::SWITCH_ON])
  134. ->lock(Config::isPessimism()) // Todo 是否使用悲观锁
  135. ->find();
  136. if (!$products[$key]) {
  137. throw new Exception(__('There are not exist or Offline'));
  138. }
  139. }
  140. if (count($products) == 0 || count($productIds) != count($products)) {
  141. throw new Exception(__('There are offline product'));
  142. }
  143. // 从购物车下单多个商品时,有同一个商品的不同规格导致减库存问题
  144. if (count($productIds) > 0) {
  145. $reduceStock = [];
  146. foreach ($products as $key => $value) {
  147. if (!isset($reduceStock[$value['id']])) {
  148. $reduceStock[$value['id']] = $numbers[$key];
  149. } else {
  150. $products[$key]['stock'] -= $reduceStock[$value['id']];
  151. $reduceStock[$value['id']] += $numbers[$key];
  152. }
  153. }
  154. }
  155. // 条件二
  156. foreach ($products as $key => $product) {
  157. $productInfo = (new \addons\unishop\extend\Product())->getBaseData($product, $specs[$key] ? $specs[$key] : '');
  158. if ($productInfo['stock'] < $numbers[$key]) {
  159. throw new Exception(__('Insufficient inventory,%s pieces left', $productInfo['stock']));
  160. }
  161. $orderPrice = bcadd($orderPrice, bcmul($productInfo['sales_price'], $numbers[$key], 2), 2);
  162. $baseProductInfo[] = $productInfo;
  163. }
  164. // 条件三
  165. /*$delivery = (new DeliveryRuleModel())->cityInScopeOfDelivery($extra['city_id'], $extra['delivery_id']);
  166. if (!$delivery) {
  167. throw new Exception(__('Your receiving address is not within the scope of delivery'));
  168. } else {
  169. if ($delivery['min'] > array_sum($numbers)) {
  170. throw new Exception(__('You must purchase at least %s item to use this shipping method', $delivery['min']));
  171. }
  172. }*/
  173. $delivery = [];
  174. /*$address = (new Address)->where(['id' => $extra['address_id'], 'user_id' => $extra['userId']])->find();
  175. if (!$address) {
  176. throw new Exception(__('Address not exist'));
  177. }*/
  178. $address = [];
  179. // 条件四
  180. if ($extra['coupon_id']) {
  181. // $coupon = Coupon::get($extra['coupon_id']);
  182. $coupon = Db::name('unishop_coupon_user')->alias('cu')
  183. ->field(['cu.id as cu_id','c.id','c.title','c.least','c.value','c.starttime','c.endtime'])
  184. ->join('unishop_coupon c','cu.coupon_id = c.id','LEFT')
  185. ->where('cu.user_id',$extra['userId'])
  186. ->where('cu.status',0)
  187. ->where('c.deletetime',NULL)
  188. ->where('c.switch',Coupon::SWITCH_ON)
  189. // ->where('c.starttime','<',time())
  190. // ->where('c.endtime','>',time())
  191. ->where('cu.id',$extra['coupon_id'])
  192. ->find();
  193. if(!empty($coupon)){
  194. if ($coupon['starttime'] > time() || $coupon['endtime'] < time()) {
  195. throw new Exception('此优惠券不可用');
  196. }
  197. // 至少消费多少钱
  198. if ($coupon['least'] > $orderPrice) {
  199. throw new Exception('选中的优惠券不满足使用条件');
  200. }
  201. }else{
  202. $coupon = [];
  203. }
  204. } else {
  205. $coupon = [];
  206. }
  207. $params = [$products, $delivery, $coupon, $baseProductInfo, $address, $orderPrice, $specs, $numbers];
  208. }
  209. /**
  210. * 支付成功
  211. * 行为一:更改订单的支付状态,更新支付时间。
  212. * 行为二:减少商品的已下单但未支付的数量
  213. * @param $params
  214. * @param $extra
  215. * @throws \think\db\exception\DataNotFoundException
  216. * @throws \think\db\exception\ModelNotFoundException
  217. * @throws \think\exception\DbException
  218. */
  219. public function paidSuccess(&$params, $extra)
  220. {
  221. $order = &$params;
  222. $order->have_paid = time();// 更新支付时间为当前时间
  223. $order->pay_type = $extra['pay_type'];
  224. $order->save();
  225. $orderProductModel = new OrderProduct();
  226. $orderProducts = $orderProductModel
  227. ->with('product')
  228. ->where(['order_id' => $order->id])
  229. ->select();
  230. foreach ($orderProducts as $product) {
  231. if (isset($product->product)) {
  232. $product->product->no_buy_yet -= $product->number;
  233. $product->product->save();
  234. }
  235. }
  236. // More ...
  237. }
  238. /**
  239. * 支付失败
  240. * @param $params
  241. */
  242. public function paidFail(&$params)
  243. {
  244. $order = &$params;
  245. $order->have_paid = \addons\unishop\model\Order::PAID_NO;
  246. $order->save();
  247. // More ...
  248. }
  249. /**
  250. * 订单退款
  251. * 行为一:退款
  252. * @param array $params 订单数据
  253. */
  254. public function orderRefund(&$params)
  255. {
  256. $order = &$params;
  257. // 行为一
  258. switch ($order['pay_type']) {
  259. case \addons\unishop\model\Order::PAY_WXPAY:
  260. $app = Wechat::initEasyWechat('payment');
  261. $result = $app->refund->byOutTradeNumber($params['out_trade_no'], $params['out_trade_no'], bcmul($params['total_price'], 100), bcmul($params['refund']['amount'], 100), [
  262. // 可在此处传入其他参数,详细参数见微信支付文档
  263. 'refund_desc' => $params['refund']['reason_type'],
  264. ]);
  265. break;
  266. case \addons\unishop\model\Order::PAY_ALIPAY:
  267. $alipay = Ali::initAliPay();
  268. $order = [
  269. 'out_trade_no' => $params['out_trade_no'],
  270. 'refund_amount' => $params['total_price'],
  271. ];
  272. $result = $alipay->refund($order);
  273. break;
  274. }
  275. // More ...
  276. }
  277. }