Order.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. namespace app\common\model;
  3. use think\Db;
  4. use think\Exception;
  5. use think\Model;
  6. use Yansongda\Pay\Exceptions\GatewayException;
  7. use addons\epay\library\Service;
  8. use addons\shop\model\OrderAction;
  9. use addons\shop\model\TemplateMsg;
  10. use traits\model\SoftDelete;
  11. use app\common\Enum\OrderEnum;
  12. /**
  13. * 模型
  14. */
  15. class Order extends Model
  16. {
  17. use SoftDelete;
  18. // 表名
  19. protected $name = 'shop_order';
  20. // 开启自动写入时间戳字段
  21. protected $autoWriteTimestamp = 'int';
  22. // 定义时间戳字段名
  23. protected $createTime = 'createtime';
  24. protected $updateTime = 'updatetime';
  25. protected $deleteTime = 'deletetime';
  26. // 追加属性
  27. protected $append = [
  28. ];
  29. protected static $config = [];
  30. protected static $tagCount = 0;
  31. protected static function init()
  32. {
  33. $config = get_addon_config('shop');
  34. self::$config = $config;
  35. }
  36. public function getOrderStatusTextAttr($value, $data)
  37. {
  38. return OrderEnum::getOrderStatusText($data['order_status']);
  39. }
  40. public function getShippingstateList()
  41. {
  42. return ['0' => __('Shippingstate 0'), '1' => __('Shippingstate 1'), '2' => __('Shippingstate 2'), '3' => __('Shippingstate 3')];
  43. }
  44. public function getPaystateList()
  45. {
  46. return ['0' => __('Paystate 0'), '1' => __('Paystate 1')];
  47. }
  48. public function getShippingstateTextAttr($value, $data)
  49. {
  50. $value = $value ? $value : $data['shippingstate'];
  51. $list = $this->getShippingstateList();
  52. return $list[$value] ?? '';
  53. }
  54. public function getPaystateTextAttr($value, $data)
  55. {
  56. $value = $value ? $value : $data['paystate'];
  57. $list = $this->getPaystateList();
  58. return $list[$value] ?? '';
  59. }
  60. //获取订单剩余有效时长
  61. public function getRemainsecondsAttr($value, $data)
  62. {
  63. return max(0, $data['expiretime'] - time());
  64. }
  65. /**
  66. * @ DateTime 2021-05-31
  67. * @ 订单信息
  68. * @param $order_sn
  69. * @param $user_id
  70. * @return array|false|\PDOStatement|string|Model
  71. */
  72. public static function getDetail($order_sn, $user_id)
  73. {
  74. return self::with(['orderGoods'])->where('order_sn', $order_sn)->where('user_id', $user_id)->find();
  75. }
  76. /**
  77. * 判断订单是否失效
  78. * @param $order_sn
  79. * @return bool
  80. */
  81. public static function isExpired($order_sn)
  82. {
  83. $orderInfo = Order::getByOrderSn($order_sn);
  84. //订单过期
  85. if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
  86. // 启动事务
  87. Db::startTrans();
  88. try {
  89. $orderInfo->save(['orderstate' => 2]);
  90. //库存恢复
  91. OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
  92. //恢复优惠券
  93. UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
  94. // 提交事务
  95. Db::commit();
  96. } catch (\Exception $e) {
  97. // 回滚事务
  98. Db::rollback();
  99. }
  100. return true;
  101. }
  102. return false;
  103. }
  104. /**
  105. * @ 支付
  106. * @param string $orderid
  107. * @param int $user_id
  108. * @param string $paytype
  109. * @param string $method
  110. * @param string $openid
  111. * @param string $notifyurl
  112. * @param string $returnurl
  113. * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response|null
  114. * @throws \Exception
  115. */
  116. public static function pay($orderid, $user_id, $paytype, $method = 'web', $openid = '', $notifyurl = null, $returnurl = null)
  117. {
  118. $request = \think\Request::instance();
  119. $order = self::getDetail($orderid, $user_id);
  120. if (!$order) {
  121. throw new \Exception('订单不存在!');
  122. }
  123. if ($order->paystate) {
  124. throw new \Exception('订单已支付!');
  125. }
  126. if ($order->orderstate) {
  127. throw new \Exception('订单已失效!');
  128. }
  129. //支付金额为0,无需支付
  130. if ($order->saleamount == 0) {
  131. throw new \Exception('无需支付!');
  132. }
  133. $order_sn = $order->order_sn;
  134. // 启动事务
  135. Db::startTrans();
  136. try {
  137. //支付方式变更
  138. if (($order['paytype'] == $paytype && $order['method'] != $method)) {
  139. $order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
  140. //更新电子面单
  141. $electronics = $order->order_electronics;
  142. foreach ($electronics as $aftersales) {
  143. $aftersales->order_sn = $order_sn;
  144. $aftersales->save();
  145. }
  146. //更新操作日志
  147. $orderAction = $order->order_action;
  148. foreach ($orderAction as $action) {
  149. $action->order_sn = $order_sn;
  150. $action->save();
  151. }
  152. $order->save(['order_sn' => $order_sn]);
  153. //更新订单明细
  154. foreach ($order->order_goods as $item) {
  155. $item->order_sn = $order_sn;
  156. $item->save();
  157. }
  158. }
  159. //更新支付类型和方法
  160. $order->allowField(true)->save(['paytype' => $paytype, 'method' => $method, 'openid' => $openid]);
  161. //提交事务
  162. Db::commit();
  163. } catch (\Exception $e) {
  164. // 回滚事务
  165. Db::rollback();
  166. throw new \Exception($e->getMessage());
  167. }
  168. $response = null;
  169. $epay = get_addon_info('epay');
  170. if ($epay && $epay['state']) {
  171. $notifyurl = $notifyurl ? $notifyurl : $request->root(true) . '/addons/shop/order/epay/type/notify/paytype/' . $paytype;
  172. $returnurl = $returnurl ? $returnurl : $request->root(true) . '/addons/shop/order/epay/type/return/paytype/' . $paytype . '/order_sn/' . $order_sn;
  173. //保证取出的金额一致,不一致将导致订单重复错误
  174. $amount = sprintf("%.2f", $order->saleamount);
  175. $params = [
  176. 'amount' => $amount,
  177. 'orderid' => $order_sn,
  178. 'type' => $paytype,
  179. 'title' => "支付{$amount}元",
  180. 'notifyurl' => $notifyurl,
  181. 'returnurl' => $returnurl,
  182. 'method' => $method,
  183. 'openid' => $openid
  184. ];
  185. try {
  186. $response = Service::submitOrder($params);
  187. } catch (GatewayException $e) {
  188. throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败,请稍后重试");
  189. }
  190. } else {
  191. throw new \Exception("请在后台安装配置微信支付宝整合插件");
  192. }
  193. return $response;
  194. }
  195. /**
  196. * @ DateTime 2021-06-01
  197. * @ 订单结算
  198. * @param string $order_sn 订单号
  199. * @param float $payamount 支付金额
  200. * @param string $transactionid 流水号
  201. * @return bool
  202. */
  203. public static function settle($order_sn, $payamount, $transactionid = '')
  204. {
  205. $order = self::with(['orderGoods'])->where('order_sn', $order_sn)->find();
  206. if (!$order || $order->paystate == 1) {
  207. return false;
  208. }
  209. if ($payamount != $order->saleamount) {
  210. \think\Log::write("[shop][pay][{$order_sn}][订单支付金额不一致]");
  211. return false;
  212. }
  213. // 启动事务
  214. Db::startTrans();
  215. try {
  216. $order->paystate = 1;
  217. $order->transactionid = $transactionid;
  218. $order->payamount = $payamount;
  219. $order->paytime = time();
  220. $order->paytype = !$order->paytype ? 'system' : $order->paytype;
  221. $order->method = !$order->method ? 'system' : $order->method;
  222. $order->save();
  223. if ($order->payamount == $order->saleamount) {
  224. //支付完成后,商品销量+1
  225. foreach ($order->order_goods as $item) {
  226. $goods = $item->goods;
  227. $sku = $item->sku;
  228. if ($goods) {
  229. $goods->setInc('sales', $item->nums);
  230. }
  231. if ($sku) {
  232. $sku->setInc('sales', $item->nums);
  233. }
  234. }
  235. }
  236. // 提交事务
  237. Db::commit();
  238. } catch (\Exception $e) {
  239. // 回滚事务
  240. Db::rollback();
  241. return false;
  242. }
  243. //记录操作
  244. OrderAction::push($order_sn, '系统', '订单支付成功');
  245. //发送通知
  246. TemplateMsg::sendTempMsg(0, $order->order_sn);
  247. return true;
  248. }
  249. public function user()
  250. {
  251. return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
  252. }
  253. public function address()
  254. {
  255. return $this->belongsTo('Address', 'address_id', 'id', [], 'LEFT')->setEagerlyType(0);
  256. }
  257. public function orderGoods()
  258. {
  259. return $this->hasMany('OrderGoods', 'order_sn', 'order_sn');
  260. }
  261. public function orderElectronics()
  262. {
  263. return $this->hasMany('OrderElectronics', 'order_sn', 'order_sn');
  264. }
  265. public function orderAction()
  266. {
  267. return $this->hasMany('OrderAction', 'order_sn', 'order_sn');
  268. }
  269. }