Yspay.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. } if ($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. $result = Base::refund($request, $this->config);
  218. if (isset($result['refundStatus']) && $result['refundStatus'] == 'SUCCESS') {
  219. return true;
  220. }
  221. return false;
  222. }
  223. # 查询
  224. public function query($order_id)
  225. {
  226. $request['merOrderId'] = $order_id;
  227. $request['mid'] = $this->config['mchid'];
  228. $request['tid'] = $this->config['key'];
  229. $request['instMid'] = 'MINIDEFAULT';
  230. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  231. $result = Base::refund($request, $this->config);
  232. return $result;
  233. }
  234. # 关闭订单
  235. public function close($order_id)
  236. {
  237. $request['merOrderId'] = $order_id;
  238. $request['mid'] = $this->config['mchid'];
  239. $request['tid'] = $this->config['key'];
  240. $request['instMid'] = 'MINIDEFAULT';
  241. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  242. $result = Base::close($request, $this->config);
  243. return $result;
  244. }
  245. /**
  246. * 获取二维码支付
  247. */
  248. public function qrcode($order, $refer)
  249. {
  250. $result['type'] = 'qrcode';
  251. $result['url'] = $order;
  252. return $result;
  253. }
  254. /**
  255. * 获取小程序支付
  256. */
  257. public function applet($order)
  258. {
  259. $result = array();
  260. if (isset($order['package'])) {
  261. $prepay_id = str_replace('prepay_id=', '', $order['package']);
  262. $result['time'] = $order['timeStamp'];
  263. $result['nonce_str'] = $order['nonceStr'];
  264. $result['prepay_id'] = $prepay_id;
  265. $result['sign_type'] = $order['signType'];
  266. $result['sign'] = $order['paySign'];
  267. $result['type'] = 'applet';
  268. }
  269. return $result;
  270. }
  271. /**
  272. * 获取页面支付
  273. */
  274. public function page($order, $refer)
  275. {
  276. $refer = urldecode($refer);
  277. $tools = new \JsApiPay($this->config);
  278. $info = $tools->GetJsApiParameters($order);
  279. $html = '<script type="text/javascript">
  280. function jsApiCall()
  281. {
  282. WeixinJSBridge.invoke(
  283. "getBrandWCPayRequest",
  284. '.$info.',
  285. function(res){
  286. //WeixinJSBridge.log(res.err_msg);
  287. if(res.err_msg == "get_brand_wcpay_request:ok")
  288. {
  289. location.href = "'.$refer.'";
  290. } else {
  291. alert(res.err_code+res.err_desc+res.err_msg);
  292. }
  293. }
  294. );
  295. }
  296. function callpay()
  297. {
  298. if (typeof WeixinJSBridge == "undefined"){
  299. if( document.addEventListener ){
  300. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  301. }else if (document.attachEvent){
  302. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  303. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  304. }
  305. }else{
  306. jsApiCall();
  307. }
  308. }
  309. callpay();
  310. </script>';
  311. return $html;
  312. }
  313. }
  314. class Base
  315. {
  316. static $test_host = 'https://test-api-open.chinaums.com/';
  317. static $host = 'https://api-mop.chinaums.com/';
  318. static $signMethod = 'SHA256'; //签名方式
  319. # 获取token
  320. static $token_url = 'v1/token/access';
  321. # 微信下单支付
  322. static $pay_wechat_url = 'v1/netpay/wx/unified-order';
  323. # 支付宝下单支付
  324. static $pay_alipay_url = 'v1/netpay/trade/create';
  325. # 云闪付下单支付
  326. static $pay_uac_url = 'v1/netpay/uac/mini-order';
  327. # 交易查询
  328. static $query_url = 'v1/netpay/query';
  329. # 退款
  330. static $refund_url = 'v1/netpay/refund';
  331. # 退款查询
  332. static $refund_query_url = 'v1/netpay/refund-query';
  333. # 订单关闭
  334. static $close_url = 'v1/netpay/close';
  335. # 二维码支付
  336. static $qrcode_url = 'v1/netpay/bills/get-qrcode';
  337. //===================== 支付相关 ==============================
  338. /**
  339. * 支付交易
  340. */
  341. static public function pay($param, $config)
  342. {
  343. $url = self::$pay_wechat_url;
  344. $result = self::get($url, $param, $config);
  345. return $result;
  346. }
  347. /**
  348. * 获取支付二维码
  349. */
  350. static public function get_pay_code($param, $config)
  351. {
  352. $url = self::$qrcode_url;
  353. $result = self::get($url, $param, $config);
  354. return $result;
  355. }
  356. /**
  357. * 支付撤销
  358. */
  359. static public function close()
  360. {
  361. $url = self::$close_url;
  362. $result = self::get($url, $param, $config);
  363. return $result;
  364. }
  365. /**
  366. * 交易退款
  367. */
  368. static public function refund($param, $config)
  369. {
  370. $url = self::$refund_url;
  371. $result = self::get($url, $param, $config);
  372. return $result;
  373. }
  374. /**
  375. * 交易查询
  376. */
  377. static public function query()
  378. {
  379. $url = self::$query_url;
  380. $result = self::get($url, $param, $config);
  381. return $result;
  382. }
  383. /**
  384. * 交易退款查询
  385. */
  386. static public function refundQuery()
  387. {
  388. $url = self::$refund_query_url;
  389. $result = self::get($url, $param, $config);
  390. return $result;
  391. }
  392. //====================== 获取调用凭证===========================
  393. /**
  394. * 通用调用凭证获取
  395. * 默认使用token方式,使用签名方式需要传入参数
  396. */
  397. static public function getAuth($type = 'token', $param, $config)
  398. {
  399. if ($type === 'token') {
  400. return self::getAccessTokenByToken($config);
  401. }
  402. return self::getAccessTokenBySig($param, $config);
  403. }
  404. /**
  405. * 方式一,OPEN-ACCESS-TOKEN方式
  406. */
  407. static function getAccessTokenByToken($config)
  408. {
  409. $param = [
  410. 'appId' => $config['appid'],
  411. 'timestamp' => date('YmdHis'),
  412. 'nonce' => md5(uniqid(microtime(true),true)),
  413. 'signMethod' => self::$signMethod,
  414. ];
  415. $param['signature'] = self::signature($param, $config['appsecret']);
  416. $result = self::get(self::$token_url, $param, $config);
  417. if (isset($result['errCode']) && isset($result['accessToken'])) {
  418. return 'OPEN-ACCESS-TOKEN AccessToken='.$result['accessToken'];
  419. }
  420. return '';
  421. }
  422. /**
  423. * 方式二,OPEN-BODY-SIG方式
  424. */
  425. static function getAccessTokenBySig($data, $config)
  426. {
  427. $param = [
  428. 'AppId' => $config['appid'],
  429. 'Timestamp' => date('YmdHis'),
  430. 'Nonce' => md5(uniqid(microtime(true),true))
  431. ];
  432. return 'OPEN-BODY-SIG AppId="'.$param['AppId'].'", Timestamp="'.$param['Timestamp'].'", Nonce="'.$param['Nonce'].'", Signature="'.self::signature2($data, $param, $config['appsecret']).'"';
  433. }
  434. /**
  435. * 计算签名,方式一
  436. */
  437. static function signature($param, $appsecret)
  438. {
  439. return bin2hex(hash(self::$signMethod, $param['appId'].$param['timestamp'].$param['nonce'].$appsecret, true));
  440. }
  441. /**
  442. * 计算签名,方式二
  443. */
  444. static function signature2($data, $param, $appsecret)
  445. {
  446. $str = bin2hex(hash('sha256', Dever::json_encode($data), true));
  447. return base64_encode(hash_hmac('sha256', $param['AppId'].$param['Timestamp'].$param['Nonce'].$str, $appsecret, true));
  448. }
  449. /**
  450. * 获取信息
  451. */
  452. static function get($url, $param, $config)
  453. {
  454. $url = $config['box'] == 1 ? self::$host . $url : self::$test_host . $url;
  455. $header = array();
  456. $header['Authorization'] = self::getAuth('sig', $param, $config);
  457. $result = Dever::curl($url, $param, 'post', true, $header);
  458. if (strstr($result, '<html><head>')) {
  459. Dever::alert('系统错误');
  460. }
  461. $result = Dever::json_decode($result);
  462. if (isset($result['errCode'])) {
  463. if ($result['errCode'] == '0000' || $result['errCode'] == 'SUCCESS') {
  464. return $result;
  465. } elseif (isset($result['errInfo'])) {
  466. Dever::alert($result['errInfo']);
  467. } elseif (isset($result['errMsg'])) {
  468. Dever::alert($result['errMsg']);
  469. }
  470. } else {
  471. Dever::alert('系统错误');
  472. }
  473. return $result;
  474. }
  475. }