Order.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 (1 == 1) {
  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. $result = 1;
  43. }
  44. if ($result == 0) { // 锁生效
  45. throw new Exception('下单失败,请重试');
  46. }
  47. $key++;
  48. }
  49. }
  50. // More ...
  51. }
  52. /**
  53. * 检查是否符合创建订单的条件
  54. * 条件1:商品是否存在
  55. * 条件2:商品库存情况
  56. * 条件3:收货地址是否在范围内
  57. * 条件4:是否使用优惠券,优惠券能否可用
  58. * @param array $params
  59. * @param array $extra
  60. * @throws Exception
  61. * @throws \think\exception\DbException
  62. */
  63. public function createOrderBefore(&$params, $extra)
  64. {
  65. $specs = [''];
  66. $numbers = [$extra['number']];
  67. $productIds = [$extra['product_id']];
  68. if (count($specs) !== count($numbers) || count($specs) !== count($productIds)) {
  69. throw new Exception(__('Parameter error'));
  70. }
  71. // 订单价格
  72. $orderPrice = 0;
  73. // 条件一
  74. $products = [];
  75. foreach ($productIds as $key => &$productId) {
  76. $products[$key] = Db::name('unishop_product')
  77. ->where(['id' => $productId, 'switch' => Product::SWITCH_ON])
  78. ->lock(Config::isPessimism()) // Todo 是否使用悲观锁
  79. ->find();
  80. if (!$products[$key]) {
  81. throw new Exception(__('There are not exist or Offline'));
  82. }
  83. }
  84. if (count($products) == 0 || count($productIds) != count($products)) {
  85. throw new Exception(__('There are offline product'));
  86. }
  87. // 从购物车下单多个商品时,有同一个商品的不同规格导致减库存问题
  88. /*if (count($productIds) > 0) {
  89. $reduceStock = [];
  90. foreach ($products as $key => $value) {
  91. if (!isset($reduceStock[$value['id']])) {
  92. $reduceStock[$value['id']] = $numbers[$key];
  93. } else {
  94. $products[$key]['stock'] -= $reduceStock[$value['id']];
  95. $reduceStock[$value['id']] += $numbers[$key];
  96. }
  97. }
  98. }*/
  99. // 条件二
  100. foreach ($products as $key => $product) {
  101. $productInfo = (new \addons\unishop\extend\Product())->getBaseData($product, $specs[$key] ? $specs[$key] : '');
  102. if ($productInfo['stock'] < $numbers[$key]) {
  103. throw new Exception(__('Insufficient inventory,%s pieces left', $productInfo['stock']));
  104. }
  105. $orderPrice = bcadd($orderPrice, bcmul($productInfo['sales_price'], $numbers[$key], 2), 2);
  106. $baseProductInfo[] = $productInfo;
  107. }
  108. // 条件三
  109. /*$delivery = (new DeliveryRuleModel())->cityInScopeOfDelivery($extra['city_id'], $extra['delivery_id']);
  110. if (!$delivery) {
  111. throw new Exception(__('Your receiving address is not within the scope of delivery'));
  112. } else {
  113. if ($delivery['min'] > array_sum($numbers)) {
  114. throw new Exception(__('You must purchase at least %s item to use this shipping method', $delivery['min']));
  115. }
  116. }*/
  117. $delivery = [];
  118. /*$address = (new Address)->where(['id' => $extra['address_id'], 'user_id' => $extra['userId']])->find();
  119. if (!$address) {
  120. throw new Exception(__('Address not exist'));
  121. }*/
  122. $address = [];
  123. // 条件四
  124. /*if ($extra['coupon_id']) {
  125. // $coupon = Coupon::get($extra['coupon_id']);
  126. $coupon = Db::name('unishop_coupon_user')->alias('cu')
  127. ->field(['cu.id as cu_id','c.id','c.title','c.least','c.value','c.starttime','c.endtime'])
  128. ->join('unishop_coupon c','cu.coupon_id = c.id','LEFT')
  129. ->where('cu.user_id',$extra['userId'])
  130. ->where('cu.status',0)
  131. ->where('c.deletetime',NULL)
  132. ->where('c.switch',Coupon::SWITCH_ON)
  133. // ->where('c.starttime','<',time())
  134. // ->where('c.endtime','>',time())
  135. ->where('cu.id',$extra['coupon_id'])
  136. ->find();
  137. if(!empty($coupon)){
  138. if ($coupon['starttime'] > time() || $coupon['endtime'] < time()) {
  139. throw new Exception('此优惠券不可用');
  140. }
  141. // 至少消费多少钱
  142. if ($coupon['least'] > $orderPrice) {
  143. throw new Exception('选中的优惠券不满足使用条件');
  144. }
  145. }else{
  146. $coupon = [];
  147. }
  148. } else {
  149. $coupon = [];
  150. }*/
  151. $coupon = [];
  152. $params = [$products, $delivery, $coupon, $baseProductInfo, $address, $orderPrice, $specs, $numbers];
  153. }
  154. /**
  155. * 支付成功
  156. * 行为一:更改订单的支付状态,更新支付时间。
  157. * 行为二:减少商品的已下单但未支付的数量
  158. * @param $params
  159. * @param $extra
  160. * @throws \think\db\exception\DataNotFoundException
  161. * @throws \think\db\exception\ModelNotFoundException
  162. * @throws \think\exception\DbException
  163. */
  164. public function paidSuccess(&$params, $extra)
  165. {
  166. $order = &$params;
  167. $order->have_paid = time();// 更新支付时间为当前时间
  168. $order->pay_type = $extra['pay_type'];
  169. $order->save();
  170. $orderProductModel = new OrderProduct();
  171. $orderProducts = $orderProductModel
  172. ->with('product')
  173. ->where(['order_id' => $order->id])
  174. ->select();
  175. foreach ($orderProducts as $product) {
  176. if (isset($product->product)) {
  177. $product->product->no_buy_yet -= $product->number;
  178. $product->product->save();
  179. }
  180. }
  181. // More ...
  182. }
  183. /**
  184. * 支付失败
  185. * @param $params
  186. */
  187. public function paidFail(&$params)
  188. {
  189. $order = &$params;
  190. $order->have_paid = \addons\unishop\model\Order::PAID_NO;
  191. $order->save();
  192. // More ...
  193. }
  194. /**
  195. * 订单退款
  196. * 行为一:退款
  197. * @param array $params 订单数据
  198. */
  199. public function orderRefund(&$params)
  200. {
  201. $order = &$params;
  202. // 行为一
  203. switch ($order['pay_type']) {
  204. case \addons\unishop\model\Order::PAY_WXPAY:
  205. $app = Wechat::initEasyWechat('payment');
  206. $result = $app->refund->byOutTradeNumber($params['out_trade_no'], $params['out_trade_no'], bcmul($params['total_price'], 100), bcmul($params['refund']['amount'], 100), [
  207. // 可在此处传入其他参数,详细参数见微信支付文档
  208. 'refund_desc' => $params['refund']['reason_type'],
  209. ]);
  210. break;
  211. case \addons\unishop\model\Order::PAY_ALIPAY:
  212. $alipay = Ali::initAliPay();
  213. $order = [
  214. 'out_trade_no' => $params['out_trade_no'],
  215. 'refund_amount' => $params['total_price'],
  216. ];
  217. $result = $alipay->refund($order);
  218. break;
  219. }
  220. // More ...
  221. }
  222. }