PayForm.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace backend\models\forms;
  3. use backend\models\PayApi;
  4. use common\helpers\Utils;
  5. use Yii;
  6. use yii\base\Model;
  7. use yii\helpers\Url;
  8. class PayForm extends Model
  9. {
  10. public $login;
  11. public $amount;
  12. public $payType;
  13. public $bankCode;
  14. private $_outPayResult;
  15. public static $payNames = [
  16. 1 => '人人支付',
  17. 2 => '网通支付',
  18. 3 => '杉德支付',
  19. 4 => '顺通支付',
  20. 5 => '3xmta支付',
  21. 6 => '迅捷支付',
  22. 7 => 'Ctype支付',
  23. ];
  24. public static $payMethods = [
  25. 'renren' => 1,
  26. 'wangtong' => 2,
  27. 'sand' => 3,
  28. 'shangxinshuntong' => 4,
  29. 'threexmta' => 5,
  30. 'xunjie' => 6,
  31. 'ctype' => 7,
  32. ];
  33. /**
  34. * @inheritdoc
  35. */
  36. public function rules()
  37. {
  38. return [
  39. [['login', 'amount', 'payType'], 'required'],
  40. ['amount', 'match', 'pattern' => '/^([1-9]\d*|[0])(\.\d{1,2})?$/'],
  41. ['payType', 'integer'],
  42. ['payType', 'in', 'range' => array_keys(self::$payNames)],
  43. ['bankCode', 'required', 'when' => function ($model) {
  44. /** @var PayForm $model */
  45. return in_array($model->payType, [1,3]);
  46. }, 'message' => '请选择银行'],
  47. ];
  48. }
  49. /**
  50. * @return bool
  51. */
  52. public function outPay()
  53. {
  54. if (Yii::$app->getUser()->getIsGuest()) {
  55. $this->addError('login', '用户未登录');
  56. Yii::$app->getUser()->loginRequired();
  57. return false;
  58. }
  59. if ($this->validate()) {
  60. $data = [];
  61. $data['orderSn'] = date('YmdHis').rand(1000,9999);
  62. $data['amount'] = $this->amount;
  63. $data['login'] = $this->login;
  64. $data['payType'] = $this->payType;
  65. $data['bankCode'] = $this->bankCode;
  66. $data['memberId'] = Yii::$app->getUser()->getId();
  67. $data['notifyUrl'] = Url::to(["/pay/notify/{$this->payType}"], true);
  68. $data['returnUrl'] = Url::to(["/pay/return/{$this->payType}"], true);
  69. $data['ip'] = Utils::getClientIp();
  70. $api = new PayApi();
  71. $result = $api->outPay($data);
  72. if ($result['code'] == 1) {
  73. $this->_outPayResult = $result['data'];
  74. } else {
  75. if (is_array($result['message'])) {
  76. $this->addErrors($result['message']);
  77. } else {
  78. $this->addError('amount', $result['message']);
  79. }
  80. }
  81. }
  82. return !$this->hasErrors();
  83. }
  84. /**
  85. * @return string
  86. */
  87. public function getOutPayResult()
  88. {
  89. return $this->_outPayResult;
  90. }
  91. /**
  92. * @param string $payMethod
  93. * @return mixed|null
  94. */
  95. public function getPayTypeByMethod($payMethod)
  96. {
  97. return isset(self::$payMethods[$payMethod]) ? self::$payMethods[$payMethod] : null;
  98. }
  99. }