pay.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /* eslint-disable */
  2. // h5调试
  3. var hostName = location.host;
  4. if (!(hostName.indexOf(configObj.productionEnvHost) > -1)) {
  5. if (configObj.isDebug) {
  6. new window.VConsole();
  7. }
  8. }
  9. $(document).ready(function() {
  10. // 解决移动端300ms延迟
  11. FastClick.attach(document.body);
  12. // 微信授权码
  13. var code = '',
  14. // 订单页面设置的金额
  15. amount = GetQueryString('price'),
  16. // 微信SDK的URL
  17. wxPaySDKURL = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
  18. // 支付宝SDK的URL
  19. aliPaySDKURL =
  20. 'https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.inc.min.js',
  21. // 订单号
  22. mer_ord_id =
  23. localStorage.getItem('mer_ord_id') ||
  24. dayjs().format('YYYYMMDDHHmmssSSS') + '' + randomNum(100, 999),
  25. // 流水号
  26. hf_seq_id = '',
  27. // 轮训支付状态定时标识
  28. timer = null,
  29. // 银联授权码
  30. userAuthCode = '',
  31. // IP
  32. client_ip = '',
  33. // 银联userID
  34. union_user_id = '',
  35. // 银联授权码状态码
  36. respCode = '',
  37. // 倒计时时间
  38. effectTime = configObj.mobile.payTime * 60,
  39. pay_minute = '20',
  40. pay_second = '00',
  41. // 支付类型
  42. tradeType = '';
  43. // 埋点
  44. MonitorMinSDK.init({
  45. pid: 'dg-checkout',
  46. appToken: 'app-226f04f1-f5ae-4ac3-b420-032b518cd0e9',
  47. appKey: '24e67f6771036c5cd6225eebe1a99671',
  48. });
  49. const params = {
  50. huifu_id: configObj.huifuId,
  51. os: 'h5',
  52. page: 'full'
  53. };
  54. MonitorMinSDK.track('0090_00006404', params, true);
  55. // 订单倒计时,全屏幕版才会有倒计时
  56. if ($('#pay_minute') && $('#pay_minute').length) {
  57. startCountDown();
  58. }
  59. // 弹层收银台时,订单页面显示
  60. if ($('#orderPage') && $('#orderPage').length) {
  61. $('#priceOrder').text(amount);
  62. $('#countOrder').text(amount * 100);
  63. }
  64. // 支付环境判断
  65. payEnvHandle();
  66. // 取消事件
  67. $('#cashierCancelBtn').click(function() {
  68. location.href = jumpLink('orderConfirm.html?price=' + amount);
  69. });
  70. // 支付点击事件
  71. $('#pay-button').click(function() {
  72. console.log('触发点击')
  73. payType();
  74. });
  75. // 重新下单
  76. $('#continuePayBtn').click(function() {
  77. reOrder();
  78. });
  79. // 切换支付类型
  80. var list = document.getElementsByTagName('li');
  81. for (let i = 0; i < list.length; i++) {
  82. list[i].onclick = function(e) {
  83. $(`#${list[i].id} input`).prop('checked', false);
  84. $(`#${e.target.id} input`).prop('checked', true);
  85. if (e.target.id === 'huabeipayItem') {
  86. tradeType = 'FQ_ALIPAY';
  87. } else if (e.target.id === 'bankpayItem') {
  88. tradeType = 'FQ_BANK';
  89. }
  90. };
  91. }
  92. // 上传标识
  93. function uploadPayInfo() {
  94. var params = {
  95. product_id: configObj.productId,
  96. sys_id: configObj.sysId,
  97. data: {
  98. //
  99. huifu_id: configObj.huifuId,
  100. resource: 'H5',
  101. id_code: 'co',
  102. action: 'CALL',
  103. ref_req_date: dayjs().format('YYYYMMDD'), //YYYYMMDD
  104. // 交易的订单号
  105. ref_req_seqid: mer_ord_id, //orderID
  106. },
  107. };
  108. axios.post(configObj.prodUploadPayAPI, params);
  109. }
  110. // 环境判断,加载不同支付选项
  111. function payEnvHandle() {
  112. if (isInWeiXinApp) {
  113. loadPaySDK(wxPaySDKURL);
  114. $('#wxpayItem').show();
  115. $('#bankpayItem').show();
  116. $('#wxpayInput').attr('checked', true);
  117. code = GetQueryString('code');
  118. let type = GetQueryString('type');
  119. let state = GetQueryString('state');
  120. if (!code) {
  121. // url重定向带上当前金额
  122. // 微信code获取
  123. weixinAuth();
  124. } else {
  125. if (!localStorage.getItem('openid')) {
  126. try {
  127. // var paymentData = {
  128. // auth_code: code,
  129. // client_type: '1',
  130. // };
  131. var paymentData = {
  132. type: type,
  133. code: code,
  134. state: state,
  135. };
  136. // 获取openid
  137. service
  138. .post(configObj.api.wxAuth, paymentData)
  139. .then((res) => {
  140. console.log('-log- ~weixin- data', res.data);
  141. const {
  142. openid
  143. } = res.data;
  144. if (res.data && openid) {
  145. $('#pageLoadingMask').hide();
  146. localStorage.setItem('openid', openid);
  147. }
  148. })
  149. .catch((error) => {
  150. console.log('-log- weixin~ error', error);
  151. alert(error);
  152. });
  153. } catch (error) {
  154. console.log('weixin---', error);
  155. }
  156. } else {
  157. $('#pageLoadingMask').hide();
  158. }
  159. }
  160. console.log('到此处了')
  161. } else if (isInUnionApp) {
  162. console.log('---union--env--');
  163. $('#quickpasspayItem').show();
  164. $('#bankpayItem').show();
  165. $('#quickpasspayInput').attr('checked', true);
  166. respCode = GetQueryString('respCode');
  167. userAuthCode = GetQueryString('userAuthCode');
  168. if (!respCode || respCode.length === 0) {
  169. unionPayReady();
  170. } else {
  171. getUnionUserId(userAuthCode);
  172. }
  173. } else {
  174. console.log('---alipay env---');
  175. loadPaySDK(aliPaySDKURL);
  176. $('#alipayItem').show();
  177. $('#huabeipayItem').show();
  178. $('#bankpayItem').show();
  179. $('#alipayInput').attr('checked', true);
  180. // 页面加载完,隐藏页面loading
  181. $('#pageLoadingMask').hide();
  182. }
  183. console.log('yyyyyyyyyyyyy55555555555')
  184. }
  185. // 点击支付时,支付逻辑判断
  186. function payType() {
  187. // 银行卡分期 花呗分期
  188. if (tradeType === 'FQ_BANK' || tradeType === 'FQ_ALIPAY') {
  189. fenqiPay(tradeType);
  190. return;
  191. }
  192. if (isInWeiXinApp) {
  193. wxPay();
  194. } else if (isInUnionApp) {
  195. $('#loadingMask').show();
  196. // 银联云闪付,需要传递用户IP
  197. axios
  198. .get('https://api.ipify.org/?format=json')
  199. .then((res) => {
  200. const {
  201. data: ipInfo
  202. } = res;
  203. client_ip = ipInfo.ip;
  204. unionPay();
  205. })
  206. .catch(() => {
  207. client_ip = '172.31.19.51';
  208. unionPay();
  209. });
  210. } else {
  211. aliPay();
  212. }
  213. }
  214. // 分期支付
  215. function fenqiPay(tradeType) {
  216. try {
  217. let goods_desc =
  218. tradeType == 'FQ_BANK' ? '银行卡分期测试商品-无线鼠标' : '花呗分期测试商品-无线鼠标';
  219. var paymentCreateData = {
  220. amount: amount,
  221. trade_type: tradeType,
  222. goods_desc,
  223. extra_info: {
  224. mer_ord_id,
  225. },
  226. user_id: '',
  227. };
  228. $('#loadingMask').show();
  229. service
  230. .post(configObj.createPayURL, paymentCreateData)
  231. .then((res) => {
  232. console.log('-log-alipay ~ res', res);
  233. if (res && res.resp_code === '000000') {
  234. const {
  235. json_data
  236. } = res;
  237. if (json_data.req_seq_id) {
  238. hf_seq_id = json_data.req_seq_id;
  239. let payType = tradeType === 'FQ_BANK' ? 'unionpay' : 'alipay';
  240. var url =
  241. `https://hfenqi.cloudpnr.com/h5/qrcode/?huifuId=${configObj.huifuId}&productId=${configObj.productId}&reqSeqId=${json_data.req_seq_id}&payType=${payType}&transAmt=${amount}`;
  242. window.location.href = url;
  243. }
  244. } else {
  245. $('#loadingMask').hide();
  246. }
  247. })
  248. .catch((error) => {
  249. console.log('--fenqiPay--error--', error);
  250. $('#loadingMask').hide();
  251. });
  252. } catch (error) {
  253. console.log(error.toString());
  254. }
  255. }
  256. // 支付方式-支付宝
  257. function aliPay() {
  258. try {
  259. var paymentData = {
  260. amount: amount,
  261. trade_type: 'A_NATIVE',
  262. goods_desc: '支付宝测试商品-无线鼠标',
  263. extra_info: {
  264. mer_ord_id,
  265. },
  266. user_id: '',
  267. };
  268. $('#loadingMask').show();
  269. service
  270. .post(configObj.api.createPay, paymentData)
  271. .then((res) => {
  272. console.log('-log-alipay ~ res', res);
  273. // 下单成功上传凭证,获取对应奖励
  274. uploadPayInfo();
  275. const {
  276. json_data,
  277. pay_info
  278. } = res;
  279. if (res && res.resp_code === '000000') {
  280. if (pay_info && json_data.hf_seq_id) {
  281. hf_seq_id = json_data.hf_seq_id;
  282. timer = setInterval(function() {
  283. queryOrder(hf_seq_id);
  284. }, 5000);
  285. window.location.href =
  286. 'alipays://platformapi/startapp?saId=10000007&qrcode=' + pay_info;
  287. } else {
  288. alert(json_data.resp_desc);
  289. }
  290. } else {
  291. $('#loadingMask').hide();
  292. }
  293. })
  294. .catch((error) => {
  295. console.log('--alipay--error--', error);
  296. $('#loadingMask').hide();
  297. });
  298. } catch (error) {
  299. console.log(error.toString());
  300. }
  301. }
  302. // 支付方式-微信
  303. function wxPay() {
  304. $('#loadingMask').show();
  305. try {
  306. // 生成订单
  307. // 当前页面取消支付,重新生成订单号
  308. mer_ord_id = dayjs().format('YYYYMMDDHHmmssSSS') + '' + randomNum(100, 999);
  309. localStorage.setItem('mer_ord_id', mer_ord_id);
  310. var paymentData = {
  311. amount: amount,
  312. trade_type: 'T_JSAPI',
  313. goods_desc: '微信测试商品-无线鼠标',
  314. extra_info: {
  315. mer_ord_id,
  316. },
  317. // 微信openID
  318. user_id: localStorage.getItem('openid'),
  319. };
  320. service
  321. .post(configObj.api.createPay, paymentData)
  322. .then((res) => {
  323. console.log('-log-wxPay ~ res', res);
  324. const {
  325. json_data
  326. } = res;
  327. // 下单成功上传凭证,获取对应奖励
  328. uploadPayInfo();
  329. if (json_data && json_data.pay_info && json_data.hf_seq_id) {
  330. hf_seq_id = json_data.hf_seq_id;
  331. let pay_info = JSON.parse(json_data.pay_info);
  332. // JSAPI调起支付
  333. if (typeof WeixinJSBridge == 'undefined') {
  334. if (document.addEventListener) {
  335. document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  336. } else if (document.attachEvent) {
  337. document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
  338. document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  339. }
  340. } else {
  341. onBridgeReady(pay_info, queryOrder, hf_seq_id);
  342. }
  343. }
  344. })
  345. .catch((error) => {
  346. console.log('--weixinPay--error--', error);
  347. });
  348. } catch (error) {
  349. $('#loadingMask').hide();
  350. alert(error);
  351. console.log(error.toString());
  352. }
  353. }
  354. // 支付方式-云闪付
  355. function unionPay() {
  356. var paymentData = {
  357. amount: amount,
  358. trade_type: 'U_JSAPI',
  359. goods_desc: '银联测试商品-无线鼠标',
  360. extra_info: {
  361. mer_ord_id,
  362. user_id: union_user_id,
  363. },
  364. user_id: union_user_id,
  365. client_ip,
  366. };
  367. console.log('-log- ~ paymentData', paymentData);
  368. $('#loadingMask').show();
  369. service
  370. .post(configObj.api.createPay, paymentData)
  371. .then((res) => {
  372. console.log('-log-unionPay ~ res', res);
  373. // 下单成功上传凭证,获取对应奖励
  374. uploadPayInfo();
  375. if (res && res.resp_code === '000000') {
  376. $('#loadingMask').hide();
  377. const {
  378. pay_info
  379. } = res;
  380. console.log('-log- ~ pay_info', pay_info);
  381. if (pay_info) {
  382. window.location.href = pay_info;
  383. }
  384. } else {
  385. $('#loadingMask').hide();
  386. }
  387. })
  388. .catch((error) => {
  389. $('#loadingMask').hide();
  390. console.log('--unionPay--error--', error);
  391. });
  392. }
  393. // 银联环境跳转
  394. function unionPayReady() {
  395. userAuthCode = GetQueryString('userAuthCode');
  396. console.log('-log- unionPayReady~ userAuthCode', userAuthCode);
  397. let urlNow = encodeURIComponent(window.location.href);
  398. let url = 'https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=' + urlNow;
  399. window.location = url;
  400. }
  401. // 获取银联用户ID
  402. function getUnionUserId(userAuthCode) {
  403. // 隐藏page loading
  404. $('#pageLoadingMask').show();
  405. var params = {
  406. auth_code: decodeURIComponent(userAuthCode),
  407. };
  408. console.log('-log- union-getUserId~ params', params);
  409. service
  410. .post(configObj.api.unionpayAuth, params)
  411. .then((res) => {
  412. console.log('-log- ~union-userInfo- data', res);
  413. const {
  414. jsonData,
  415. resp_code,
  416. json_data
  417. } = res;
  418. if (resp_code == '000000') {
  419. $('#pageLoadingMask').hide();
  420. if (jsonData && jsonData.user_id) {
  421. union_user_id = jsonData.user_id;
  422. } else if (json_data && json_data.user_id) {
  423. union_user_id = json_data.user_id;
  424. }
  425. } else {
  426. // alert(jsonData.return_desc);
  427. $('#pageLoadingMask').hide();
  428. }
  429. })
  430. .catch((error) => {
  431. $('#pageLoadingMask').hide();
  432. console.log('union--getUserId--error', error);
  433. // alert(JSON.stringify(error));
  434. });
  435. }
  436. // 拉起微信支付
  437. function onBridgeReady(pay_info, callback, hf_seq_id) {
  438. if (typeof WeixinJSBridge !== 'undefined') {
  439. WeixinJSBridge.invoke(
  440. 'getBrandWCPayRequest', {
  441. 'appId': pay_info.appId, //appid
  442. 'timeStamp': pay_info.timeStamp, //时间戳,自1970年以来的秒数
  443. 'nonceStr': pay_info.nonceStr, //随机串
  444. 'package': pay_info.package,
  445. 'signType': pay_info.signType, //微信签名方式:
  446. 'paySign': pay_info.paySign, //微信签名
  447. },
  448. function(res) {
  449. console.log('====>: onBridgeReady -> res', res);
  450. if (res.err_msg == 'get_brand_wcpay_request:ok') {
  451. // 使用以上方式判断前端返回,微信团队郑重提示:
  452. //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
  453. callback(hf_seq_id);
  454. } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
  455. $('#loadingMask').hide();
  456. $('#cancelPay').show();
  457. $('#continuePay').click(function() {
  458. $('#cancelPay').hide();
  459. });
  460. } else {
  461. callback(hf_seq_id);
  462. }
  463. }
  464. );
  465. } else {
  466. console.log('不是在微信app内');
  467. }
  468. }
  469. // 加载支付SDK
  470. function loadPaySDK(url) {
  471. return new Promise((resolve, reject) => {
  472. let script = document.createElement('script');
  473. script.type = 'text/javascript';
  474. script.src = url;
  475. script.onload = () => {
  476. resolve(true);
  477. };
  478. script.onerror = reject;
  479. document.head.appendChild(script);
  480. });
  481. }
  482. // 支付成功
  483. function paySuccess() {
  484. location.href = jumpLink('paySuccess.html?price=' + amount);
  485. }
  486. // 支付失败
  487. function payFail() {
  488. location.href = jumpLink('payFail.html?price=' + amount);
  489. }
  490. // 查询订单详情
  491. function queryOrder(hf_seq_id) {
  492. var queryOrderData;
  493. if (tradeType === 'FQ_ALIPAY') {
  494. queryOrderData = {
  495. org_req_seq_id: hf_seq_id,
  496. };
  497. } else {
  498. queryOrderData = {
  499. hf_seq_id,
  500. };
  501. }
  502. service
  503. .post(configObj.api.queryPay, queryOrderData)
  504. .then((res) => {
  505. console.log('-log-queryOrder ~ res', res);
  506. const {
  507. json_data,
  508. resp_code
  509. } = res;
  510. if (json_data && (resp_code === '000000' || resp_code === '00000000')) {
  511. if (json_data.trans_stat == 'S') {
  512. // 支付成功
  513. clearInterval(timer);
  514. // 支付成功时间
  515. localStorage.setItem('end_time', json_data.end_time);
  516. $('#loadingMask').hide();
  517. paySuccess();
  518. } else if (json_data.trans_stat == 'F') {
  519. // 支付失败
  520. clearInterval(timer);
  521. $('#loadingMask').hide();
  522. payFail();
  523. }
  524. } else {
  525. $('#loadingMask').hide();
  526. clearInterval(timer);
  527. }
  528. })
  529. .catch((error) => {
  530. console.log('--queryOrder--error--', error);
  531. });
  532. }
  533. // 查询 online 订单详情 针对分期支付订单
  534. function queryOnlineOrder(hf_seq_id) {
  535. var queryOrderData = {
  536. org_req_seq_id: hf_seq_id,
  537. };
  538. service
  539. .post(configObj.onlineQueryPayURL, queryOrderData)
  540. .then((res) => {
  541. console.log('-log-query OnlineOrder ~ res', res);
  542. const {
  543. json_data,
  544. resp_code
  545. } = res;
  546. if (json_data && (resp_code === '000000' || resp_code === '00000000')) {
  547. if (json_data.trans_stat == 'S') {
  548. // 支付成功
  549. clearInterval(timer);
  550. // 支付成功时间
  551. localStorage.setItem('end_time', json_data.end_time);
  552. $('#loadingMask').hide();
  553. paySuccess();
  554. } else if (json_data.trans_stat == 'F') {
  555. // 支付失败
  556. clearInterval(timer);
  557. $('#loadingMask').hide();
  558. payFail();
  559. }
  560. }
  561. })
  562. .catch((error) => {
  563. console.log('--query OnlineOrder--error--', error);
  564. });
  565. }
  566. // 倒计时
  567. function startCountDown() {
  568. let count = 0;
  569. const startTime = Date.now();
  570. const fixed = () => {
  571. count++;
  572. effectTime -= 1;
  573. if (effectTime < 0) return;
  574. const offset = Date.now() - (startTime + count * 1000);
  575. let nextTime = 1000 - offset;
  576. if (nextTime < 0) nextTime = 0;
  577. formatSeconds(effectTime);
  578. timeoutRemind(effectTime);
  579. setTimeout(fixed, nextTime);
  580. };
  581. setTimeout(fixed, 1000);
  582. }
  583. // 格式化时间
  584. function formatSeconds(seconds) {
  585. if (seconds < 0) return;
  586. pay_minute = String((seconds / 60) % 60 | 0).padStart(2, '0');
  587. pay_second = String(seconds % 60 | 0).padStart(2, '0');
  588. document.getElementById('pay_minute').innerText = pay_minute;
  589. document.getElementById('pay_second').innerText = pay_second;
  590. }
  591. // 超时提醒
  592. function timeoutRemind(seconds) {
  593. if (seconds <= 0) {
  594. document.getElementById('timeoutRemind').classList.remove('hide');
  595. }
  596. }
  597. // 重新下单
  598. function reOrder() {
  599. $('#timeoutRemind').hide();
  600. const toUrl = jumpLink('goodsDetail.html');
  601. if (history.replaceState) {
  602. history.replaceState(null, document.title, toUrl);
  603. history.go(0);
  604. } else {
  605. location.replace(toUrl);
  606. }
  607. }
  608. // 跳转链接
  609. function jumpLink(urlName) {
  610. const origin = location.origin;
  611. const pathname = location.pathname;
  612. const urlAry = pathname.split('/');
  613. urlAry.pop();
  614. urlAry.push(urlName);
  615. const urlStr = urlAry.join('/');
  616. const link = origin + urlStr;
  617. return link;
  618. }
  619. });