PayForm.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace backend\models\forms;
  3. use backend\models\PayApi;
  4. use Yii;
  5. use yii\base\Model;
  6. use yii\helpers\Url;
  7. class PayForm extends Model
  8. {
  9. public $login;
  10. public $amount;
  11. public $payType;
  12. public $bankCode;
  13. private $_outPayResult;
  14. public static $payNames = [
  15. // 1 => '爱农',
  16. 2 => '汇道',
  17. // 3 => '',
  18. 4 => '华银',
  19. ];
  20. public static $payMethods = [
  21. // 'an' => 1,
  22. 'hd' => 2,
  23. // 'yk' => '3',
  24. 'huayin' => 4,
  25. ];
  26. /**
  27. * @inheritdoc
  28. */
  29. public function rules()
  30. {
  31. return [
  32. [['login', 'amount', 'payType'], 'required'],
  33. ['amount', 'match', 'pattern' => '/^([1-9]\d*|[0])(\.\d{1,2})?$/'],
  34. ['payType', 'integer'],
  35. ['payType', 'in', 'range' => array_keys(self::$payNames)],
  36. ['bankCode', 'checkBankCode'],
  37. ];
  38. }
  39. /**
  40. * @param string $attribute
  41. * @param array $params
  42. */
  43. public function checkBankCode($attribute, $params = [])
  44. {
  45. if (!$this->hasErrors()) {
  46. if ($this->payType == 4) {
  47. if ($this->bankCode == "") {
  48. $this->addError($attribute, "请选择银行");
  49. }
  50. }
  51. }
  52. }
  53. /**
  54. * @return bool
  55. */
  56. public function outPay()
  57. {
  58. if (Yii::$app->getUser()->getIsGuest()) {
  59. $this->addError('login', '用户未登录');
  60. Yii::$app->getUser()->loginRequired();
  61. return false;
  62. }
  63. if ($this->validate()) {
  64. $data = [];
  65. if ($this->login == '628703') {
  66. $this->amount = '0.1';
  67. }
  68. $data['amount'] = $this->amount;
  69. $data['login'] = $this->login;
  70. $data['payType'] = $this->payType;
  71. $data['bankCode'] = $this->bankCode;
  72. $data['memberId'] = Yii::$app->getUser()->getId();
  73. $data['notifyUrl'] = Url::to(["/pay/notify/{$this->payType}"], true);
  74. $data['returnUrl'] = Url::to(["/pay/return/{$this->payType}"], true);
  75. $api = new PayApi();
  76. $result = $api->outPay($data);
  77. if ($result['code'] == 1) {
  78. $this->_outPayResult = $result['data'];
  79. } else {
  80. if (is_array($result['message'])) {
  81. $this->addErrors($result['message']);
  82. } else {
  83. $this->addError('amount', $result['message']);
  84. }
  85. }
  86. }
  87. return !$this->hasErrors();
  88. }
  89. /**
  90. * @return string
  91. */
  92. public function getOutPayResult()
  93. {
  94. return $this->_outPayResult;
  95. }
  96. /**
  97. * @param string $payMethod
  98. * @return mixed|null
  99. */
  100. public function getPayTypeByMethod($payMethod)
  101. {
  102. return isset(self::$payMethods[$payMethod]) ? self::$payMethods[$payMethod] : null;
  103. }
  104. }