Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

285 righe
12 KiB

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