Payment.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace app\common\model;
  3. use think\Log;
  4. use think\Model;
  5. class Payment extends Model
  6. {
  7. protected $autoWriteTimestamp=true;
  8. protected $type=[
  9. 'params'=>'json',
  10. ];
  11. public static function pay(User $user,$amount,$class,$func,$params,$body="订单付款"){
  12. $payment=self::create([
  13. 'class'=>$class,
  14. 'func'=>$func,
  15. 'params'=>$params,
  16. 'order_no'=>order_no(),
  17. 'amount'=>$amount,
  18. 'user_id'=>$user['id'],
  19. ]);
  20. try {
  21. $data=payment($user)->order->unify([
  22. 'body' => $body,
  23. 'out_trade_no' => $payment['order_no'],
  24. 'total_fee' => (int)($payment['amount']*100),
  25. 'notify_url' => request()->root(true)."/index/payment/index/order_no/".$payment['order_no'],
  26. 'trade_type' => 'JSAPI',
  27. 'openid' => $user['openid'],
  28. ]);
  29. if(empty($data['return_code']) || $data['return_code']!='SUCCESS' || $data['result_code']!='SUCCESS'){
  30. Log::error("支付错误:".json_encode($data));
  31. throw_user("支付错误:".($data['err_code_des']??$data['return_msg']??''));
  32. }
  33. $p=payment($user)->jssdk->sdkConfig($data['prepay_id']);
  34. return $p;
  35. }catch (\Exception $e){
  36. throw_user($e->getMessage());
  37. }
  38. }
  39. public function user(){
  40. return $this->belongsTo(User::class);
  41. }
  42. public function payed(){
  43. $user=$this->user;
  44. return payment($user)->handlePaidNotify(function ($message, $fail){
  45. Log::info("支付通知:".json_encode($message));
  46. if($this['pay_time']){
  47. return true;
  48. }
  49. $this['pay_time']=date('Y-m-d H:i:s');
  50. $class=new $this['class'];
  51. $class->{$this['func']}($this['params'],$this);
  52. return true;
  53. });
  54. }
  55. }