Yspay.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. <?php namespace Pay\Lib;
  2. use Dever;
  3. class Yspay extends Core
  4. {
  5. public function __construct($config)
  6. {
  7. $project = Dever::project('pay');
  8. # 通知接口
  9. $config['notify'] = $this->url($config['type'], $config['id']);
  10. $set = explode('|', $config['mchid']);
  11. $config['mid'] = $set[0];
  12. $config['tid'] = $set[1];
  13. if (isset($set[2])) {
  14. $config['prefix'] = $set[2];
  15. }
  16. $set = explode('|', $config['key']);
  17. $config['sub_appid'] = $set[0];
  18. $config['sub_appsecret'] = $set[1];
  19. if (isset($set[2])) {
  20. $config['key'] = $set[2];
  21. }
  22. $this->config = $config;
  23. }
  24. /**
  25. * 通知
  26. */
  27. public function notify()
  28. {
  29. $input = file_get_contents("php://input");
  30. if ($input) {
  31. parse_str($input, $input);
  32. } else {
  33. $input = Dever::input();
  34. }
  35. $test = Dever::input('test');
  36. if ($test == 1) {
  37. $input = json_decode('{"msgType":"wx.notify","payTime":"2021-12-29 18:24:42","buyerCashPayAmt":"1","connectSys":"UNIONPAY","sign":"E82978003E0121B320D3520B1930FB4C2072B639126F3427351631F1D0A998CF","merName":"中食民安(北京)科技有限公司","mid":"89810007372106N","invoiceAmount":"1","settleDate":"2021-12-29","billFunds":"现金:1","buyerId":"otdJ_uD-zTNmDn7-u13oActXu8lA","mchntUuid":"2d9081bd7db8ad75017dbbe68981314f","tid":"DM098308","instMid":"MINIDEFAULT","receiptAmount":"1","couponAmount":"0","targetOrderId":"4200001344202112290882463274","signType":"SHA256","billFundsDesc":"现金支付0.01元。","subBuyerId":"oGlMn5e_vdYK8uAaCgyexarFKBrY","orderDesc":"中食民安(北京)科技有限公司","seqId":"25267273719N","merOrderId":"138K_G202112297347788956443487","targetSys":"WXPay","bankInfo":"OTHERS","totalAmount":"1","createTime":"2021-12-29 18:24:38","buyerPayAmount":"1","iB":"KRHn","notifyId":"d4122965-b772-4f8f-b5c4-f3d483da0962","subInst":"100000","status":"TRADE_SUCCESS"}', true);
  38. $input = json_decode('{"bankInfo":"OTHERS","billDate":"2022-01-06","billDesc":"中食民安(北京)科技有限公司","billNo":"138KG202201064666839470673943","billPayment":"{\"payTime\":\"2022-01-06 13:24:56\",\"buyerCashPayAmt\":1,\"paySeqId\":\"25394941600N\",\"invoiceAmount\":1,\"settleDate\":\"2022-01-06\",\"buyerId\":\"otdJ_uHh75dIaI6EKu-6usw0hjD4\",\"receiptAmount\":1,\"totalAmount\":1,\"couponAmount\":0,\"billBizType\":\"bills\",\"buyerPayAmount\":1,\"targetOrderId\":\"4200001348202201065614123115\",\"payDetail\":\"现金支付0.01元。\",\"merOrderId\":\"138KG2022010646668394706739430\",\"status\":\"TRADE_SUCCESS\",\"targetSys\":\"WXPay\"}","billQRCode":"https:\/\/qr.95516.com\/48020000\/138K2201066502428138291294","billStatus":"PAID","createTime":"2022-01-06 13:24:28","instMid":"QRPAYDEFAULT","mchntUuid":"2d9081bd7db8ad75017dbbe68981314f","merName":"中食民安(北京)科技有限公司","mid":"89810007372106N","notifyId":"49a83755-b476-47c3-a0b6-629dc7a43742","qrCodeId":"138K2201066502428138291294","qrCodeType":"BILLPAY","receiptAmount":"1","seqId":"25394941600N","signType":"SHA256","subInst":"100000","tid":"DM098308","totalAmount":"1","vE":"Bclv","sign":"1D048E292E17225A4EEF4AB438630601A19E50CDA71DF9E7A4304AABBD134A38","e_sign":"1D048E292E17225A4EEF4AB438630601A19E50CDA71DF9E7A4304AABBD134A38"}', true);
  39. }
  40. $sign = $input['sign'];
  41. unset($input['sign']);
  42. if (isset($input['e_sign'])) {
  43. unset($input['e_sign']);
  44. }
  45. ksort($input);
  46. $string = array();
  47. foreach ($input as $k => $v) {
  48. if (strstr($v, '&') || strstr($v, '@')) {
  49. $v = urlencode($v);
  50. }
  51. $string[] = $k . '=' . $v;
  52. }
  53. $string = implode('&', $string);
  54. $string .= $this->config['key'];
  55. if ($input['signType'] == 'SHA256') {
  56. $string = hash("sha256", $string);
  57. } else {
  58. $string = md5($string);
  59. }
  60. $string = strtoupper($string);
  61. $input['sign'] = $sign;
  62. $input['e_sign'] = $string;
  63. $this->log('支付回调-初始化', $input);
  64. if ($sign == $string) {
  65. if (isset($input['billNo']) && $input['billNo']) {
  66. $key = 'billNo';
  67. } else {
  68. $key = 'merOrderId';
  69. }
  70. if (isset($this->config['prefix']) && $this->config['prefix']) {
  71. $input[$key] = str_replace($this->config['prefix'], '', $input[$key]);
  72. }
  73. if (isset($input['billPayment'])) {
  74. $input['billPayment'] = json_decode($input['billPayment'], true);
  75. if (isset($input['billPayment']['status'])) {
  76. $input['status'] = $input['billPayment']['status'];
  77. }
  78. }
  79. if (!isset($input['status'])) {
  80. echo 'FAILED';die;
  81. }
  82. $desc = '';
  83. if ($input['status'] == 'TRADE_SUCCESS') {
  84. # 成功
  85. } elseif ($input['status'] == 'TRADE_REFUND') {
  86. # 退款
  87. echo 'SUCCESS';die;
  88. } elseif ($input['status'] == 'TRADE_CLOSED') {
  89. $desc = '交易关闭';
  90. } elseif ($input['status'] == 'UNKNOWN') {
  91. $desc = '不明确的交易状态';
  92. } else {
  93. echo 'FAILED';die;
  94. }
  95. $this->updateOrder($input[$key], $input['totalAmount']);
  96. echo 'SUCCESS';die;
  97. } else {
  98. echo 'FAILED';die;
  99. }
  100. }
  101. /**
  102. * 获取统一下单的基本信息
  103. */
  104. public function order($account_id, $project_id, $uid, $username, $product_id, $name, $cash, $openid = false, $type = 1, $order_id = false, $other = false)
  105. {
  106. $order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $this->config['type'], $order_id);
  107. if (isset($this->config['prefix']) && $this->config['prefix']) {
  108. $request['merOrderId'] = $this->config['prefix'] . $order_id;
  109. } else {
  110. $request['merOrderId'] = $order_id;
  111. }
  112. $request['mid'] = $this->config['mid'];
  113. $request['tid'] = $this->config['tid'];
  114. $request['instMid'] = 'MINIDEFAULT';
  115. $request['totalAmount'] = round($cash * 100, 2);
  116. //$request['totalAmount'] = 100;
  117. $request['subAppId'] = $this->config['sub_appid'];
  118. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  119. $request['expireTime'] = date("Y-m-d H:i:s", time() + $this->config['timeout']);
  120. $request['notifyUrl'] = $this->config['notify'];
  121. $request['tradeType'] = 'MINI';
  122. if ($other) {
  123. $request['originalAmount'] = round($other['oprice'] * 100, 2);
  124. $request['divisionFlag'] = true;
  125. # 平台分账金额
  126. $other['per'] = $other['per'] && $other['per'] >= 0 ? $other['per'] : 0;
  127. $other['per'] = $other['per']/100;
  128. $request['platformAmount'] = round($request['totalAmount'] * $other['per'], 2);
  129. $request['subOrders'] = array();
  130. $request['subOrders']['mid'] = $other['mid'];
  131. if (isset($this->config['prefix']) && $this->config['prefix']) {
  132. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  133. } else {
  134. $request['subOrders']['merOrderId'] = $other['order_id'];
  135. }
  136. $request['subOrders']['totalAmount'] = round($request['totalAmount'] - $request['platformAmount'], 2);
  137. $request['subOrders'] = array($request['subOrders']);
  138. }
  139. if (!$openid) {
  140. # 测试的openid
  141. $request['subOpenId'] = 'ofBUV0RUoy_8C4VctZjrSDGzhUfY';
  142. } else {
  143. $request['subOpenId'] = $openid;
  144. }
  145. if ($type == 2) {
  146. # 二维码支付
  147. $request['instMid'] = 'QRPAYDEFAULT';
  148. $request['billNo'] = $request['merOrderId'];
  149. unset($request['merOrderId']);
  150. $result = Base::get_pay_code($request, $this->config);
  151. if (isset($result['billQRCode'])) {
  152. $result['request'] = $request;
  153. $result['payMsg'] = $result['billQRCode'];
  154. if ($other) {
  155. $result['other'] = $other;
  156. }
  157. $this->updateOrderParam($order_id, $result);
  158. return $result['payMsg'];
  159. }
  160. } else {
  161. # 小程序支付
  162. $result = Base::pay($request, $this->config);
  163. if (isset($result['miniPayRequest'])) {
  164. $result['request'] = $request;
  165. $result['payMsg'] = $result['miniPayRequest'];
  166. unset($result['miniPayRequest']);
  167. if ($other) {
  168. $result['other'] = $other;
  169. }
  170. $this->updateOrderParam($order_id, $result);
  171. return $result['payMsg'];
  172. }
  173. }
  174. return false;
  175. }
  176. # 退款
  177. public function refund($order_id, $cash, $order, $refund_order_id = false)
  178. {
  179. if ($refund_order_id) {
  180. $refund_order_id = $refund_order_id . '_' . Dever::order();
  181. }
  182. if (isset($this->config['prefix']) && $this->config['prefix']) {
  183. $request['merOrderId'] = $this->config['prefix'] . $order_id;
  184. if ($refund_order_id) {
  185. $request['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  186. }
  187. } else {
  188. $request['merOrderId'] = $order_id;
  189. if ($refund_order_id) {
  190. $request['refundOrderId'] = $refund_order_id;
  191. }
  192. }
  193. $request['mid'] = $this->config['mid'];
  194. $request['tid'] = $this->config['tid'];
  195. $request['instMid'] = 'MINIDEFAULT';
  196. if (isset($order['param']['targetOrderId'])) {
  197. $request['targetOrderId'] = $order['param']['targetOrderId'];
  198. }
  199. $request['subAppId'] = $this->config['appid'];
  200. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  201. $request['refundAmount'] = round($cash * 100, 2);
  202. if (isset($order['param']['other']) && $order['param']['other']) {
  203. $other = $order['param']['other'];
  204. $other['per'] = $other['per'] && $other['per'] >= 0 ? $other['per'] : 0;
  205. $other['per'] = $other['per']/100;
  206. $request['platformAmount'] = round($request['refundAmount'] * $other['per'], 2);
  207. $request['subOrders'] = array();
  208. $request['subOrders']['mid'] = $other['mid'];
  209. if (isset($this->config['prefix']) && $this->config['prefix']) {
  210. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  211. if ($refund_order_id) {
  212. $request['subOrders']['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  213. }
  214. } else {
  215. $request['subOrders']['merOrderId'] = $other['order_id'];
  216. if ($refund_order_id) {
  217. $request['subOrders']['refundOrderId'] = $refund_order_id;
  218. }
  219. }
  220. $request['subOrders']['totalAmount'] = round($request['refundAmount'] - $request['platformAmount'], 2);
  221. $request['subOrders'] = array($request['subOrders']);
  222. }
  223. $account = Dever::db('pay/account')->find($order['account_id']);
  224. $method = 'refund';
  225. if ($account && $account['system_source'] == 4) {
  226. $method = 'code_refund';
  227. $request['billNo'] = $request['merOrderId'];
  228. $request['instMid'] = 'QRPAYDEFAULT';
  229. $request['billDate'] = date('Y-m-d');
  230. }
  231. $result = Base::$method($request, $this->config);
  232. if (isset($result['refundStatus']) && $result['refundStatus'] == 'SUCCESS') {
  233. return true;
  234. }
  235. return false;
  236. }
  237. # 查询
  238. public function query($order_id)
  239. {
  240. $request['merOrderId'] = $order_id;
  241. $request['mid'] = $this->config['mchid'];
  242. $request['tid'] = $this->config['key'];
  243. $request['instMid'] = 'MINIDEFAULT';
  244. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  245. $result = Base::refund($request, $this->config);
  246. return $result;
  247. }
  248. # 关闭订单
  249. public function close($order_id)
  250. {
  251. $request['merOrderId'] = $order_id;
  252. $request['mid'] = $this->config['mchid'];
  253. $request['tid'] = $this->config['key'];
  254. $request['instMid'] = 'MINIDEFAULT';
  255. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  256. $result = Base::close($request, $this->config);
  257. return $result;
  258. }
  259. /**
  260. * 获取二维码支付
  261. */
  262. public function qrcode($order, $refer)
  263. {
  264. $result['type'] = 'qrcode';
  265. $result['url'] = $order;
  266. return $result;
  267. }
  268. /**
  269. * 获取小程序支付
  270. */
  271. public function applet($order)
  272. {
  273. $result = array();
  274. if (isset($order['package'])) {
  275. $prepay_id = str_replace('prepay_id=', '', $order['package']);
  276. $result['time'] = $order['timeStamp'];
  277. $result['nonce_str'] = $order['nonceStr'];
  278. $result['prepay_id'] = $prepay_id;
  279. $result['sign_type'] = $order['signType'];
  280. $result['sign'] = $order['paySign'];
  281. $result['type'] = 'applet';
  282. }
  283. return $result;
  284. }
  285. /**
  286. * 获取页面支付
  287. */
  288. public function page($order, $refer)
  289. {
  290. $refer = urldecode($refer);
  291. $tools = new \JsApiPay($this->config);
  292. $info = $tools->GetJsApiParameters($order);
  293. $html = '<script type="text/javascript">
  294. function jsApiCall()
  295. {
  296. WeixinJSBridge.invoke(
  297. "getBrandWCPayRequest",
  298. '.$info.',
  299. function(res){
  300. //WeixinJSBridge.log(res.err_msg);
  301. if(res.err_msg == "get_brand_wcpay_request:ok")
  302. {
  303. location.href = "'.$refer.'";
  304. } else {
  305. alert(res.err_code+res.err_desc+res.err_msg);
  306. }
  307. }
  308. );
  309. }
  310. function callpay()
  311. {
  312. if (typeof WeixinJSBridge == "undefined"){
  313. if( document.addEventListener ){
  314. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  315. }else if (document.attachEvent){
  316. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  317. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  318. }
  319. }else{
  320. jsApiCall();
  321. }
  322. }
  323. callpay();
  324. </script>';
  325. return $html;
  326. }
  327. }
  328. class Base
  329. {
  330. static $test_host = 'https://test-api-open.chinaums.com/';
  331. static $host = 'https://api-mop.chinaums.com/';
  332. static $signMethod = 'SHA256'; //签名方式
  333. # 获取token
  334. static $token_url = 'v1/token/access';
  335. # 微信下单支付
  336. static $pay_wechat_url = 'v1/netpay/wx/unified-order';
  337. # 支付宝下单支付
  338. static $pay_alipay_url = 'v1/netpay/trade/create';
  339. # 云闪付下单支付
  340. static $pay_uac_url = 'v1/netpay/uac/mini-order';
  341. # 交易查询
  342. static $query_url = 'v1/netpay/query';
  343. # 退款
  344. static $refund_url = 'v1/netpay/refund';
  345. # 退款查询
  346. static $refund_query_url = 'v1/netpay/refund-query';
  347. # 订单关闭
  348. static $close_url = 'v1/netpay/close';
  349. # 二维码支付
  350. static $qrcode_url = 'v1/netpay/bills/get-qrcode';
  351. # 二维码支付退款
  352. static $qrcode_refund_url = 'v1/netpay/bills/refund';
  353. //===================== 支付相关 ==============================
  354. /**
  355. * 支付交易
  356. */
  357. static public function pay($param, $config)
  358. {
  359. $url = self::$pay_wechat_url;
  360. $result = self::get($url, $param, $config);
  361. return $result;
  362. }
  363. /**
  364. * 获取支付二维码
  365. */
  366. static public function get_pay_code($param, $config)
  367. {
  368. $url = self::$qrcode_url;
  369. $result = self::get($url, $param, $config);
  370. return $result;
  371. }
  372. /**
  373. * 二维码交易退款
  374. */
  375. static public function code_refund($param, $config)
  376. {
  377. $url = self::$qrcode_refund_url;
  378. $result = self::get($url, $param, $config);
  379. return $result;
  380. }
  381. /**
  382. * 支付撤销
  383. */
  384. static public function close()
  385. {
  386. $url = self::$close_url;
  387. $result = self::get($url, $param, $config);
  388. return $result;
  389. }
  390. /**
  391. * 交易退款
  392. */
  393. static public function refund($param, $config)
  394. {
  395. $url = self::$refund_url;
  396. $result = self::get($url, $param, $config);
  397. return $result;
  398. }
  399. /**
  400. * 交易查询
  401. */
  402. static public function query()
  403. {
  404. $url = self::$query_url;
  405. $result = self::get($url, $param, $config);
  406. return $result;
  407. }
  408. /**
  409. * 交易退款查询
  410. */
  411. static public function refundQuery()
  412. {
  413. $url = self::$refund_query_url;
  414. $result = self::get($url, $param, $config);
  415. return $result;
  416. }
  417. //====================== 获取调用凭证===========================
  418. /**
  419. * 通用调用凭证获取
  420. * 默认使用token方式,使用签名方式需要传入参数
  421. */
  422. static public function getAuth($type = 'token', $param, $config)
  423. {
  424. if ($type === 'token') {
  425. return self::getAccessTokenByToken($config);
  426. }
  427. return self::getAccessTokenBySig($param, $config);
  428. }
  429. /**
  430. * 方式一,OPEN-ACCESS-TOKEN方式
  431. */
  432. static function getAccessTokenByToken($config)
  433. {
  434. $param = [
  435. 'appId' => $config['appid'],
  436. 'timestamp' => date('YmdHis'),
  437. 'nonce' => md5(uniqid(microtime(true),true)),
  438. 'signMethod' => self::$signMethod,
  439. ];
  440. $param['signature'] = self::signature($param, $config['appsecret']);
  441. $result = self::get(self::$token_url, $param, $config);
  442. if (isset($result['errCode']) && isset($result['accessToken'])) {
  443. return 'OPEN-ACCESS-TOKEN AccessToken='.$result['accessToken'];
  444. }
  445. return '';
  446. }
  447. /**
  448. * 方式二,OPEN-BODY-SIG方式
  449. */
  450. static function getAccessTokenBySig($data, $config)
  451. {
  452. $param = [
  453. 'AppId' => $config['appid'],
  454. 'Timestamp' => date('YmdHis'),
  455. 'Nonce' => md5(uniqid(microtime(true),true))
  456. ];
  457. return 'OPEN-BODY-SIG AppId="'.$param['AppId'].'", Timestamp="'.$param['Timestamp'].'", Nonce="'.$param['Nonce'].'", Signature="'.self::signature2($data, $param, $config['appsecret']).'"';
  458. }
  459. /**
  460. * 计算签名,方式一
  461. */
  462. static function signature($param, $appsecret)
  463. {
  464. return bin2hex(hash(self::$signMethod, $param['appId'].$param['timestamp'].$param['nonce'].$appsecret, true));
  465. }
  466. /**
  467. * 计算签名,方式二
  468. */
  469. static function signature2($data, $param, $appsecret)
  470. {
  471. $str = bin2hex(hash('sha256', Dever::json_encode($data), true));
  472. return base64_encode(hash_hmac('sha256', $param['AppId'].$param['Timestamp'].$param['Nonce'].$str, $appsecret, true));
  473. }
  474. /**
  475. * 获取信息
  476. */
  477. static function get($url, $param, $config)
  478. {
  479. $url = $config['box'] == 1 ? self::$host . $url : self::$test_host . $url;
  480. $header = array();
  481. $header['Authorization'] = self::getAuth('sig', $param, $config);
  482. $result = Dever::curl($url, $param, 'post', true, $header);
  483. if (strstr($result, '<html><head>')) {
  484. Dever::alert('系统错误');
  485. }
  486. $result = Dever::json_decode($result);
  487. if (isset($result['errCode'])) {
  488. if ($result['errCode'] == '0000' || $result['errCode'] == 'SUCCESS') {
  489. return $result;
  490. } elseif (isset($result['errInfo'])) {
  491. Dever::alert($result['errInfo']);
  492. } elseif (isset($result['errMsg'])) {
  493. Dever::alert($result['errMsg']);
  494. }
  495. } else {
  496. Dever::alert('系统错误');
  497. }
  498. return $result;
  499. }
  500. }