Yspay.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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'] = $cash * 100;
  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'] = $other['oprice'] * 100;
  124. $request['divisionFlag'] = true;
  125. # 平台分账金额
  126. $other['per'] = $other['per']/100;
  127. $request['platformAmount'] = $request['totalAmount'] * $other['per'];
  128. $request['subOrders'] = array();
  129. $request['subOrders']['mid'] = $other['mid'];
  130. if (isset($this->config['prefix']) && $this->config['prefix']) {
  131. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  132. } else {
  133. $request['subOrders']['merOrderId'] = $other['order_id'];
  134. }
  135. $request['subOrders']['totalAmount'] = $request['totalAmount'] - $request['platformAmount'];
  136. $request['subOrders'] = array($request['subOrders']);
  137. }
  138. if (!$openid) {
  139. # 测试的openid
  140. $request['subOpenId'] = 'ofBUV0RUoy_8C4VctZjrSDGzhUfY';
  141. } else {
  142. $request['subOpenId'] = $openid;
  143. }
  144. if ($type == 2) {
  145. # 二维码支付
  146. $request['billNo'] = $request['merOrderId'];
  147. unset($request['merOrderId']);
  148. $result = Base::get_pay_code($request, $this->config);
  149. if (isset($result['billQRCode'])) {
  150. $result['request'] = $request;
  151. $result['payMsg'] = $result['billQRCode'];
  152. if ($other) {
  153. $result['other'] = $other;
  154. }
  155. $this->updateOrderParam($order_id, $result);
  156. return $result['payMsg'];
  157. }
  158. } else {
  159. # 小程序支付
  160. $result = Base::pay($request, $this->config);
  161. if (isset($result['miniPayRequest'])) {
  162. $result['request'] = $request;
  163. $result['payMsg'] = $result['miniPayRequest'];
  164. unset($result['miniPayRequest']);
  165. if ($other) {
  166. $result['other'] = $other;
  167. }
  168. $this->updateOrderParam($order_id, $result);
  169. return $result['payMsg'];
  170. }
  171. }
  172. return false;
  173. }
  174. # 退款
  175. public function refund($order_id, $cash, $order, $refund_order_id = false)
  176. {
  177. if (isset($this->config['prefix']) && $this->config['prefix']) {
  178. $request['merOrderId'] = $this->config['prefix'] . $order_id;
  179. if ($refund_order_id) {
  180. $request['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  181. }
  182. } else {
  183. $request['merOrderId'] = $order_id;
  184. if ($refund_order_id) {
  185. $request['refundOrderId'] = $refund_order_id;
  186. }
  187. }
  188. $request['mid'] = $this->config['mid'];
  189. $request['tid'] = $this->config['tid'];
  190. $request['instMid'] = 'MINIDEFAULT';
  191. if (isset($order['param']['targetOrderId'])) {
  192. $request['targetOrderId'] = $order['param']['targetOrderId'];
  193. }
  194. $request['subAppId'] = $this->config['appid'];
  195. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  196. $request['refundAmount'] = $cash * 100;
  197. if (isset($order['param']['other']) && $order['param']['other']) {
  198. $other = $order['param']['other'];
  199. $other['per'] = $other['per']/100;
  200. $request['platformAmount'] = $request['refundAmount'] * $other['per'];
  201. $request['subOrders'] = array();
  202. $request['subOrders']['mid'] = $other['mid'];
  203. if (isset($this->config['prefix']) && $this->config['prefix']) {
  204. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  205. if ($refund_order_id) {
  206. $request['subOrders']['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  207. }
  208. } else {
  209. $request['subOrders']['merOrderId'] = $other['order_id'];
  210. if ($refund_order_id) {
  211. $request['subOrders']['refundOrderId'] = $refund_order_id;
  212. }
  213. }
  214. $request['subOrders']['totalAmount'] = $request['refundAmount'] - $request['platformAmount'];
  215. $request['subOrders'] = array($request['subOrders']);
  216. }
  217. $account = Dever::db('pay/account')->find($order['account_id']);
  218. $method = 'refund';
  219. if ($account && $account['system_source'] == 4) {
  220. $method = 'code_refund';
  221. }
  222. $result = Base::$method($request, $this->config);
  223. if (isset($result['refundStatus']) && $result['refundStatus'] == 'SUCCESS') {
  224. return true;
  225. }
  226. return false;
  227. }
  228. # 查询
  229. public function query($order_id)
  230. {
  231. $request['merOrderId'] = $order_id;
  232. $request['mid'] = $this->config['mchid'];
  233. $request['tid'] = $this->config['key'];
  234. $request['instMid'] = 'MINIDEFAULT';
  235. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  236. $result = Base::refund($request, $this->config);
  237. return $result;
  238. }
  239. # 关闭订单
  240. public function close($order_id)
  241. {
  242. $request['merOrderId'] = $order_id;
  243. $request['mid'] = $this->config['mchid'];
  244. $request['tid'] = $this->config['key'];
  245. $request['instMid'] = 'MINIDEFAULT';
  246. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  247. $result = Base::close($request, $this->config);
  248. return $result;
  249. }
  250. /**
  251. * 获取二维码支付
  252. */
  253. public function qrcode($order, $refer)
  254. {
  255. $result['type'] = 'qrcode';
  256. $result['url'] = $order;
  257. return $result;
  258. }
  259. /**
  260. * 获取小程序支付
  261. */
  262. public function applet($order)
  263. {
  264. $result = array();
  265. if (isset($order['package'])) {
  266. $prepay_id = str_replace('prepay_id=', '', $order['package']);
  267. $result['time'] = $order['timeStamp'];
  268. $result['nonce_str'] = $order['nonceStr'];
  269. $result['prepay_id'] = $prepay_id;
  270. $result['sign_type'] = $order['signType'];
  271. $result['sign'] = $order['paySign'];
  272. $result['type'] = 'applet';
  273. }
  274. return $result;
  275. }
  276. /**
  277. * 获取页面支付
  278. */
  279. public function page($order, $refer)
  280. {
  281. $refer = urldecode($refer);
  282. $tools = new \JsApiPay($this->config);
  283. $info = $tools->GetJsApiParameters($order);
  284. $html = '<script type="text/javascript">
  285. function jsApiCall()
  286. {
  287. WeixinJSBridge.invoke(
  288. "getBrandWCPayRequest",
  289. '.$info.',
  290. function(res){
  291. //WeixinJSBridge.log(res.err_msg);
  292. if(res.err_msg == "get_brand_wcpay_request:ok")
  293. {
  294. location.href = "'.$refer.'";
  295. } else {
  296. alert(res.err_code+res.err_desc+res.err_msg);
  297. }
  298. }
  299. );
  300. }
  301. function callpay()
  302. {
  303. if (typeof WeixinJSBridge == "undefined"){
  304. if( document.addEventListener ){
  305. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  306. }else if (document.attachEvent){
  307. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  308. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  309. }
  310. }else{
  311. jsApiCall();
  312. }
  313. }
  314. callpay();
  315. </script>';
  316. return $html;
  317. }
  318. }
  319. class Base
  320. {
  321. static $test_host = 'https://test-api-open.chinaums.com/';
  322. static $host = 'https://api-mop.chinaums.com/';
  323. static $signMethod = 'SHA256'; //签名方式
  324. # 获取token
  325. static $token_url = 'v1/token/access';
  326. # 微信下单支付
  327. static $pay_wechat_url = 'v1/netpay/wx/unified-order';
  328. # 支付宝下单支付
  329. static $pay_alipay_url = 'v1/netpay/trade/create';
  330. # 云闪付下单支付
  331. static $pay_uac_url = 'v1/netpay/uac/mini-order';
  332. # 交易查询
  333. static $query_url = 'v1/netpay/query';
  334. # 退款
  335. static $refund_url = 'v1/netpay/refund';
  336. # 退款查询
  337. static $refund_query_url = 'v1/netpay/refund-query';
  338. # 订单关闭
  339. static $close_url = 'v1/netpay/close';
  340. # 二维码支付
  341. static $qrcode_url = 'v1/netpay/bills/get-qrcode';
  342. # 二维码支付退款
  343. static $qrcode_refund_url = 'v1/netpay/bills/refund';
  344. //===================== 支付相关 ==============================
  345. /**
  346. * 支付交易
  347. */
  348. static public function pay($param, $config)
  349. {
  350. $url = self::$pay_wechat_url;
  351. $result = self::get($url, $param, $config);
  352. return $result;
  353. }
  354. /**
  355. * 获取支付二维码
  356. */
  357. static public function get_pay_code($param, $config)
  358. {
  359. $url = self::$qrcode_url;
  360. $result = self::get($url, $param, $config);
  361. return $result;
  362. }
  363. /**
  364. * 二维码交易退款
  365. */
  366. static public function code_refund($param, $config)
  367. {
  368. $url = self::$qrcode_refund_url;
  369. $result = self::get($url, $param, $config);
  370. return $result;
  371. }
  372. /**
  373. * 支付撤销
  374. */
  375. static public function close()
  376. {
  377. $url = self::$close_url;
  378. $result = self::get($url, $param, $config);
  379. return $result;
  380. }
  381. /**
  382. * 交易退款
  383. */
  384. static public function refund($param, $config)
  385. {
  386. $url = self::$refund_url;
  387. $result = self::get($url, $param, $config);
  388. return $result;
  389. }
  390. /**
  391. * 交易查询
  392. */
  393. static public function query()
  394. {
  395. $url = self::$query_url;
  396. $result = self::get($url, $param, $config);
  397. return $result;
  398. }
  399. /**
  400. * 交易退款查询
  401. */
  402. static public function refundQuery()
  403. {
  404. $url = self::$refund_query_url;
  405. $result = self::get($url, $param, $config);
  406. return $result;
  407. }
  408. //====================== 获取调用凭证===========================
  409. /**
  410. * 通用调用凭证获取
  411. * 默认使用token方式,使用签名方式需要传入参数
  412. */
  413. static public function getAuth($type = 'token', $param, $config)
  414. {
  415. if ($type === 'token') {
  416. return self::getAccessTokenByToken($config);
  417. }
  418. return self::getAccessTokenBySig($param, $config);
  419. }
  420. /**
  421. * 方式一,OPEN-ACCESS-TOKEN方式
  422. */
  423. static function getAccessTokenByToken($config)
  424. {
  425. $param = [
  426. 'appId' => $config['appid'],
  427. 'timestamp' => date('YmdHis'),
  428. 'nonce' => md5(uniqid(microtime(true),true)),
  429. 'signMethod' => self::$signMethod,
  430. ];
  431. $param['signature'] = self::signature($param, $config['appsecret']);
  432. $result = self::get(self::$token_url, $param, $config);
  433. if (isset($result['errCode']) && isset($result['accessToken'])) {
  434. return 'OPEN-ACCESS-TOKEN AccessToken='.$result['accessToken'];
  435. }
  436. return '';
  437. }
  438. /**
  439. * 方式二,OPEN-BODY-SIG方式
  440. */
  441. static function getAccessTokenBySig($data, $config)
  442. {
  443. $param = [
  444. 'AppId' => $config['appid'],
  445. 'Timestamp' => date('YmdHis'),
  446. 'Nonce' => md5(uniqid(microtime(true),true))
  447. ];
  448. return 'OPEN-BODY-SIG AppId="'.$param['AppId'].'", Timestamp="'.$param['Timestamp'].'", Nonce="'.$param['Nonce'].'", Signature="'.self::signature2($data, $param, $config['appsecret']).'"';
  449. }
  450. /**
  451. * 计算签名,方式一
  452. */
  453. static function signature($param, $appsecret)
  454. {
  455. return bin2hex(hash(self::$signMethod, $param['appId'].$param['timestamp'].$param['nonce'].$appsecret, true));
  456. }
  457. /**
  458. * 计算签名,方式二
  459. */
  460. static function signature2($data, $param, $appsecret)
  461. {
  462. $str = bin2hex(hash('sha256', Dever::json_encode($data), true));
  463. return base64_encode(hash_hmac('sha256', $param['AppId'].$param['Timestamp'].$param['Nonce'].$str, $appsecret, true));
  464. }
  465. /**
  466. * 获取信息
  467. */
  468. static function get($url, $param, $config)
  469. {
  470. $url = $config['box'] == 1 ? self::$host . $url : self::$test_host . $url;
  471. $header = array();
  472. $header['Authorization'] = self::getAuth('sig', $param, $config);
  473. $result = Dever::curl($url, $param, 'post', true, $header);
  474. if (strstr($result, '<html><head>')) {
  475. Dever::alert('系统错误');
  476. }
  477. $result = Dever::json_decode($result);
  478. if (isset($result['errCode'])) {
  479. if ($result['errCode'] == '0000' || $result['errCode'] == 'SUCCESS') {
  480. return $result;
  481. } elseif (isset($result['errInfo'])) {
  482. Dever::alert($result['errInfo']);
  483. } elseif (isset($result['errMsg'])) {
  484. Dever::alert($result['errMsg']);
  485. }
  486. } else {
  487. Dever::alert('系统错误');
  488. }
  489. return $result;
  490. }
  491. }