Yspay.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. }
  39. $sign = $input['sign'];
  40. unset($input['sign']);
  41. if (isset($input['e_sign'])) {
  42. unset($input['sign']);
  43. }
  44. ksort($input);
  45. $string = array();
  46. foreach ($input as $k => $v) {
  47. if (strstr($v, '&') || strstr($v, '@')) {
  48. $v = urlencode($v);
  49. }
  50. $string[] = $k . '=' . $v;
  51. }
  52. $string = implode('&', $string);
  53. $string .= $this->config['key'];
  54. if ($input['signType'] == 'SHA256') {
  55. $string = hash("sha256", $string);
  56. } else {
  57. $string = md5($string);
  58. }
  59. $string = strtoupper($string);
  60. $input['sign'] = $sign;
  61. $input['e_sign'] = $string;
  62. $this->log('支付回调-初始化', $input);
  63. if ($sign == $string) {
  64. if (isset($input['billNo']) && $input['billNo']) {
  65. $key = 'billNo';
  66. } else {
  67. $key = 'merOrderId';
  68. }
  69. if (isset($this->config['prefix']) && $this->config['prefix']) {
  70. $input[$key] = str_replace($this->config['prefix'], '', $input[$key]);
  71. }
  72. if (!isset($input['status'])) {
  73. echo 'FAILED';die;
  74. }
  75. $desc = '';
  76. if ($input['status'] == 'TRADE_SUCCESS') {
  77. # 成功
  78. } if ($input['status'] == 'TRADE_REFUND') {
  79. # 退款
  80. echo 'SUCCESS';die;
  81. } elseif ($input['status'] == 'TRADE_CLOSED') {
  82. $desc = '交易关闭';
  83. } elseif ($input['status'] == 'UNKNOWN') {
  84. $desc = '不明确的交易状态';
  85. } else {
  86. echo 'FAILED';die;
  87. }
  88. $this->updateOrder($input[$key], $input['totalAmount']);
  89. echo 'SUCCESS';die;
  90. } else {
  91. echo 'FAILED';die;
  92. }
  93. }
  94. /**
  95. * 获取统一下单的基本信息
  96. */
  97. public function order($account_id, $project_id, $uid, $username, $product_id, $name, $cash, $openid = false, $type = 1, $order_id = false, $other = false)
  98. {
  99. $order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $this->config['type'], $order_id);
  100. if (isset($this->config['prefix']) && $this->config['prefix']) {
  101. $request['merOrderId'] = $this->config['prefix'] . $order_id;
  102. } else {
  103. $request['merOrderId'] = $order_id;
  104. }
  105. $request['mid'] = $this->config['mid'];
  106. $request['tid'] = $this->config['tid'];
  107. $request['instMid'] = 'MINIDEFAULT';
  108. $request['totalAmount'] = $cash * 100;
  109. //$request['totalAmount'] = 100;
  110. $request['subAppId'] = $this->config['sub_appid'];
  111. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  112. $request['expireTime'] = date("Y-m-d H:i:s", time() + $this->config['timeout']);
  113. $request['notifyUrl'] = $this->config['notify'];
  114. $request['tradeType'] = 'MINI';
  115. if ($other) {
  116. $request['originalAmount'] = $other['oprice'] * 100;
  117. $request['divisionFlag'] = true;
  118. # 平台分账金额
  119. $other['per'] = $other['per']/100;
  120. $request['platformAmount'] = $request['totalAmount'] * $other['per'];
  121. $request['subOrders'] = array();
  122. $request['subOrders']['mid'] = $other['mid'];
  123. if (isset($this->config['prefix']) && $this->config['prefix']) {
  124. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  125. } else {
  126. $request['subOrders']['merOrderId'] = $other['order_id'];
  127. }
  128. $request['subOrders']['totalAmount'] = $request['totalAmount'] - $request['platformAmount'];
  129. $request['subOrders'] = array($request['subOrders']);
  130. }
  131. if (!$openid) {
  132. # 测试的openid
  133. $request['subOpenId'] = 'ofBUV0RUoy_8C4VctZjrSDGzhUfY';
  134. } else {
  135. $request['subOpenId'] = $openid;
  136. }
  137. if ($type == 2) {
  138. # 二维码支付
  139. $request['billNo'] = $request['merOrderId'];
  140. unset($request['merOrderId']);
  141. $result = Base::get_pay_code($request, $this->config);
  142. if (isset($result['billQRCode'])) {
  143. $result['request'] = $request;
  144. $result['payMsg'] = $result['billQRCode'];
  145. if ($other) {
  146. $result['other'] = $other;
  147. }
  148. $this->updateOrderParam($order_id, $result);
  149. return $result['payMsg'];
  150. }
  151. } else {
  152. # 小程序支付
  153. $result = Base::pay($request, $this->config);
  154. if (isset($result['miniPayRequest'])) {
  155. $result['request'] = $request;
  156. $result['payMsg'] = $result['miniPayRequest'];
  157. unset($result['miniPayRequest']);
  158. if ($other) {
  159. $result['other'] = $other;
  160. }
  161. $this->updateOrderParam($order_id, $result);
  162. return $result['payMsg'];
  163. }
  164. }
  165. return false;
  166. }
  167. # 退款
  168. public function refund($order_id, $cash, $order, $refund_order_id = false)
  169. {
  170. if (isset($this->config['prefix']) && $this->config['prefix']) {
  171. $request['merOrderId'] = $this->config['prefix'] . $order_id;
  172. if ($refund_order_id) {
  173. $request['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  174. }
  175. } else {
  176. $request['merOrderId'] = $order_id;
  177. if ($refund_order_id) {
  178. $request['refundOrderId'] = $refund_order_id;
  179. }
  180. }
  181. $request['mid'] = $this->config['mid'];
  182. $request['tid'] = $this->config['tid'];
  183. $request['instMid'] = 'MINIDEFAULT';
  184. if (isset($order['param']['targetOrderId'])) {
  185. $request['targetOrderId'] = $order['param']['targetOrderId'];
  186. }
  187. $request['subAppId'] = $this->config['appid'];
  188. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  189. $request['refundAmount'] = $cash * 100;
  190. if (isset($order['param']['other']) && $order['param']['other']) {
  191. $other = $order['param']['other'];
  192. $other['per'] = $other['per']/100;
  193. $request['platformAmount'] = $request['refundAmount'] * $other['per'];
  194. $request['subOrders'] = array();
  195. $request['subOrders']['mid'] = $other['mid'];
  196. if (isset($this->config['prefix']) && $this->config['prefix']) {
  197. $request['subOrders']['merOrderId'] = $this->config['prefix'] . $other['order_id'];
  198. if ($refund_order_id) {
  199. $request['subOrders']['refundOrderId'] = $this->config['prefix'] . $refund_order_id;
  200. }
  201. } else {
  202. $request['subOrders']['merOrderId'] = $other['order_id'];
  203. if ($refund_order_id) {
  204. $request['subOrders']['refundOrderId'] = $refund_order_id;
  205. }
  206. }
  207. $request['subOrders']['totalAmount'] = $request['refundAmount'] - $request['platformAmount'];
  208. $request['subOrders'] = array($request['subOrders']);
  209. }
  210. $result = Base::refund($request, $this->config);
  211. if (isset($result['refundStatus']) && $result['refundStatus'] == 'SUCCESS') {
  212. return true;
  213. }
  214. return false;
  215. }
  216. # 查询
  217. public function query($order_id)
  218. {
  219. $request['merOrderId'] = $order_id;
  220. $request['mid'] = $this->config['mchid'];
  221. $request['tid'] = $this->config['key'];
  222. $request['instMid'] = 'MINIDEFAULT';
  223. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  224. $result = Base::refund($request, $this->config);
  225. return $result;
  226. }
  227. # 关闭订单
  228. public function close($order_id)
  229. {
  230. $request['merOrderId'] = $order_id;
  231. $request['mid'] = $this->config['mchid'];
  232. $request['tid'] = $this->config['key'];
  233. $request['instMid'] = 'MINIDEFAULT';
  234. $request['requestTimestamp'] = date("Y-m-d H:i:s");
  235. $result = Base::close($request, $this->config);
  236. return $result;
  237. }
  238. /**
  239. * 获取二维码支付
  240. */
  241. public function qrcode($order, $refer)
  242. {
  243. $result['type'] = 'qrcode';
  244. $result['url'] = $order;
  245. return $result;
  246. }
  247. /**
  248. * 获取小程序支付
  249. */
  250. public function applet($order)
  251. {
  252. $result = array();
  253. if (isset($order['package'])) {
  254. $prepay_id = str_replace('prepay_id=', '', $order['package']);
  255. $result['time'] = $order['timeStamp'];
  256. $result['nonce_str'] = $order['nonceStr'];
  257. $result['prepay_id'] = $prepay_id;
  258. $result['sign_type'] = $order['signType'];
  259. $result['sign'] = $order['paySign'];
  260. $result['type'] = 'applet';
  261. }
  262. return $result;
  263. }
  264. /**
  265. * 获取页面支付
  266. */
  267. public function page($order, $refer)
  268. {
  269. $refer = urldecode($refer);
  270. $tools = new \JsApiPay($this->config);
  271. $info = $tools->GetJsApiParameters($order);
  272. $html = '<script type="text/javascript">
  273. function jsApiCall()
  274. {
  275. WeixinJSBridge.invoke(
  276. "getBrandWCPayRequest",
  277. '.$info.',
  278. function(res){
  279. //WeixinJSBridge.log(res.err_msg);
  280. if(res.err_msg == "get_brand_wcpay_request:ok")
  281. {
  282. location.href = "'.$refer.'";
  283. } else {
  284. alert(res.err_code+res.err_desc+res.err_msg);
  285. }
  286. }
  287. );
  288. }
  289. function callpay()
  290. {
  291. if (typeof WeixinJSBridge == "undefined"){
  292. if( document.addEventListener ){
  293. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  294. }else if (document.attachEvent){
  295. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  296. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  297. }
  298. }else{
  299. jsApiCall();
  300. }
  301. }
  302. callpay();
  303. </script>';
  304. return $html;
  305. }
  306. }
  307. class Base
  308. {
  309. static $test_host = 'https://test-api-open.chinaums.com/';
  310. static $host = 'https://api-mop.chinaums.com/';
  311. static $signMethod = 'SHA256'; //签名方式
  312. # 获取token
  313. static $token_url = 'v1/token/access';
  314. # 微信下单支付
  315. static $pay_wechat_url = 'v1/netpay/wx/unified-order';
  316. # 支付宝下单支付
  317. static $pay_alipay_url = 'v1/netpay/trade/create';
  318. # 云闪付下单支付
  319. static $pay_uac_url = 'v1/netpay/uac/mini-order';
  320. # 交易查询
  321. static $query_url = 'v1/netpay/query';
  322. # 退款
  323. static $refund_url = 'v1/netpay/refund';
  324. # 退款查询
  325. static $refund_query_url = 'v1/netpay/refund-query';
  326. # 订单关闭
  327. static $close_url = 'v1/netpay/close';
  328. # 二维码支付
  329. static $qrcode_url = 'v1/netpay/bills/get-qrcode';
  330. //===================== 支付相关 ==============================
  331. /**
  332. * 支付交易
  333. */
  334. static public function pay($param, $config)
  335. {
  336. $url = self::$pay_wechat_url;
  337. $result = self::get($url, $param, $config);
  338. return $result;
  339. }
  340. /**
  341. * 获取支付二维码
  342. */
  343. static public function get_pay_code($param, $config)
  344. {
  345. $url = self::$qrcode_url;
  346. $result = self::get($url, $param, $config);
  347. return $result;
  348. }
  349. /**
  350. * 支付撤销
  351. */
  352. static public function close()
  353. {
  354. $url = self::$close_url;
  355. $result = self::get($url, $param, $config);
  356. return $result;
  357. }
  358. /**
  359. * 交易退款
  360. */
  361. static public function refund($param, $config)
  362. {
  363. $url = self::$refund_url;
  364. $result = self::get($url, $param, $config);
  365. return $result;
  366. }
  367. /**
  368. * 交易查询
  369. */
  370. static public function query()
  371. {
  372. $url = self::$query_url;
  373. $result = self::get($url, $param, $config);
  374. return $result;
  375. }
  376. /**
  377. * 交易退款查询
  378. */
  379. static public function refundQuery()
  380. {
  381. $url = self::$refund_query_url;
  382. $result = self::get($url, $param, $config);
  383. return $result;
  384. }
  385. //====================== 获取调用凭证===========================
  386. /**
  387. * 通用调用凭证获取
  388. * 默认使用token方式,使用签名方式需要传入参数
  389. */
  390. static public function getAuth($type = 'token', $param, $config)
  391. {
  392. if ($type === 'token') {
  393. return self::getAccessTokenByToken($config);
  394. }
  395. return self::getAccessTokenBySig($param, $config);
  396. }
  397. /**
  398. * 方式一,OPEN-ACCESS-TOKEN方式
  399. */
  400. static function getAccessTokenByToken($config)
  401. {
  402. $param = [
  403. 'appId' => $config['appid'],
  404. 'timestamp' => date('YmdHis'),
  405. 'nonce' => md5(uniqid(microtime(true),true)),
  406. 'signMethod' => self::$signMethod,
  407. ];
  408. $param['signature'] = self::signature($param, $config['appsecret']);
  409. $result = self::get(self::$token_url, $param, $config);
  410. if (isset($result['errCode']) && isset($result['accessToken'])) {
  411. return 'OPEN-ACCESS-TOKEN AccessToken='.$result['accessToken'];
  412. }
  413. return '';
  414. }
  415. /**
  416. * 方式二,OPEN-BODY-SIG方式
  417. */
  418. static function getAccessTokenBySig($data, $config)
  419. {
  420. $param = [
  421. 'AppId' => $config['appid'],
  422. 'Timestamp' => date('YmdHis'),
  423. 'Nonce' => md5(uniqid(microtime(true),true))
  424. ];
  425. return 'OPEN-BODY-SIG AppId="'.$param['AppId'].'", Timestamp="'.$param['Timestamp'].'", Nonce="'.$param['Nonce'].'", Signature="'.self::signature2($data, $param, $config['appsecret']).'"';
  426. }
  427. /**
  428. * 计算签名,方式一
  429. */
  430. static function signature($param, $appsecret)
  431. {
  432. return bin2hex(hash(self::$signMethod, $param['appId'].$param['timestamp'].$param['nonce'].$appsecret, true));
  433. }
  434. /**
  435. * 计算签名,方式二
  436. */
  437. static function signature2($data, $param, $appsecret)
  438. {
  439. $str = bin2hex(hash('sha256', Dever::json_encode($data), true));
  440. return base64_encode(hash_hmac('sha256', $param['AppId'].$param['Timestamp'].$param['Nonce'].$str, $appsecret, true));
  441. }
  442. /**
  443. * 获取信息
  444. */
  445. static function get($url, $param, $config)
  446. {
  447. $url = $config['box'] == 1 ? self::$host . $url : self::$test_host . $url;
  448. $header = array();
  449. $header['Authorization'] = self::getAuth('sig', $param, $config);
  450. $result = Dever::curl($url, $param, 'post', true, $header);
  451. if (strstr($result, '<html><head>')) {
  452. Dever::alert('系统错误');
  453. }
  454. $result = Dever::json_decode($result);
  455. if (isset($result['errCode'])) {
  456. if ($result['errCode'] == '0000' || $result['errCode'] == 'SUCCESS') {
  457. return $result;
  458. } elseif (isset($result['errInfo'])) {
  459. Dever::alert($result['errInfo']);
  460. } elseif (isset($result['errMsg'])) {
  461. Dever::alert($result['errMsg']);
  462. }
  463. } else {
  464. Dever::alert('系统错误');
  465. }
  466. return $result;
  467. }
  468. }