JoinPayFastPay.php 18 KB

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