Yspay.php 15 KB

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