Payment.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace app\common\model;
  3. use think\Log;
  4. use think\Model;
  5. /**
  6. * @property string order_no
  7. * @property MobileOrder order
  8. */
  9. class Payment extends Model
  10. {
  11. protected $autoWriteTimestamp=true;
  12. protected $type=[
  13. 'params'=>'json',
  14. 'settle_data'=>'json',
  15. 'settle_query_data'=>'json',
  16. 'refund_data'=>'json',
  17. 'refund_query_data'=>'json',
  18. ];
  19. public static function pay(User $user,$amount,$class,$func,$params,$body="订单付款"){
  20. $payment=self::create([
  21. 'class'=>$class,
  22. 'func'=>$func,
  23. 'params'=>$params,
  24. 'order_no'=>order_no(),
  25. 'amount'=>$amount,
  26. 'user_id'=>$user['id'],
  27. ]);
  28. try {
  29. $data=payment($user)->order->unify([
  30. 'body' => $body,
  31. 'out_trade_no' => $payment['order_no'],
  32. 'total_fee' => (int)($payment['amount']*100),
  33. 'notify_url' => request()->root(true)."/index/payment/index/order_no/".$payment['order_no'],
  34. 'trade_type' => 'JSAPI',
  35. 'openid' => $user['openid'],
  36. ]);
  37. if(empty($data['return_code']) || $data['return_code']!='SUCCESS' || $data['result_code']!='SUCCESS'){
  38. Log::error("支付错误:".json_encode($data));
  39. throw_user("支付错误:".($data['err_code_des']??$data['return_msg']??''));
  40. }
  41. $p=payment($user)->jssdk->sdkConfig($data['prepay_id']);
  42. return $p;
  43. }catch (\Exception $e){
  44. throw_user($e->getMessage());
  45. }
  46. }
  47. public function user(){
  48. return $this->belongsTo(User::class);
  49. }
  50. public function payed(){
  51. $user=$this->user;
  52. return payment($user)->handlePaidNotify(function ($message, $fail){
  53. Log::info("支付通知:".json_encode($message));
  54. if($this['pay_time']){
  55. return true;
  56. }
  57. $this['pay_time']=date('Y-m-d H:i:s');
  58. $class=new $this['class'];
  59. $class->{$this['func']}($this['params'],$this);
  60. return true;
  61. });
  62. }
  63. protected static function init()
  64. {
  65. self::beforeInsert(function (self $payment){
  66. });
  67. }
  68. public function refundSuccess(){
  69. $this['refund_status']=2;
  70. $this['refund_at']=date('Y-m-d H:i:s');
  71. $this->save();
  72. }
  73. public function settleSuccess($success,$queryData=null){
  74. $this['refund_query_data']=$queryData;
  75. if($success) {
  76. $this['settle_status'] = 2;
  77. $this['settle_at'] = date('Y-m-d H:i:s');
  78. }else{
  79. $this['settle_status']=3;
  80. }
  81. $this->save();
  82. }
  83. }