JoinPayFastPay.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. namespace common\components\payment;
  3. use addons\JoinPay\common\models\JoinpayFastpayOrder;
  4. use addons\JoinPay\common\models\JoinPayUserBankcard;
  5. use Yii;
  6. use Exception;
  7. use common\components\payment\joinpay\util\{RandomUtil,RequestUtil,AESUtil,ObjectUtil,SignUtil};
  8. use common\components\payment\joinpay\entity\{Request,SecretKey,Response};
  9. use common\components\payment\joinpay\exceptions\SDKException;
  10. use common\models\common\UserBankCard;
  11. use common\helpers\Url;
  12. use common\enums\PayTypeEnum;
  13. use common\enums\StatusEnum;
  14. use common\models\common\PaymentTrade;
  15. use common\models\common\PaymentTradeOrder;
  16. /**
  17. * 汇聚支付-快捷协议支付
  18. *
  19. * Class JoinPayFastPay
  20. * @package common\components\payment
  21. */
  22. class JoinPayFastPay
  23. {
  24. public $config = [];
  25. public $url = 'https://api.joinpay.com/fastpay';
  26. public $refund_url = 'https://api.joinpay.com/refund';
  27. public function __construct($config)
  28. {
  29. if(stripos($config['joinpay_fast_pay_public_key'],'BEGIN PUBLIC KEY') === false){
  30. $config['joinpay_fast_pay_public_key'] = "-----BEGIN PUBLIC KEY-----\n".
  31. wordwrap($config['joinpay_fast_pay_public_key'], 64, "\n", true).
  32. "\n-----END PUBLIC KEY-----";
  33. }
  34. $this->config = $config;
  35. }
  36. public function getError()
  37. {
  38. // 文件services/common/PayService.php $refund_class->getError() 无此方法飘红
  39. return '';
  40. }
  41. /**
  42. * 快捷支付-发送签约短信
  43. * @desc 签约第一步
  44. * @param int $card_id UserBankCard->id
  45. * @throws Exception
  46. * @return bool
  47. */
  48. public function sendSignSms($card_id)
  49. {
  50. $card = JoinPayUserBankcard::findOne(['card_id' => $card_id]);
  51. if(!$card){
  52. throw new Exception('银行卡信息不存在');
  53. }
  54. $order_id = JoinpayFastPayOrder::createOrder($card->mall_id,$card->user_id,$card_id,0.01);
  55. $orderInfo = JoinpayFastPayOrder::findOne(['id' => $order_id]);
  56. // $orderInfo = [];
  57. $secKey = RandomUtil::randomStr(16);
  58. $request_data = $this->getData($orderInfo,$card->toArray(),$secKey);
  59. $request = $this->getRequestObject('fastPay.agreement.signSms',$request_data,$secKey);
  60. $secretKey = $this->getSecretKeyObject();
  61. try {
  62. $response = RequestUtil::doRequest($this->url, $request, $secretKey);
  63. if ($response->isSuccess()) {
  64. //受理成功
  65. $dataArr = json_decode($response->getData(), true);
  66. if ($dataArr["order_status"] == 'P1000' || $dataArr['order_status'] == 'P3000') {
  67. //成功
  68. return true;
  69. } else {
  70. \Yii::error('FAIL OR PROCESSING OR UNKNOWN, Response =' . json_encode($dataArr, JSON_UNESCAPED_UNICODE));
  71. throw new Exception($dataArr['err_msg']);
  72. }
  73. } else {
  74. \Yii::error('受理失败, Response =' . json_encode($response, JSON_UNESCAPED_UNICODE));
  75. throw new Exception('受理失败');
  76. }
  77. }catch (SDKException $e){
  78. throw new Exception($e->getMsg());
  79. } catch (Exception $e) {
  80. throw new Exception($e->getMessage().'请稍后重新发起交易,或联系汇聚客服');
  81. }
  82. }
  83. /**
  84. * 快捷支付-签约
  85. * @desc 签约第二步 END
  86. * @param $card_info
  87. * @param $sms_code
  88. * @throws Exception
  89. * @return bool
  90. */
  91. public function sign($card_id,$sms_code)
  92. {
  93. $card_info = UserBankCard::findOne([
  94. 'id' => $card_id,
  95. 'status' => StatusEnum::ENABLED,
  96. ]);
  97. /** @var JoinPayUserBankcard $card_info */
  98. $joinpay_card_info = JoinPayUserBankcard::findOne([
  99. 'card_id' => $card_id,
  100. 'status' => StatusEnum::ENABLED,
  101. 'is_sign' => 0,
  102. ]);
  103. if (empty($card_info) || empty($joinpay_card_info)) throw new \Exception('银行卡不存在');
  104. /** @var JoinpayFastPayOrder $orderInfo */
  105. $orderInfo = JoinpayFastpayOrder::find()
  106. ->where(['bank_card_id' => $card_info->id,'user_id'=>$card_info->user_id])
  107. ->orderBy('id desc')
  108. ->one();
  109. if (empty($orderInfo)) throw new \Exception('签约订单未找到');
  110. $secKey = RandomUtil::randomStr(16);
  111. $request_data = [
  112. 'mch_no_trade' => '',
  113. 'mch_order_no' => $orderInfo->order_no,
  114. 'sms_code' => $sms_code
  115. ];
  116. $request = $this->getRequestObject("fastPay.agreement.smsSign",$request_data,$secKey);
  117. $secretKey = $this->getSecretKeyObject();
  118. try {
  119. $response = RequestUtil::doRequest($this->url, $request, $secretKey);
  120. if ($response->isSuccess()) {
  121. //受理成功
  122. $dataArr = json_decode($response->getData(), true);
  123. \Yii::error(' Response data => '.json_encode($dataArr, JSON_UNESCAPED_UNICODE));
  124. if($dataArr["order_status"] == "P1000" || $dataArr['order_status'] == 'P3000'){
  125. //成功
  126. //返回签约ID : sign_no , bank_code,jp_order_no
  127. $joinpay_card_info->sign_no = $dataArr['sign_no'] ?? '';
  128. $joinpay_card_info->is_sign = !empty($dataArr['sign_no']) ? 1 : 0;
  129. $joinpay_card_info->bank_code = $dataArr['bank_code'] ?? '';
  130. $joinpay_card_info->updated_at = time();
  131. if(!$joinpay_card_info->save()){
  132. throw new Exception($joinpay_card_info->getErrorMessage());
  133. }
  134. $orderInfo->jp_order_no = $dataArr['jp_order_no'] ?? '';
  135. $orderInfo->updated_at = time();
  136. if(!$orderInfo->save()){
  137. throw new Exception($orderInfo->getErrorMessage());
  138. }
  139. return true;
  140. }else{
  141. throw new Exception($dataArr['err_msg'] ?? '操作失败');
  142. }
  143. }else{
  144. throw new Exception($response->getBizMsg() ?? '受理失败');
  145. }
  146. } catch (Exception $e) {
  147. throw $e;
  148. }
  149. }
  150. /**
  151. * 解约
  152. * @param $card_info
  153. * @return bool
  154. * @throws Exception
  155. */
  156. public function unsign($card_info)
  157. {
  158. $order_id = JoinpayFastPayOrder::createOrder($card_info->mall_id,$card_info->user_id,$card_info->id,0.01,0);
  159. $orderInfo = JoinpayFastPayOrder::findOne(['id' => $order_id]);
  160. $secKey = RandomUtil::randomStr(16);
  161. $request_data = [
  162. 'mch_order_no' => $orderInfo->order_no,
  163. 'mch_req_time' => date('Y-m-d H:i:s', $orderInfo->created_at),
  164. 'sign_no' => AESUtil::encryptECB($card_info->sign_no, $secKey)
  165. //'bank_card_no' => $card_info->bank_card_no,
  166. ];
  167. $request = $this->getRequestObject('fastPay.agreement.unSign',$request_data,$secKey);
  168. $secretKey = $this->getSecretKeyObject();
  169. try {
  170. $response = RequestUtil::doRequest($this->url, $request, $secretKey);
  171. if ($response->isSuccess()) {
  172. //受理成功
  173. $dataArr = json_decode($response->getData(), true);
  174. \Yii::error(' Response data='.json_encode($dataArr, JSON_UNESCAPED_UNICODE));
  175. if($dataArr["order_status"] == "P1000" || $dataArr['order_status'] == 'P3000'){
  176. //成功
  177. $card_info->sign_no = '';
  178. $card_info->is_sign = 0;
  179. $card_info->updated_at = time();
  180. if(!$card_info->save()){
  181. throw new Exception($card_info->getErrorMessage());
  182. }
  183. $orderInfo->jp_order_no = $dataArr['jp_order_no'] ?? '';
  184. $orderInfo->updated_at = time();
  185. if(!$orderInfo->save()){
  186. throw new Exception($orderInfo->getErrorMessage());
  187. }
  188. return true;
  189. }else{
  190. throw new Exception('FAIL OR PROCESSING OR UNKNOWN');
  191. }
  192. }else{
  193. throw new Exception($response->getBizMsg() ?? '受理失败');
  194. }
  195. } catch (Exception $e) {
  196. throw $e;
  197. }
  198. }
  199. /**
  200. * 支付短信接口
  201. * @param $trade_id 支付流水id
  202. * @param $card_id 银行卡记录id
  203. * @throws Exception
  204. * @return bool
  205. */
  206. public function sendPaySms(int $trade_id, $card_info,$mall_id)
  207. {
  208. // $card_info = JoinPayUserBankcard::find()->where(['id' => $card_id])->asArray()->one();
  209. $order_info = PaymentTrade::find()
  210. ->select('*,out_trade_no as order_no')
  211. ->where(['id' => $trade_id])
  212. ->asArray()
  213. ->one();
  214. $secKey = RandomUtil::randomStr(16);
  215. $request_data = $this->getData($order_info,$card_info,$secKey,true);
  216. $request = $this->getRequestObject("fastPay.agreement.paySms",$request_data,$secKey);
  217. $secretKey = $this->getSecretKeyObject();
  218. try {
  219. $response = RequestUtil::doRequest($this->url, $request, $secretKey);
  220. if ($response->isSuccess()) {//受理成功
  221. $dataArr = json_decode($response->getData(), true);
  222. if($dataArr["order_status"] == "P1000" || $dataArr['order_status'] == 'P3000'){//订单交易成功
  223. return true;
  224. }else{
  225. throw new Exception('FAIL OR PROCESSING OR UNKNOWN');
  226. }
  227. }else{
  228. throw new Exception($response->getBizMsg() ?? '受理失败');
  229. }
  230. } catch (Exception $e) {
  231. throw $e;
  232. }
  233. }
  234. /**
  235. * 订单支付
  236. * @param array $order
  237. * [
  238. * 'order_no' => '交易流水号'
  239. * 'sms_code' => '短信验证码'
  240. * 'created_at' => '交易创建时间戳'
  241. * ]
  242. *
  243. * @throws Exception
  244. * @return bool
  245. */
  246. public function pay($order)
  247. {
  248. $secKey = RandomUtil::randomStr(16);
  249. $request = new Request();
  250. $request_data = [
  251. 'mch_no_trade' => '',
  252. 'mch_order_no' => $order['order_no'],
  253. 'sms_code' => $order['sms_code'],
  254. 'mch_req_time' => date('Y-m-d H:i:s', $order['created_at'])
  255. ];
  256. $request->setMethod("fastPay.agreement.smsPay");
  257. $request->setVersion("1.0");
  258. $request->setMchNo($this->config['joinpay_merchant_no']);
  259. $request->setSignType("2");
  260. $request->setRandStr(RandomUtil::randomStr(32));
  261. $request->setData($request_data);
  262. $request->setSecKey($secKey);//rsa有效
  263. $secretKey = $this->getSecretKeyObject();
  264. try {
  265. $response = RequestUtil::doRequest($this->url, $request, $secretKey);
  266. \Yii::error(' fastpay response data => ' . $response->getData());\Yii::getLogger()->flush(true);
  267. if ($response->isSuccess()) {
  268. //受理成功
  269. $dataArr = json_decode($response->getData(), true);
  270. if($dataArr["order_status"] == "P1000"){
  271. //订单交易成功
  272. $trade = PaymentTrade::findOne(['out_trade_no' => $order['order_no']]);
  273. $trade_order = PaymentTradeOrder::findOne(['trade_id' => $trade->id]);
  274. // 返回这两个数据给前端展示支付成功页面使用
  275. return ['amount' => $trade_order->total_fee, 'order_no' => $trade_order->order_no];
  276. }else{
  277. throw new Exception('支付异常,请查询是否扣款');
  278. }
  279. }else{
  280. throw new Exception($response->getBizMsg() ?? '受理失败');
  281. }
  282. } catch (Exception $e) {
  283. throw $e;
  284. }
  285. }
  286. /**
  287. * 组装汇聚请求参数data
  288. * @param $orderInfo
  289. * @param $userBankInfo
  290. * @param $secKey
  291. * @param bool $is_pay
  292. * @return array
  293. */
  294. private function getData($orderInfo,$userBankInfo,$secKey,$is_pay = false)
  295. {
  296. $data = [];
  297. $data["mch_no_trade"] = "";
  298. $data["mch_order_no"] = $orderInfo['order_no'];
  299. $data["order_amount"] = sprintf("%.2f", $orderInfo['pay_fee']);
  300. //$data["mch_req_time"] = date('Y-m-d H:i:s', time());
  301. $data["mch_req_time"] = date('Y-m-d H:i:s', $orderInfo['created_at']);
  302. $data["order_desc"] = $orderInfo['title'];
  303. $data["id_type"] = "1";
  304. // $data["callback_url"] = Url::toFront( ['notify/' . PayTypeEnum::action(PayTypeEnum::JOINPAY_FAST_PAY)],TRUE);
  305. $data["callback_url"] = \Yii::$app->request->hostInfo . '/join-pay/notify/joinpay-fastpay';
  306. $data["callback_param"] = json_encode(['mall_id' => $userBankInfo['mall_id']]);// 公用回传参数;
  307. if(!$is_pay){
  308. $data["payer_name"] = AESUtil::encryptECB($userBankInfo['payer_name'], $secKey);//加密
  309. $data["id_no"] = AESUtil::encryptECB($userBankInfo['id_no'], $secKey);//加密
  310. $data["bank_card_no"] = AESUtil::encryptECB($userBankInfo['bank_card_no'], $secKey);//加密
  311. $data["mobile_no"] = AESUtil::encryptECB($userBankInfo['mobile_no'], $secKey);//加密
  312. }else{
  313. //支付
  314. $data['bank_card_no'] = AESUtil::encryptECB($userBankInfo['bank_card_no'], $secKey);//加密
  315. }
  316. //信用卡 需要加入:expire_date,cvv
  317. //https://www.joinpay.com/open-platform/pages/document.html?apiName=%E5%BF%AB%E6%8D%B7%E5%8D%8F%E8%AE%AE%E6%94%AF%E4%BB%98&id=9
  318. return $data;
  319. }
  320. /**
  321. * 获取Request 对象
  322. * @param $method
  323. * @param $request_data
  324. * @param $secKey
  325. * @return Request
  326. */
  327. private function getRequestObject($method,$request_data,$secKey)
  328. {
  329. $request = new Request();
  330. $request->setMethod($method);
  331. $request->setVersion('1.0');
  332. $request->setMchNo($this->config['joinpay_merchant_no']);
  333. $request->setSignType('2');
  334. $request->setRandStr(RandomUtil::randomStr(32));
  335. $request->setData($request_data);
  336. $request->setSecKey($secKey);//rsa有效
  337. return $request;
  338. }
  339. /**
  340. * 获取SecretKey Object
  341. * @return SecretKey
  342. */
  343. private function getSecretKeyObject()
  344. {
  345. $secretKey = new SecretKey();
  346. $secretKey->setReqSignKey($this->config['joinpay_fast_pay_private_key']);//签名:使用商户私钥
  347. $secretKey->setRespVerifyKey($this->config['joinpay_fast_pay_public_key']);//验签:使用平台公钥
  348. $secretKey->setSecKeyEncryptKey($this->config['joinpay_fast_pay_public_key']);//sec_key加密:使用平台公钥
  349. $secretKey->setSecKeyDecryptKey($this->config['joinpay_fast_pay_private_key']);//sec_key解密:使用商户私钥
  350. return $secretKey;
  351. }
  352. /**
  353. * 回调处理
  354. * @return bool
  355. */
  356. public function notify()
  357. {
  358. try{
  359. $post = Yii::$app->request->post();
  360. $data = $this->checkNotifyParams($post);
  361. return [
  362. 'out_trade_no' => $data['mch_order_no'], //商户订单号
  363. 'trade_no' => $post['jp_order_no'], //汇聚平台流水号
  364. 'pay_fee' => $data['order_amount']
  365. ];
  366. }catch(Exception $e){
  367. \Yii::error(__CLASS__ .' method:'.__METHOD__ .' error :'.$e->getMessage());
  368. return false;
  369. }
  370. }
  371. /**
  372. * 回调验签
  373. * @param $data
  374. * @return bool
  375. * @throws Exception
  376. */
  377. public function signature_verify($data)
  378. {
  379. $respJson = json_encode($data,JSON_UNESCAPED_UNICODE);
  380. $response = new Response();
  381. try{
  382. ObjectUtil::fillProperties($response, $respJson);
  383. }catch (Exception $e){
  384. throw new Exception(SDKException::BIZ_ERROR, "请求完成,但响应信息转换失败: " . $e->getMessage() . ",respJson = " . $respJson);
  385. }
  386. $isOk = false;
  387. $secretKey = $this->getSecretKeyObject();
  388. try{
  389. $signStr = SignUtil::getSortedString($response, false);
  390. $isOk = SignUtil::verify($signStr, $response->getSign(), $response->getSignType(), $secretKey->getRespVerifyKey());
  391. }catch (Exception $e){
  392. throw new Exception(SDKException::BIZ_ERROR, "请求完成,但响应信息验签异常: " . $e->getMessage() . ",respJson = " . $respJson);
  393. }
  394. if($isOk !== true){
  395. throw new Exception(SDKException::BIZ_ERROR, "响应信息验签不通过! respJson = " . $respJson);
  396. }
  397. if($data['biz_code'] !== 'JS000000'){
  398. throw new Exception('error');
  399. }
  400. if($data['mch_no'] != $this->config['joinpay_merchant_no']){
  401. throw new Exception('商户号有误');
  402. }
  403. return true;
  404. }
  405. /**
  406. * 校验回调参数
  407. * @param $res
  408. * @return bool
  409. * @throws Exception
  410. */
  411. public function checkNotifyParams($res)
  412. {
  413. $this->signature_verify($res);
  414. $data = json_decode($res['data'],true);
  415. if($data['order_status'] !== 'P1000'){
  416. //P100:支付成功
  417. throw new Exception($data['err_msg'] ?? '交易失败');
  418. }
  419. $order_no = $data['mch_order_no'];
  420. $total_fee = (doubleval($data['order_amount']) * 100) . '';
  421. //订单号查询
  422. $trade = PaymentTrade::findOne(['trade_no' => $order_no]);
  423. if (!$trade || $trade->is_pay == 1) {
  424. throw new Exception('订单不存在');
  425. }
  426. $order_amount = (doubleval($trade->pay_fee) * 100) . '';
  427. //金额是否一致
  428. if (intval($total_fee) !== intval($order_amount)) {
  429. throw new Exception('支付金额与订单金额不一致: ' . $order_no);
  430. }
  431. return $data;
  432. }
  433. /**
  434. * 退款
  435. * @param array $info
  436. * [
  437. * 'refund_order_no' => $refund_order_no,
  438. * 'out_trade_no' => $out_trade_no, //trade表交易流水号
  439. * 'refund_amount' => 1,
  440. * 'refund_reason' => 1
  441. * 'trade_created_at' => 1661400214
  442. * ]
  443. *
  444. * @return bool
  445. * @throws
  446. */
  447. public function refund($info)
  448. {
  449. $secKey = RandomUtil::randomStr(16);
  450. $request_data = [
  451. 'refund_order_no' => $info['refund_order_no'],
  452. 'refund_amount' => $info['refund_amount'],
  453. 'refund_reason' => mb_substr($info['refund_reason'],0,60),
  454. 'org_mch_order_no' => $info['out_trade_no'],
  455. 'org_mch_req_time' => date('Y-m-d H:i:s',$info['trade_created_at']),
  456. 'callback_url' => \Yii::getAlias('@apiUrl').'/notify/joinpay-fast-refund'
  457. ];
  458. $request = $this->getRequestObject('fastPay.refund',$request_data,$secKey);
  459. $secretKey = $this->getSecretKeyObject();
  460. try {
  461. $response = RequestUtil::doRequest($this->refund_url, $request, $secretKey);
  462. if ($response->isSuccess()) {
  463. \Yii::error('joinpay fast refund res:' . $response->getData());
  464. //受理成功
  465. $dataArr = json_decode($response->getData(), true);
  466. if($dataArr["refund_status"] == '101'){
  467. //退款失败
  468. throw new Exception('退款失败');
  469. }
  470. return true;
  471. } else {
  472. \Yii::error('受理失败, Response =' . json_encode($response, JSON_UNESCAPED_UNICODE));
  473. throw new Exception($response->getBizMsg());
  474. }
  475. }catch (SDKException $e){
  476. throw new Exception($e->getMsg());
  477. } catch (Exception $e) {
  478. throw new Exception($e->getMessage());
  479. }
  480. }
  481. }