OrderPay.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: 芸众商城 www.yunzshop.com
  5. * Date: 2017/4/26
  6. * Time: 上午11:32
  7. */
  8. namespace app\common\models;
  9. use app\common\events\order\BeforeOrderMergePayEvent;
  10. use app\common\events\order\OrderPayValidateEvent;
  11. use app\common\exceptions\ShopException;
  12. use app\common\payment\PaymentConfig;
  13. use app\common\traits\HasProcessTrait;
  14. //use app\frontend\models\Member;
  15. use app\frontend\modules\order\models\PreOrder;
  16. use app\frontend\modules\order\OrderCollection;
  17. use Carbon\Carbon;
  18. use Illuminate\Database\Eloquent\Builder;
  19. use Illuminate\Database\Eloquent\Collection;
  20. use app\common\exceptions\AppException;
  21. use app\common\services\PayFactory;
  22. use app\frontend\modules\order\services\OrderService;
  23. use app\frontend\modules\payType\BasePayType;
  24. use app\frontend\modules\payType\CreditPay;
  25. use app\frontend\modules\payType\Remittance;
  26. use app\frontend\modules\payment\managers\OrderPaymentTypeManager;
  27. use Illuminate\Support\Facades\App;
  28. use app\common\services\SystemMsgService;
  29. /**
  30. * Class OrderPay
  31. * @package app\common\models
  32. * @property int id
  33. * @property int uid
  34. * @property int status
  35. * @property string pay_sn
  36. * @property int pay_type_id
  37. * @property Carbon pay_time
  38. * @property Carbon refund_time
  39. * @property float amount
  40. * @property array order_ids
  41. * @property Collection orders
  42. * @property Collection payOrder
  43. * @property Collection allStatus
  44. * @property PayType payType
  45. * @property Member member
  46. * @property string pay_type_name
  47. * @property string status_name
  48. */
  49. class OrderPay extends BaseModel
  50. {
  51. use HasProcessTrait;
  52. public $table = 'yz_order_pay';
  53. protected $guarded = ['id'];
  54. protected $search_fields = ['pay_sn'];
  55. protected $casts = ['order_ids' => 'json'];
  56. protected $dates = ['pay_time', 'refund_time'];
  57. protected $appends = ['status_name', 'pay_type_name'];
  58. protected $attributes = [
  59. 'status' => 0,
  60. 'pay_type_id' => 0,
  61. ];
  62. const STATUS_UNPAID = 0;
  63. const STATUS_PAID = 1;
  64. const STATUS_REFUNDED = 2;
  65. public static function newVirtual($amount = 0.01)
  66. {
  67. $orderPay = new static(['amount' => $amount]);
  68. $order = new PreOrder(['is_virtual' => 1]);
  69. $orderPay->setRelation('orders', new OrderCollection([$order]));
  70. return $orderPay;
  71. }
  72. /**
  73. * 根据paysn查询支付方式
  74. *
  75. * @param $pay_sn
  76. * @return mixed
  77. */
  78. public function get_paysn_by_pay_type_id($pay_sn)
  79. {
  80. return self::select('pay_type_id')
  81. ->where('pay_sn', $pay_sn)
  82. ->value('pay_type_id');
  83. }
  84. public function scopeOrderPay(Builder $query)
  85. {
  86. return $query->with('payType');
  87. }
  88. /**
  89. * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
  90. */
  91. public function member()
  92. {
  93. return $this->belongsTo(Member::class, 'uid');
  94. }
  95. /**
  96. * @return mixed
  97. */
  98. public function getStatusNameAttribute()
  99. {
  100. return $this->allStatus[$this->status];
  101. }
  102. /**
  103. * @return \Illuminate\Support\Collection
  104. */
  105. public function getAllStatusAttribute()
  106. {
  107. return collect([
  108. self::STATUS_UNPAID => '未支付',
  109. self::STATUS_PAID => '已支付',
  110. self::STATUS_REFUNDED => '已退款',
  111. ]);
  112. }
  113. /**
  114. * @return string
  115. */
  116. public function getPayTypeNameAttribute()
  117. {
  118. return $this->payType->name;
  119. }
  120. /**
  121. * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  122. */
  123. public function orders()
  124. {
  125. return $this->belongsToMany(Order::class, (new OrderPayOrder)->getTable(), 'order_pay_id', 'order_id');
  126. }
  127. /**
  128. * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
  129. */
  130. public function payType()
  131. {
  132. return $this->belongsTo(PayType::class);
  133. }
  134. /**
  135. * @return \Illuminate\Support\Collection|static
  136. */
  137. public function getPaymentTypes()
  138. {
  139. /**
  140. * @var OrderPaymentTypeManager $orderPaymentTypeManager
  141. */
  142. $orderPaymentTypeManager = app('PaymentManager')->make('OrderPaymentTypeManager');
  143. $paymentTypes = $orderPaymentTypeManager->getOrderPaymentTypes($this);
  144. return $paymentTypes;
  145. }
  146. /**
  147. * @return \Illuminate\Support\Collection|static
  148. */
  149. public function getAllPaymentTypes()
  150. {
  151. /**
  152. * @var OrderPaymentTypeManager $orderPaymentTypeManager
  153. */
  154. $orderPaymentTypeManager = app('PaymentManager')->make('OrderPaymentTypeManager');
  155. $paymentTypes = $orderPaymentTypeManager->getAllOrderPaymentTypes($this);
  156. return $paymentTypes;
  157. }
  158. /**
  159. * 支付
  160. * @param int $payTypeId
  161. * @throws AppException
  162. */
  163. public function pay($payTypeId = null)
  164. {
  165. if (!is_null($payTypeId)) {
  166. $this->pay_type_id = $payTypeId;
  167. }
  168. $this->payValidate();
  169. $this->status = self::STATUS_PAID;
  170. $this->pay_time = time();
  171. $this->save();
  172. $this->orders->each(function ($order) {
  173. OrderService::orderPay(['order_id' => $order->id, 'order_pay_id' => $this->id, 'pay_type_id' => $this->pay_type_id]);
  174. });
  175. }
  176. public function applyValidate()
  177. {
  178. // 校验库存
  179. }
  180. /**
  181. * 支付校验
  182. * @throws AppException
  183. */
  184. private function payValidate()
  185. {
  186. if (is_null($this->pay_type_id)) {
  187. throw new AppException('请选择支付方式');
  188. }
  189. // if ($this->status > self::STATUS_UNPAID) {
  190. // throw new AppException('(ID' . $this->id . '),此流水号已支付');
  191. // }
  192. if ($this->orders->isEmpty()) {
  193. throw new AppException('(ID:' . $this->id . ')未找到对应订单');
  194. }
  195. $this->orders->each(function (\app\common\models\Order $order) {
  196. if ($order->status > Order::WAIT_PAY) {
  197. throw new AppException('(ID:' . $order->id . ')订单已付款,请勿重复付款');
  198. }
  199. if ($order->status == Order::CLOSE) {
  200. throw new AppException('(ID:' . $order->id . ')订单已关闭,无法付款');
  201. }
  202. \Log::debug('支付前监听开始',$order->id);
  203. event($event = new BeforeOrderMergePayEvent($this, $order, $this->pay_type_id));
  204. if ($event->isBreak()) {
  205. throw new AppException('(ID:' . $order->id . ')订单无法支付,' . $event->plugin_msg . ':' . $event->error_msg);
  206. }
  207. \Log::debug('支付前监听结束',$order->id);
  208. });
  209. if (bccomp($this->orders->sum('price'), $this->amount) != 0) {
  210. throw new AppException('(ID' . $this->id . '),此流水号对应订单价格发生变化,请重新请求支付');
  211. };
  212. }
  213. /**
  214. * 支付事件校验,点击支付按钮时触发
  215. */
  216. private function OrderPayValidate()
  217. {
  218. // 支付类型
  219. $this->orders->each(function (\app\common\models\Order $order) {
  220. event(new OrderPayValidateEvent($order));
  221. });
  222. }
  223. /**
  224. * @throws AppException
  225. */
  226. public function applyPay()
  227. {
  228. return $this->getPayType()->applyPay();
  229. }
  230. /**
  231. * @return \Illuminate\Database\Eloquent\Relations\HasMany
  232. */
  233. public function payOrder()
  234. {
  235. return $this->hasMany(PayOrder::class, 'out_order_no', 'pay_sn');
  236. }
  237. /**
  238. * 代付记录
  239. * @return \Illuminate\Database\Eloquent\Relations\HasOne
  240. */
  241. public function behalfPay()
  242. {
  243. return $this->hasOne(OrderBehalfPayRecord::class, 'order_pay_id', 'id');
  244. }
  245. /**
  246. * 获取支付参数
  247. * @param int $payTypeId
  248. * @param array $payParams
  249. * @return array
  250. * @throws AppException
  251. */
  252. public function getPayResult($payTypeId = null, $payParams = [])
  253. {
  254. if ($this->created_at->timestamp + 60 < time()) {
  255. throw new AppException('支付请求记录已过期,请返回订单页面重新选择付款');
  256. }
  257. if (!is_null($payTypeId)) {
  258. $this->pay_type_id = $payTypeId;
  259. }
  260. $this->payValidate();
  261. // 支付前校验事件
  262. $this->OrderPayValidate();
  263. // 从丁哥的接口获取统一的支付参数
  264. $query_str = $this->getPayType()->getPayParams($payParams);
  265. $pay = PayFactory::create($this->pay_type_id);
  266. $result = $pay->doPay($query_str, $this->pay_type_id);
  267. if (!isset($result)) {
  268. throw new AppException('获取支付参数失败');
  269. }
  270. return $result;
  271. }
  272. /**
  273. * 获取支付类型对象
  274. * @return PayType|BasePayType
  275. * @throws AppException
  276. */
  277. private function getPayType()
  278. {
  279. if (!$this->payType instanceof BasePayType) {
  280. if ($this->pay_type_id == PayType::CREDIT) {
  281. $payType = CreditPay::find($this->pay_type_id);
  282. } elseif ($this->pay_type_id == PayType::REMITTANCE) {
  283. $payType = Remittance::find($this->pay_type_id);
  284. } else {
  285. $payType = BasePayType::find($this->pay_type_id);
  286. }
  287. if (!isset($payType)) {
  288. throw new AppException("未找到对应支付方式(id:{$this->pay_type_id})");
  289. }
  290. /**
  291. * @var BasePayType $payType
  292. */
  293. $payType->setOrderPay($this);
  294. $this->setRelation('payType', $payType);
  295. }
  296. return $this->payType;
  297. }
  298. /**
  299. * 快速退款
  300. * @throws AppException
  301. */
  302. public function fastRefund(Order $order = null)
  303. {
  304. //订单退款金额
  305. if (!isset($order)) {
  306. $amount = $this->amount;
  307. } else {
  308. event(new \app\common\events\order\BeforeOrderRefundedEvent($order));
  309. $refundedPrice = \app\common\models\refund\RefundApply::getAfterSales($order->id)->sum('price');
  310. //这里减去订单已部分退款金额
  311. $amount = max(bcsub($order->price, $refundedPrice,2),0);
  312. }
  313. //预约商品服务费不退
  314. if (!is_null(\app\common\modules\shop\ShopConfig::current()->get('store_reserve_refund_price')) && $order->status == Order::COMPLETE) {
  315. $class = array_get(\app\common\modules\shop\ShopConfig::current()->get('store_reserve_refund_price'), 'class');
  316. $function = array_get(\app\common\modules\shop\ShopConfig::current()->get('store_reserve_refund_price'), 'function');
  317. $plugin_res = $class::$function($order);
  318. if ($plugin_res['res']) {
  319. $amount = $plugin_res['price'];
  320. }
  321. }
  322. //$pay = PayFactory::create($this->pay_type_id);
  323. $payAdapter = new \app\common\modules\refund\RefundPayAdapter($this->pay_type_id);
  324. $totalmoney = $this->amount; //订单总金额
  325. try {
  326. //$result = $pay->doRefund($this->pay_sn, $totalmoney, $amount);
  327. $result = $payAdapter->pay($this->pay_sn, $totalmoney, $amount);
  328. if ($result['status']) {
  329. $this->updateRefund($this->id);
  330. }
  331. return $result;
  332. } catch (\Exception $e) {
  333. $systemMsg = new SystemMsgService;
  334. $msgContent = $order? "订单号{$order->order_sn}" : "支付号:{$this->pay_sn}";
  335. $errorData = [
  336. 'title' => '订单快速退款失败',
  337. 'content' => strval($e->getMessage()).",{$msgContent}",
  338. 'redirect_url' => '',
  339. 'redirect_param' => ''
  340. ];
  341. $systemMsg->sendSysMsg(7,$errorData);
  342. \Log::debug('错误支付回调参数', $e->getMessage());
  343. throw new AppException($e->getMessage());
  344. }
  345. }
  346. public function updateRefund($id)
  347. {
  348. if ($id) {
  349. OrderPay::where('id', $id)->where('status', '!=', OrderPay::STATUS_REFUNDED)->update([
  350. 'status' => OrderPay::STATUS_REFUNDED,
  351. 'refund_time' => time(),
  352. ]);
  353. }
  354. }
  355. public function updatePayStatus($pay_type_id)
  356. {
  357. OrderPay::where('id', $this->id)->update([
  358. 'pay_type_id' => $pay_type_id,
  359. 'status' => OrderPay::STATUS_PAID,
  360. 'pay_time' => time(),
  361. ]);
  362. //todo 这里不用save是防止模型有修改其他参数一起更新风险
  363. // $this->pay_type_id = $pay_type_id;
  364. // $this->status = self::STATUS_PAID;
  365. // $this->pay_time = time();
  366. // $this->save();
  367. }
  368. public function refund()
  369. {
  370. $this->status = OrderPay::STATUS_REFUNDED;
  371. $this->save();
  372. }
  373. /**
  374. * 快速退款(退回余额)
  375. * @throws AppException
  376. */
  377. public function fastRefund2(Order $order = null)
  378. {
  379. //订单退款金额
  380. if (!isset($order)) {
  381. $this->status = OrderPay::STATUS_REFUNDED;
  382. $amount = $this->amount;
  383. } else {
  384. $amount = $order->price;
  385. }
  386. $pay = PayFactory::create(3);
  387. $totalmoney = $this->amount; //订单总金额
  388. try {
  389. $result = $pay->doRefund($this->pay_sn, $totalmoney, $amount);
  390. if ($result) {
  391. $this->save();
  392. }
  393. return $result;
  394. } catch (\Exception $e) {
  395. throw new AppException($e->getMessage());
  396. }
  397. }
  398. public function save(array $options = [])
  399. {
  400. //如果修改之前不是退款状态,并且修改之后是退款状态,则更新退款时间
  401. if ($this->getOriginal('status') != self::STATUS_REFUNDED and $this->status == self::STATUS_REFUNDED) {
  402. $this->refund_time = time();
  403. }
  404. return parent::save($options); // TODO: Change the autogenerated stub
  405. }
  406. }