Order.php 8.3 KB

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