You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

332 lines
11 KiB

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: travis
  5. * Date: 2019/12/12
  6. * Time: 6:20
  7. */
  8. namespace api\logic;
  9. use backend\modules\shop\models\ars\Order;
  10. use backend\modules\shop\models\ars\PaymentLog;
  11. use backend\modules\shop\models\ars\RefundLog;
  12. use backend\modules\shop\models\ars\WxPayConfig;
  13. use Yii;
  14. use EasyWeChat\Factory;
  15. use yii\db\Exception;
  16. use yii\helpers\Json;
  17. use yii\httpclient\Client;
  18. use yii\web\BadRequestHttpException;
  19. use yii\base\BaseObject;
  20. use yii\web\NotFoundHttpException;
  21. use yii\web\ServerErrorHttpException;
  22. class WxPaymentLogic extends BaseObject
  23. {
  24. /*支付类型*/
  25. const PAY_TYPE_WEB = 1;
  26. const PAY_TYPE_MINI_PROGRAM = 2;
  27. /*支付状态*/
  28. const STATUS_PAYMENT_WAITING = 0;
  29. const STATUS_PAYMENT_SUCCESS = 1;
  30. /*退款状态*/
  31. const STATUS_REFUND_WAIT = 0; //退款待审核
  32. const STATUS_REFUND_CONFIRM = 1; //退款待确认
  33. const STATUS_REFUND_SUCCESS = 2; //退款成功
  34. const STATUS_REFUND_PORTION = 3; //部分退款
  35. /*发起支付方式*/
  36. const TRADE_TYPE_JS_API = 'JSAPI';
  37. public $appId;
  38. public $mchId;
  39. public $key;
  40. public $certPath;
  41. public $keyPath;
  42. public $notifyUrl;
  43. public $tradeType;
  44. public $payType;
  45. public $app;
  46. public $order;
  47. public $viewAction = 'view';
  48. /**
  49. * @param $payType
  50. * @return mixed
  51. * @throws BadRequestHttpException
  52. * @throws Exception
  53. * 微信统一下单
  54. */
  55. public function wxPayment($payType)
  56. {
  57. $this->payType = $payType;
  58. $unifyParams = $this->applyPaymentData();
  59. return $this->unify($unifyParams);
  60. }
  61. /**
  62. * @return array
  63. * @throws BadRequestHttpException
  64. * @throws Exception
  65. * 生成支付参数
  66. */
  67. private function applyPaymentData()
  68. {
  69. $orderId = Yii::$app->request->getBodyParam('order_id');/*int 商品id*/
  70. $paymentAmount = Yii::$app->request->getBodyParam('payment_amount');/*int 商品id*/
  71. $notifyUrl = Yii::$app->request->getBodyParam('notify_url');/*int 商品id*/
  72. if (empty($orderId) || empty($paymentAmount) || empty($notifyUrl)) {
  73. throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
  74. }
  75. $this->tradeType = self::TRADE_TYPE_JS_API;
  76. $this->savePaymentLog($orderId, $paymentAmount, $notifyUrl);
  77. $params = [
  78. 'body' => '订单支付',
  79. 'out_trade_no' => $orderId,
  80. 'total_fee' => round($paymentAmount * 100),
  81. 'openid' => Yii::$app->user->identity->wx_openid,
  82. ];
  83. return $params;
  84. }
  85. /**
  86. * @param string $orderId
  87. * @param float $paymentAmount
  88. * @param string $notifyUrl
  89. * @throws Exception
  90. * 保存支付信息
  91. */
  92. private function savePaymentLog($orderId, $paymentAmount, $notifyUrl)
  93. {
  94. $paymentLog = PaymentLog::findOne(['order_id' => $this->order->order_sn]);
  95. if (!$paymentLog) {
  96. $paymentLog = new PaymentLog();
  97. }
  98. $paymentLog->order_id = $orderId;
  99. $paymentLog->payment_amount = $paymentAmount;
  100. $paymentLog->notify_url = $notifyUrl;
  101. $paymentLog->type = $this->payType;
  102. $paymentLog->status = self::STATUS_PAYMENT_WAITING;
  103. if (!$paymentLog->save()) {
  104. throw new Exception(Helper::errorMessageStr($paymentLog->errors));
  105. }
  106. }
  107. protected function getApp()
  108. {
  109. $this->initObject();
  110. $config = [
  111. 'app_id' => $this->appId,
  112. 'mch_id' => $this->mchId,
  113. 'key' => $this->key,
  114. 'cert_path' => $this->certPath,
  115. 'key_path' => $this->keyPath,
  116. 'notify_url' => $this->notifyUrl,
  117. 'trade_type' => $this->tradeType,
  118. // 'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
  119. ];
  120. $this->app = Factory::payment($config);
  121. // 判断当前是否为沙箱模式:
  122. // $this->app->inSandbox();
  123. }
  124. /**
  125. * @var WxPayConfig $wxPayConfig
  126. */
  127. private function initObject()
  128. {
  129. $path = Yii::getAlias('@backend');
  130. $wxPayConfig = WxPayConfig::find()->one();
  131. switch ($this->payType) {
  132. case self::PAY_TYPE_WEB:
  133. // $wxConfig = WxConfig::find()->one();
  134. // $this->appId = trim($wxConfig->appid);
  135. break;
  136. case self::PAY_TYPE_MINI_PROGRAM:
  137. // $miniProgramConfig = MiniProgramConfig::find()->one();
  138. // $this->appId = trim($miniProgramConfig->appid);
  139. break;
  140. }
  141. $this->mchId = $wxPayConfig->mch_id;
  142. $this->certPath = trim($path . $wxPayConfig->cert_path);
  143. $this->keyPath = trim($path . $wxPayConfig->key_path);
  144. $this->notifyUrl = Yii::$app->request->hostInfo . '/wx-payment/notify';
  145. }
  146. /**
  147. * @param $unifyParams
  148. * @return mixed
  149. * 统一下单
  150. */
  151. private function unify($unifyParams)
  152. {
  153. $this->getApp();
  154. return $this->app->order->unify($unifyParams);
  155. }
  156. /**
  157. * @return array|bool
  158. * @throws BadRequestHttpException
  159. * @throws \yii\base\InvalidConfigException
  160. * @throws \yii\httpclient\Exception
  161. * 微信支付回调
  162. */
  163. public function notify()
  164. {
  165. $notifyData = Json::decode(Json::encode(simplexml_load_string(Yii::$app->request->getRawBody(), 'SimpleXMLElement', LIBXML_NOCDATA)));
  166. Yii::info($notifyData, "notify");
  167. if (!$this->checkSign($notifyData)) {
  168. throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
  169. }
  170. $tra = Yii::$app->db->beginTransaction('SERIALIZABLE');
  171. try {
  172. if ($notifyData->result_code != 'SUCCESS' || $notifyData->return_code != 'SUCCESS') {
  173. throw new BadRequestHttpException('result_code or return_code is false');
  174. }
  175. $paymentLog = PaymentLog::findOne(['order_id' => $notifyData->out_trade_no]);
  176. $this->notifyUrl = Yii::$app->request->hostInfo . $paymentLog->notify_url;
  177. $paymentLog->mch_id = $notifyData->mch_id;
  178. $paymentLog->wx_payment_id = $notifyData->transaction_id; //交易号
  179. $paymentLog->status = self::STATUS_PAYMENT_SUCCESS;
  180. $paymentLog->payment_at = time();
  181. if (!$paymentLog->save()) {
  182. throw new Exception(Helper::errorMessageStr($paymentLog->errors));
  183. }
  184. if (!$tra->commit()) {
  185. throw new Exception('保存数据失败');
  186. }
  187. /*转发回调信息*/
  188. $this->forwardNotify($notifyData, true);
  189. return ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];//回传成功信息到微信服务器
  190. } catch (Exception $e) {
  191. $tra->rollBack();
  192. $this->forwardNotify($notifyData, false);
  193. Yii::info($e->getMessage(), 'notify');
  194. return false;
  195. } catch (BadRequestHttpException $e) {
  196. $tra->rollBack();
  197. $this->forwardNotify($notifyData, false);
  198. Yii::info($e->getMessage(), 'notify');
  199. return false;
  200. }
  201. }
  202. /**
  203. * @param $notifyData $tra->rollBack();
  204. * @param $status
  205. * @return bool
  206. * @throws \yii\base\InvalidConfigException
  207. * @throws \yii\httpclient\Exception
  208. * 转发异步回调信息
  209. */
  210. private function forwardNotify($notifyData, $status)
  211. {
  212. $notify = [
  213. 'notify' => [
  214. 'status' => $status,
  215. 'notify' => $notifyData
  216. ]
  217. ];
  218. $client = new Client();
  219. $response = $client->createRequest()
  220. ->setMethod('POST')
  221. ->setUrl($this->notifyUrl)
  222. ->addHeaders(['content-type' => 'application/json'])
  223. ->setContent(Json::encode($notify))
  224. ->send();
  225. if ($response->isOk) {
  226. return true;
  227. } else {
  228. return false;
  229. }
  230. }
  231. /**
  232. * @return bool
  233. * @throws BadRequestHttpException
  234. * @throws Exception
  235. * @throws NotFoundHttpException
  236. * 申请退款
  237. */
  238. public function applyRefund()
  239. {
  240. $orderId = Yii::$app->request->getBodyParam('order_id');
  241. $refundId = Yii::$app->request->getBodyParam('wx_refund_id');
  242. $refundAmount = Yii::$app->request->getBodyParam('refund_amount');
  243. $refundAccount = Yii::$app->request->getBodyParam('refund_account');
  244. $reason = Yii::$app->request->getBodyParam('reason');
  245. if (empty($orderId) || empty($refundId) || empty($refundAmount) || empty($reason)) {
  246. throw new BadRequestHttpException(Helper::REQUEST_BAD_PARAMS);
  247. }
  248. $paymentLog = PaymentLog::findOne(['order_id' => $orderId]);
  249. if (empty($paymentLog)) {
  250. throw new NotFoundHttpException('订单支付信息未找到');
  251. }
  252. if (RefundLog::findOne(['order_id' => $orderId, 'status' => self::STATUS_REFUND_WAIT])) {
  253. throw new BadRequestHttpException('此订单存在等待审核的退款申请');
  254. }
  255. $refundedAmount = RefundLog::find()
  256. ->where(['order_id' => $orderId, 'status' => self::STATUS_PAYMENT_SUCCESS])
  257. ->sum('refund_amount') ?? 0;
  258. $refundLog = new RefundLog();
  259. $refundLog->order_id = $orderId;
  260. $refundLog->wx_refund_id = Helper::timeRandomNum(3, 'P');
  261. $refundLog->reason = $reason;
  262. $refundLog->order_amount = $paymentLog->payment_amount;
  263. $refundLog->refund_amount = $refundAmount;
  264. $refundLog->refunded_amount = $refundedAmount;
  265. $refundLog->type = $paymentLog->type;
  266. $refundLog->status = self::STATUS_REFUND_WAIT;
  267. $refundLog->refund_account = $refundAccount;
  268. $refundLog->applyed_at = time();
  269. if (!$refundLog->save()) {
  270. throw new Exception(Helper::errorMessageStr($refundLog->errors));
  271. }
  272. return true;
  273. }
  274. /**
  275. * @param $data
  276. * @return bool
  277. * 支付成功回调验证签名和支付金额
  278. */
  279. public function checkSign($data)
  280. {
  281. $this->initObject();
  282. $notifySign = $data['sign'];
  283. unset($data['sign']);
  284. $sign = $this->_sign($data);
  285. if ($notifySign == $sign) {
  286. return true;
  287. } else {
  288. return false;
  289. }
  290. }
  291. /**
  292. * @param $arr
  293. * @return string
  294. * 微信签名方法
  295. */
  296. private function _sign($arr)
  297. {
  298. $arr = array_filter($arr);
  299. ksort($arr);
  300. $arr['key'] = $this->key;
  301. $queryString = http_build_query($arr);
  302. $queryString = urldecode($queryString);
  303. return strtoupper(md5($queryString));
  304. }
  305. }