pay.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. /**
  2. * uni-pay-co 统一支付服务实现
  3. */
  4. const crypto = require("crypto");
  5. const uniPay = require("uni-pay");
  6. const configCenter = require("uni-config-center");
  7. const config = configCenter({ pluginId: 'uni-pay' }).requireFile('config.js');
  8. const dao = require('../dao');
  9. const libs = require('../libs');
  10. const { UniCloudError, isUniPayError, ERROR } = require('../common/error')
  11. const db = uniCloud.database();
  12. const _ = db.command;
  13. const notifyPath = "/payNotify/";
  14. class service {
  15. constructor(obj) {
  16. }
  17. /**
  18. * 获取支付插件的完整配置
  19. */
  20. getConfig() {
  21. return config;
  22. }
  23. /**
  24. * 支付成功 - 异步通知
  25. */
  26. async paymentNotify(data = {}) {
  27. let {
  28. httpInfo,
  29. clientInfo,
  30. cloudInfo,
  31. isWxpayVirtual
  32. } = data;
  33. console.log('httpInfo: ', httpInfo);
  34. let path = httpInfo.path;
  35. let pay_type = path.substring(notifyPath.length);
  36. let provider = pay_type.split("-")[0]; // 获取支付供应商
  37. let provider_pay_type = pay_type.split("-")[1]; // 获取支付方式
  38. if (isWxpayVirtual) {
  39. // 微信虚拟支付固定参数
  40. provider = "wxpay-virtual";
  41. provider_pay_type = "mp";
  42. }
  43. // 初始化uniPayInstance
  44. let uniPayInstance = await this.initUniPayInstance({ provider, provider_pay_type });
  45. let notifyType = await uniPayInstance.checkNotifyType(httpInfo);
  46. console.log('notifyType: ', notifyType)
  47. if (notifyType === "token") {
  48. let verifyResult = await uniPayInstance.verifyTokenNotify(httpInfo);
  49. console.log('verifyResult: ', verifyResult)
  50. if (!verifyResult) {
  51. console.log('---------!签名验证未通过!---------');
  52. return;
  53. }
  54. // 校验token的测试接口,直接返回echostr
  55. return verifyResult.echostr;
  56. }
  57. if (notifyType !== "payment") {
  58. // 非支付通知直接返回成功
  59. console.log(`---------!非支付通知!---------`);
  60. return libs.common.returnNotifySUCCESS({ provider, provider_pay_type });
  61. }
  62. // 支付通知,验证签名
  63. let verifyResult = await uniPayInstance.verifyPaymentNotify(httpInfo);
  64. if (!verifyResult) {
  65. console.log('---------!签名验证未通过!---------');
  66. console.log('---------!签名验证未通过!---------');
  67. console.log('---------!签名验证未通过!---------');
  68. return {}
  69. }
  70. console.log('---------!签名验证通过!---------');
  71. verifyResult = JSON.parse(JSON.stringify(verifyResult)); // 这一句代码有用,请勿删除。
  72. console.log('verifyResult: ', verifyResult)
  73. let {
  74. outTradeNo,
  75. totalFee,
  76. transactionId,
  77. resultCode, // 微信支付v2和支付宝支付判断成功的字段
  78. openid,
  79. appId,
  80. tradeState, // 微信支付v3和微信虚拟支付判断支付成功的字段
  81. } = verifyResult;
  82. if (resultCode == "SUCCESS" || tradeState === "SUCCESS") {
  83. let time = Date.now();
  84. let payOrderInfo = await dao.uniPayOrders.updateAndReturn({
  85. whereJson: {
  86. status: 0, // status:0 为必须条件,防止重复推送时的错误
  87. out_trade_no: outTradeNo, // 商户订单号
  88. },
  89. dataJson: {
  90. status: 1, // 设置为已付款
  91. transaction_id: transactionId, // 第三方支付单号
  92. pay_date: time, // 更新支付时间(暂无法准确获取到支付时间,故用通知时间代替支付时间)
  93. notify_date: time, // 更新通知时间
  94. openid,
  95. provider, // 更新provider
  96. provider_pay_type, // 更新provider_pay_type
  97. original_data: httpInfo, // http回调信息,便于丢单时手动触发回调
  98. }
  99. });
  100. //console.log('payOrderInfo: ', payOrderInfo)
  101. if (payOrderInfo) {
  102. // 只有首次推送才执行用户自己的逻辑处理。
  103. // 用户自己的逻辑处理 开始-----------------------------------------------------------
  104. let userOrderSuccess = false;
  105. let orderPaySuccess;
  106. try {
  107. // 加载自定义异步回调函数
  108. orderPaySuccess = require(`../notify/${payOrderInfo.type}`);
  109. } catch (err) {
  110. console.log(err);
  111. }
  112. if (typeof orderPaySuccess === "function") {
  113. console.log('用户自己的回调逻辑 - 开始执行');
  114. userOrderSuccess = await orderPaySuccess({
  115. verifyResult,
  116. data: payOrderInfo,
  117. clientInfo,
  118. cloudInfo
  119. });
  120. console.log('用户自己的回调逻辑 - 执行完成');
  121. }
  122. console.log('userOrderSuccess', userOrderSuccess);
  123. // 用户自己的逻辑处理 结束-----------------------------------------------------------
  124. await dao.uniPayOrders.updateAndReturn({
  125. whereJson: {
  126. status: 1,
  127. out_trade_no: outTradeNo,
  128. },
  129. dataJson: {
  130. user_order_success: userOrderSuccess,
  131. }
  132. });
  133. } else {
  134. console.log('---------!注意:本次回调非首次回调,已被插件拦截,插件不会执行你的回调函数!---------');
  135. console.log('---------!注意:本次回调非首次回调,已被插件拦截,插件不会执行你的回调函数!---------');
  136. console.log('---------!注意:本次回调非首次回调,已被插件拦截,插件不会执行你的回调函数!---------');
  137. console.log('verifyResult:', verifyResult);
  138. }
  139. } else {
  140. console.log('verifyResult:', verifyResult);
  141. }
  142. return libs.common.returnNotifySUCCESS({ provider, provider_pay_type });
  143. }
  144. /**
  145. * 微信虚拟支付异步通知
  146. */
  147. async wxpayVirtualNotify(data = {}) {
  148. return this.paymentNotify({
  149. ...data,
  150. isWxpayVirtual: true
  151. });
  152. }
  153. /**
  154. * 统一支付 - 创建支付订单
  155. */
  156. async createOrder(data = {}) {
  157. let {
  158. provider, // 支付供应商
  159. total_fee, // 支付金额
  160. user_id, // 用户user_id(统计需要)
  161. openid, // 用户openid
  162. order_no, // 订单号
  163. out_trade_no, // 支付插件订单号
  164. description, // 订单描述
  165. type, // 回调类型
  166. qr_code, // 是否强制使用扫码支付
  167. custom, // 自定义参数(不会发送给第三方支付服务器)
  168. other, // 其他请求参数(会发送给第三方支付服务器)
  169. clientInfo, // 客户端信息
  170. cloudInfo, // 云端信息
  171. wxpay_virtual, // 仅用于微信虚拟支付
  172. apple_virtual, // 仅用于苹果虚拟支付
  173. } = data;
  174. let subject = description;
  175. let body = description;
  176. if (!out_trade_no) out_trade_no = libs.common.createOrderNo();
  177. if (!order_no || typeof order_no !== "string") {
  178. throw { errCode: ERROR[51003] };
  179. }
  180. if (!type || typeof type !== "string") {
  181. throw { errCode: ERROR[51004] };
  182. }
  183. if (provider === "wxpay-virtual") {
  184. if (typeof wxpay_virtual !== "object") {
  185. throw { errCode: ERROR[51011] };
  186. }
  187. if (typeof wxpay_virtual.buy_quantity !== "number" || wxpay_virtual.buy_quantity <= 0) {
  188. throw { errCode: ERROR[51012] };
  189. }
  190. } else if (provider === "appleiap") {
  191. if (typeof apple_virtual !== "object") {
  192. throw { errCode: ERROR[51013] };
  193. }
  194. if (typeof apple_virtual.buy_quantity !== "number" || apple_virtual.buy_quantity <= 0) {
  195. throw { errCode: ERROR[51012] };
  196. }
  197. } else {
  198. if (typeof total_fee !== "number" || total_fee <= 0 || total_fee % 1 !== 0) {
  199. throw { errCode: ERROR[51005] };
  200. }
  201. }
  202. if (!description || typeof description !== "string") {
  203. throw { errCode: ERROR[51006] };
  204. }
  205. if (!provider || typeof provider !== "string") {
  206. throw { errCode: ERROR[51007] };
  207. }
  208. if (!clientInfo) {
  209. throw { errCode: ERROR[51008] };
  210. }
  211. if (!cloudInfo) {
  212. throw { errCode: ERROR[51009] };
  213. }
  214. let res = { errCode: 0, errMsg: 'ok', order_no, out_trade_no, provider };
  215. let {
  216. clientIP: client_ip,
  217. userAgent: ua,
  218. appId: appid,
  219. deviceId: device_id,
  220. platform
  221. } = clientInfo;
  222. let {
  223. spaceId, // 服务空间ID
  224. } = cloudInfo;
  225. let {
  226. notifyUrl = {}
  227. } = config;
  228. // 业务逻辑开始-----------------------------------------------------------
  229. // 以下代码是为了兼容公测版迁移到正式版的空间
  230. let notifySpaceId = spaceId;
  231. if (!notifyUrl[notifySpaceId]) {
  232. if (notifySpaceId.indexOf("mp-") === 0) {
  233. notifySpaceId = notifySpaceId.substring(3);
  234. } else {
  235. notifySpaceId = `mp-${notifySpaceId}`
  236. }
  237. }
  238. // 以上代码是为了兼容公测版迁移到正式版的空间
  239. let currentNotifyUrl = notifyUrl[notifySpaceId] || notifyUrl["default"]; // 异步回调地址
  240. if (!currentNotifyUrl || currentNotifyUrl.indexOf("http") !== 0) {
  241. throw { errCode: ERROR[52002] };
  242. }
  243. platform = libs.common.getPlatform(platform);
  244. // 如果需要二维码支付模式,则清空下openid
  245. if (qr_code) {
  246. openid = undefined;
  247. res.qr_code = qr_code;
  248. }
  249. // 获取并自动匹配支付供应商的支付类型
  250. let provider_pay_type = libs.common.getProviderPayType({
  251. platform,
  252. provider,
  253. ua,
  254. qr_code
  255. });
  256. res.provider_pay_type = provider_pay_type;
  257. // 拼接实际异步回调地址
  258. let finalNotifyUrl = `${currentNotifyUrl}${notifyPath}${provider}-${provider_pay_type}`;
  259. // 获取uniPay交易类型
  260. let tradeType = libs.common.getTradeType({ provider, provider_pay_type });
  261. let uniPayConifg = await this.getUniPayConfig({ provider, provider_pay_type });
  262. // 初始化uniPayInstance
  263. let uniPayInstance = await this.initUniPayInstance({ provider, provider_pay_type });
  264. // 获取支付信息
  265. let getOrderInfoParam = {
  266. openid: openid,
  267. subject: subject,
  268. body: body,
  269. outTradeNo: out_trade_no,
  270. totalFee: total_fee,
  271. notifyUrl: finalNotifyUrl,
  272. tradeType: tradeType
  273. };
  274. if (provider === "wxpay" && provider_pay_type === "mweb") {
  275. getOrderInfoParam.spbillCreateIp = client_ip;
  276. if (uniPayConifg.version !== 3) {
  277. // v2版本
  278. getOrderInfoParam.sceneInfo = uniPayConifg.sceneInfo;
  279. } else {
  280. // v3版本特殊处理
  281. getOrderInfoParam.sceneInfo = JSON.parse(JSON.stringify(uniPayConifg.sceneInfo));
  282. if (getOrderInfoParam.sceneInfo.h5_info.wap_url) {
  283. getOrderInfoParam.sceneInfo.h5_info.app_url = getOrderInfoParam.sceneInfo.h5_info.wap_url;
  284. delete getOrderInfoParam.sceneInfo.h5_info.wap_url;
  285. }
  286. if (getOrderInfoParam.sceneInfo.h5_info.wap_name) {
  287. getOrderInfoParam.sceneInfo.h5_info.app_name = getOrderInfoParam.sceneInfo.h5_info.wap_name;
  288. delete getOrderInfoParam.sceneInfo.h5_info.wap_name;
  289. }
  290. }
  291. }
  292. let expand_data;
  293. try {
  294. // 如果是苹果内购,不需要执行uniPayInstance.getOrderInfo等操作
  295. if (provider !== "appleiap") {
  296. // 第三方支付服务器返回的订单信息
  297. let orderInfo;
  298. if (other) {
  299. // other 内的键名转驼峰
  300. other = libs.common.snake2camelJson(other);
  301. getOrderInfoParam = Object.assign(getOrderInfoParam, other);
  302. }
  303. getOrderInfoParam = JSON.parse(JSON.stringify(getOrderInfoParam)); // 此为去除undefined的参数
  304. if (provider === "wxpay-virtual") {
  305. // 微信虚拟支付扩展数据
  306. expand_data = {
  307. mode: wxpay_virtual.mode, // short_series_coin 代币充值; short_series_goods 道具直购
  308. buy_quantity: wxpay_virtual.buy_quantity,
  309. rate: uniPayConifg.rate || 100,
  310. sandbox: uniPayConifg.sandbox,
  311. };
  312. if (wxpay_virtual.mode === "short_series_goods") {
  313. expand_data.product_id = wxpay_virtual.product_id;
  314. expand_data.goods_price = wxpay_virtual.goods_price;
  315. }
  316. // 获取用户的sessionKey
  317. let { session_key } = await dao.opendbOpenData.getSessionKey({
  318. appId: uniPayConifg.appId,
  319. platform: "weixin-mp",
  320. openid: openid
  321. });
  322. getOrderInfoParam.sessionKey = session_key;
  323. getOrderInfoParam.mode = expand_data.mode;
  324. getOrderInfoParam.buyQuantity = expand_data.buy_quantity;
  325. getOrderInfoParam.productId = expand_data.product_id;
  326. getOrderInfoParam.goodsPrice = expand_data.goods_price;
  327. if (getOrderInfoParam.mode === "short_series_coin") {
  328. // 计算支付金额
  329. total_fee = expand_data.buy_quantity / (expand_data.rate || 100) * 100;
  330. } else if (getOrderInfoParam.mode === "short_series_goods") {
  331. // 计算支付金额
  332. total_fee = expand_data.buy_quantity * expand_data.goods_price;
  333. }
  334. }
  335. orderInfo = await uniPayInstance.getOrderInfo(getOrderInfoParam);
  336. if (qr_code && orderInfo.codeUrl) {
  337. res.qr_code_image = await libs.qrcode.toDataURL(orderInfo.codeUrl, {
  338. type: "image/png",
  339. width: 200,
  340. margin: 1,
  341. scale: 1,
  342. color: {
  343. dark: "#000000",
  344. light: "#ffffff",
  345. },
  346. errorCorrectionLevel: "Q",
  347. quality: 1
  348. });
  349. }
  350. // 支付宝支付参数特殊处理
  351. if (provider === "alipay") {
  352. if (typeof orderInfo === "object" && orderInfo.code && orderInfo.code !== "10000") {
  353. res.errCode = orderInfo.code;
  354. res.errMsg = orderInfo.subMsg;
  355. }
  356. }
  357. res.order = orderInfo;
  358. }
  359. } catch (err) {
  360. let errMsg = err.errorMessage || err.message;
  361. console.error("data: ", data);
  362. console.error("getOrderInfoParam: ", getOrderInfoParam);
  363. console.error("err: ", err);
  364. console.error("errMsg: ", errMsg);
  365. throw { errCode: ERROR[53001], errMsg };
  366. }
  367. // 尝试获取下订单信息
  368. let payOrderInfo = await dao.uniPayOrders.find({
  369. order_no,
  370. out_trade_no
  371. });
  372. let create_date = Date.now();
  373. // 如果订单不存在,则添加
  374. if (!payOrderInfo) {
  375. // 添加数据库(数据库的out_trade_no字段需设置为唯一索引)
  376. let stat_platform = clientInfo.platform;
  377. if (stat_platform === "app") {
  378. stat_platform = clientInfo.os;
  379. }
  380. let nickname;
  381. if (user_id) {
  382. // 获取nickname(冗余昵称)
  383. let userInfo = await dao.uniIdUsers.findById(user_id);
  384. if (userInfo) nickname = userInfo.nickname;
  385. }
  386. let appleiap_account_token;
  387. if (provider === "appleiap") {
  388. appleiap_account_token = libs.crypto.generateUUID();
  389. res.appleiap_account_token = appleiap_account_token;
  390. }
  391. await dao.uniPayOrders.add({
  392. provider,
  393. provider_pay_type,
  394. uni_platform: platform,
  395. status: 0,
  396. type,
  397. order_no,
  398. out_trade_no,
  399. user_id,
  400. nickname,
  401. device_id,
  402. client_ip,
  403. openid,
  404. description,
  405. total_fee,
  406. refund_fee: 0,
  407. refund_count: 0,
  408. provider_appid: uniPayConifg.appId,
  409. appid,
  410. custom,
  411. create_date,
  412. expand_data,
  413. appleiap_account_token, // 苹果虚拟支付专用字段
  414. stat_data: {
  415. platform: stat_platform,
  416. app_version: clientInfo.appVersion,
  417. app_version_code: clientInfo.appVersionCode,
  418. app_wgt_version: clientInfo.appWgtVersion,
  419. os: clientInfo.os,
  420. ua: clientInfo.ua,
  421. channel: clientInfo.channel ? clientInfo.channel : String(clientInfo.scene),
  422. scene: clientInfo.scene
  423. }
  424. });
  425. } else {
  426. // 如果订单已经存在,则修改下支付方式(用户可能先点微信支付,未付款,又点了支付宝支付)
  427. await dao.uniPayOrders.updateById(payOrderInfo._id, {
  428. provider,
  429. provider_pay_type,
  430. });
  431. }
  432. // 自动删除3天前的订单(未付款订单)
  433. // await dao.uniPayOrders.deleteExpPayOrders();
  434. // 业务逻辑结束-----------------------------------------------------------
  435. return res;
  436. }
  437. /**
  438. * 统一支付结果查询
  439. * @description 根据商户订单号或者平台订单号查询订单信息,主要用于未接收到支付通知时可以使用此接口进行支付结果验证
  440. */
  441. async getOrder(data = {}) {
  442. let {
  443. out_trade_no, // 支付插件订单号
  444. transaction_id, // 支付平台的交易单号
  445. await_notify = false, // 是否需要等待异步通知执行完成才返回前端支付结果
  446. } = data;
  447. let res = { errCode: 0, errMsg: 'ok' };
  448. // 业务逻辑开始-----------------------------------------------------------
  449. if (!out_trade_no && !transaction_id) {
  450. throw { errCode: ERROR[51010] };
  451. }
  452. let payOrderInfo;
  453. if (transaction_id) {
  454. payOrderInfo = await dao.uniPayOrders.find({
  455. transaction_id
  456. });
  457. } else if (out_trade_no) {
  458. payOrderInfo = await dao.uniPayOrders.find({
  459. out_trade_no
  460. });
  461. }
  462. if (!payOrderInfo) {
  463. throw { errCode: ERROR[52001] };
  464. }
  465. // 初始化uniPayInstance
  466. let uniPayInstance = await this.initUniPayInstance(payOrderInfo);
  467. let orderQueryJson = {};
  468. if (out_trade_no) {
  469. orderQueryJson.outTradeNo = out_trade_no;
  470. } else {
  471. orderQueryJson.transactionId = transaction_id;
  472. }
  473. if (payOrderInfo.provider === "wxpay-virtual") {
  474. orderQueryJson.openid = payOrderInfo.openid;
  475. }
  476. let queryRes;
  477. if (typeof uniPayInstance.orderQuery === "function") {
  478. queryRes = await uniPayInstance.orderQuery(orderQueryJson);
  479. console.log('queryRes: ', queryRes)
  480. } else {
  481. // 无uniPayInstance.orderQuery函数时的兼容处理
  482. if ([1, 2].indexOf(payOrderInfo.status) > -1) {
  483. queryRes = {
  484. tradeState: "SUCCESS",
  485. tradeStateDesc: "订单已支付"
  486. };
  487. } else if ([3].indexOf(payOrderInfo.status) > -1) {
  488. queryRes = {
  489. tradeState: "REFUNDED",
  490. tradeStateDesc: "订单已退款"
  491. };
  492. } else {
  493. queryRes = {
  494. tradeState: "NOPAY",
  495. tradeStateDesc: "订单未支付"
  496. };
  497. }
  498. }
  499. if (queryRes.tradeState === 'SUCCESS' || queryRes.tradeState === 'FINISHED') {
  500. if (typeof payOrderInfo.user_order_success == "undefined" && await_notify) {
  501. let whileTime = 0; // 当前循环已执行的时间(毫秒)
  502. let whileInterval = 500; // 每次循环间隔时间(毫秒)
  503. let maxTime = 20000; // 循环执行时间超过此值则退出循环(毫秒)
  504. while (typeof payOrderInfo.user_order_success == "undefined" && whileTime <= maxTime) {
  505. await libs.common.sleep(whileInterval);
  506. whileTime += whileInterval;
  507. payOrderInfo = await dao.uniPayOrders.find({
  508. out_trade_no
  509. });
  510. }
  511. }
  512. res = {
  513. errCode: 0,
  514. errMsg: "ok",
  515. has_paid: true, // 标记用户是否已付款成功(此参数只能表示用户确实付款了,但系统的异步回调逻辑可能还未执行完成)
  516. out_trade_no, // 支付插件订单号
  517. transaction_id, // 支付平台订单号
  518. status: payOrderInfo.status, // 标记当前支付订单状态 -1:已关闭 0:未支付 1:已支付 2:已部分退款 3:已全额退款
  519. user_order_success: payOrderInfo.user_order_success, // 用户异步通知逻辑是否全部执行完成,且无异常(建议前端通过此参数是否为true来判断是否支付成功)
  520. pay_order: payOrderInfo,
  521. }
  522. } else {
  523. let errMsg = queryRes.tradeStateDesc || "未支付或已退款";
  524. if (errMsg.indexOf("订单发生过退款") > -1) {
  525. errMsg = "订单已退款";
  526. }
  527. res = {
  528. errCode: -1,
  529. errMsg: errMsg,
  530. has_paid: false,
  531. out_trade_no, // 支付插件订单号
  532. transaction_id, // 支付平台订单号
  533. }
  534. }
  535. // 业务逻辑结束-----------------------------------------------------------
  536. return res;
  537. }
  538. /**
  539. * 统一退款
  540. * @description 当交易发生之后一段时间内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付款退还给买家。
  541. */
  542. async refund(data = {}) {
  543. let {
  544. out_trade_no, // 插件支付单号
  545. out_refund_no, // 退款单号(若不传,则自动生成)
  546. refund_desc = "用户申请退款",
  547. refund_fee: myRefundFee,
  548. refund_fee_type = "CNY"
  549. } = data;
  550. let res = { errCode: 0, errMsg: 'ok' };
  551. // 业务逻辑开始-----------------------------------------------------------
  552. if (!out_trade_no) {
  553. throw { errCode: ERROR[51001] };
  554. }
  555. let payOrderInfo = await dao.uniPayOrders.find({
  556. out_trade_no
  557. });
  558. if (!payOrderInfo) {
  559. throw { errCode: ERROR[52001] };
  560. }
  561. let refund_count = payOrderInfo.refund_count || 0;
  562. refund_count++;
  563. // 生成退款订单号
  564. let outRefundNo = out_refund_no ? out_refund_no : `${out_trade_no}-${refund_count}`;
  565. // 订单总金额
  566. let totalFee = payOrderInfo.total_fee;
  567. // 退款总金额
  568. let refundFee = myRefundFee || totalFee;
  569. let provider = payOrderInfo.provider;
  570. let uniPayConifg = await this.getUniPayConfig(payOrderInfo);
  571. let uniPayInstance = await this.initUniPayInstance(payOrderInfo);
  572. let refundParams = {
  573. outTradeNo: out_trade_no,
  574. outRefundNo,
  575. totalFee,
  576. refundFee,
  577. refundDesc: refund_desc,
  578. refundFeeType: refund_fee_type
  579. };
  580. if (payOrderInfo.provider === "wxpay-virtual") {
  581. refundParams.openid = payOrderInfo.openid;
  582. refundParams.refundReason = "3"; // 0-暂无描述 1-产品问题,影响使用或效果不佳 2-售后问题,无法满足需求 3-意愿问题,用户主动退款 4-价格问题 5-其他原因
  583. refundParams.reqFrom = "2"; // 当前只支持"1"-人工客服退款,即用户电话给客服,由客服发起退款流程 "2"-用户自己发起退款流程 "3"-其他
  584. // 查询当前可退款金额
  585. refundParams.leftFee = totalFee - (payOrderInfo.refund_fee || 0);
  586. // 实时查询当前可退款金额(此处注释可省一次请求)
  587. // const orderQueryRes = await uniPayInstance.orderQuery({
  588. // openid: payOrderInfo.openid,
  589. // outTradeNo: payOrderInfo.out_trade_no
  590. // });
  591. // refundParams.leftFee = orderQueryRes.leftFee;
  592. }
  593. console.log(`---- ${out_trade_no} -- ${outRefundNo} -- ${totalFee/100} -- ${refundFee/100}`)
  594. // 退款操作
  595. try {
  596. res.result = await uniPayInstance.refund(refundParams);
  597. } catch (err) {
  598. console.error(err);
  599. let errMsg = err.message;
  600. if (errMsg) {
  601. if (errMsg.indexOf("verify failure") > -1) {
  602. throw { errCode: ERROR[53005] };
  603. }
  604. if (errMsg.indexOf("header too long") > -1) {
  605. throw { errCode: ERROR[53005] };
  606. }
  607. }
  608. return { errCode: -1, errMsg: errMsg, err }
  609. }
  610. if (res.result.refundFee) {
  611. res.errCode = 0;
  612. res.errMsg = "ok";
  613. // 修改数据库
  614. try {
  615. let time = Date.now();
  616. // 修改订单状态
  617. payOrderInfo = await dao.uniPayOrders.updateAndReturn({
  618. whereJson: {
  619. _id: payOrderInfo._id,
  620. "refund_list.out_refund_no": _.neq(outRefundNo)
  621. },
  622. dataJson: {
  623. status: 2,
  624. refund_fee: _.inc(refundFee),
  625. refund_count: refund_count,
  626. refund_date: time, // 更新最近一次退款时间
  627. // 记录每次的退款详情
  628. refund_list: _.unshift({
  629. refund_date: time,
  630. refund_fee: refundFee,
  631. out_refund_no: outRefundNo,
  632. refund_desc
  633. })
  634. }
  635. });
  636. if (payOrderInfo && payOrderInfo.refund_fee >= payOrderInfo.total_fee) {
  637. // 修改订单状态为已全额退款
  638. await dao.uniPayOrders.updateById(payOrderInfo._id, {
  639. status: 3,
  640. refund_fee: payOrderInfo.total_fee,
  641. });
  642. }
  643. } catch (err) {
  644. console.error(err);
  645. }
  646. } else {
  647. console.log('res.result: ', res.result);
  648. throw { errCode: ERROR[53002] };
  649. }
  650. // 业务逻辑结束-----------------------------------------------------------
  651. return res;
  652. }
  653. /**
  654. * 查询退款(查询退款情况)
  655. * @description 提交退款申请后,通过调用该接口查询退款状态。
  656. */
  657. async getRefund(data = {}) {
  658. let {
  659. out_trade_no, // 插件支付单号
  660. } = data;
  661. if (!out_trade_no) {
  662. throw { errCode: ERROR[51001] };
  663. }
  664. let payOrderInfo = await dao.uniPayOrders.find({
  665. out_trade_no
  666. });
  667. if (!payOrderInfo) {
  668. throw { errCode: ERROR[52001] };
  669. }
  670. let provider = payOrderInfo.provider;
  671. let uniPayInstance = await this.initUniPayInstance(payOrderInfo);
  672. let queryRes;
  673. try {
  674. let refundQueryJson = {
  675. outTradeNo: out_trade_no,
  676. outRefundNo: payOrderInfo.refund_list[0].out_refund_no
  677. };
  678. if (provider === "wxpay-virtual") {
  679. refundQueryJson.openid = payOrderInfo.openid;
  680. }
  681. queryRes = await uniPayInstance.refundQuery(refundQueryJson);
  682. } catch (err) {
  683. throw { errCode: ERROR[53003], errMsg: err.errMsg };
  684. }
  685. let orderInfo = {
  686. total_fee: payOrderInfo.total_fee,
  687. refund_fee: payOrderInfo.refund_fee,
  688. refund_count: payOrderInfo.refund_count,
  689. refund_list: payOrderInfo.refund_list,
  690. provider: payOrderInfo.provider,
  691. provider_pay_type: payOrderInfo.provider_pay_type,
  692. status: payOrderInfo.status,
  693. type: payOrderInfo.type,
  694. out_trade_no: payOrderInfo.out_trade_no,
  695. transaction_id: payOrderInfo.transaction_id,
  696. };
  697. if (queryRes.refundFee > 0) {
  698. let msg = "ok";
  699. if (payOrderInfo.refund_list && payOrderInfo.refund_list.length > 0) {
  700. msg = `合计退款 ${payOrderInfo.refund_fee/100}\r\n`;
  701. for (let i in payOrderInfo.refund_list) {
  702. let item = payOrderInfo.refund_list[i];
  703. let index = Number(i) + 1;
  704. let timeStr = libs.common.timeFormat(item.refund_date, "yyyy-MM-dd hh:mm:ss");
  705. msg += `${index}、 ${timeStr} \r\n退款 ${item.refund_fee/100} \r\n`;
  706. }
  707. }
  708. return {
  709. errCode: 0,
  710. errMsg: msg,
  711. pay_order: orderInfo,
  712. result: queryRes
  713. }
  714. } else {
  715. throw { errCode: ERROR[53003] };
  716. }
  717. }
  718. /**
  719. * 关闭订单
  720. * @description 用于交易创建后,用户在一定时间内未进行支付,可调用该接口直接将未付款的交易进行关闭,避免重复支付。
  721. * 注意
  722. * 微信支付:订单生成后不能马上调用关单接口,最短调用时间间隔为 5 分钟。
  723. * 微信虚拟支付:不支持关闭订单
  724. */
  725. async closeOrder(data = {}) {
  726. let {
  727. out_trade_no, // 插件支付单号
  728. } = data;
  729. if (!out_trade_no) {
  730. throw { errCode: ERROR[51001] };
  731. }
  732. let payOrderInfo = await dao.uniPayOrders.find({
  733. out_trade_no
  734. });
  735. if (!payOrderInfo) {
  736. throw { errCode: ERROR[52001] };
  737. }
  738. let { provider } = payOrderInfo;
  739. let uniPayInstance = await this.initUniPayInstance(payOrderInfo);
  740. let closeOrderRes = await uniPayInstance.closeOrder({
  741. outTradeNo: out_trade_no
  742. });
  743. let wxpayResult = (provider === "wxpay" && closeOrderRes.resultCode === "SUCCESS");
  744. let alipayResult = (provider === "alipay" && closeOrderRes.code === "10000");
  745. if (wxpayResult || alipayResult) {
  746. // 修改订单状态为已取消
  747. await dao.uniPayOrders.update({
  748. whereJson: {
  749. _id: payOrderInfo._id,
  750. status: 0
  751. },
  752. dataJson: {
  753. status: -1,
  754. cancel_date: Date.now()
  755. }
  756. });
  757. return {
  758. errCode: 0,
  759. errMsg: "订单关闭成功",
  760. result: closeOrderRes
  761. }
  762. } else {
  763. throw { errCode: ERROR[53004] };
  764. }
  765. }
  766. /**
  767. * 根据code获取openid
  768. */
  769. async getOpenid(data = {}) {
  770. let {
  771. provider, // 支付供应商
  772. code, // 用户登录获取的code
  773. clientInfo, // 客户端环境
  774. } = data;
  775. if (!code) {
  776. throw { errCode: ERROR[51002] };
  777. }
  778. let { platform, ua } = clientInfo;
  779. // 获取并自动匹配支付供应商的支付类型
  780. let provider_pay_type = libs.common.getProviderPayType({
  781. provider,
  782. platform,
  783. ua
  784. });
  785. let needCacheSessionKey = false;
  786. let uniPayConifg = await this.getUniPayConfig({ provider, provider_pay_type });
  787. if (provider === "wxpay") {
  788. try {
  789. // 如果配置了微信虚拟支付,则使用微信虚拟支付的配置作为微信获取openid的配置
  790. let wxpayVirtualPayConifg = await this.getUniPayConfig({ provider: "wxpay-virtual", provider_pay_type: "mp" });
  791. if (wxpayVirtualPayConifg && wxpayVirtualPayConifg.appId && wxpayVirtualPayConifg.secret) {
  792. uniPayConifg = wxpayVirtualPayConifg;
  793. needCacheSessionKey = true;
  794. }
  795. } catch (err) {}
  796. let res = await libs.wxpay.getOpenid({
  797. config: uniPayConifg,
  798. code,
  799. provider_pay_type,
  800. });
  801. if (needCacheSessionKey) {
  802. // 将session_key保存到缓存表中
  803. let cacheKey = {
  804. appId: uniPayConifg.appId,
  805. platform: "weixin-mp",
  806. openid: res.openid
  807. }
  808. let session_key = res.session_key;
  809. delete res.session_key;
  810. await dao.opendbOpenData.setSessionKey(cacheKey, { session_key }, 30 * 24 * 60 * 60);
  811. }
  812. return res;
  813. } else if (provider === "alipay") {
  814. return await libs.alipay.getOpenid({
  815. config: uniPayConifg,
  816. code,
  817. });
  818. }
  819. }
  820. /**
  821. * 获取支持的支付方式
  822. * let payTypes = await service.pay.getPayProviderFromCloud();
  823. */
  824. async getPayProviderFromCloud() {
  825. let wxpay = config.wxpay && config.wxpay.enable ? true : false;
  826. let alipay = config.alipay && config.alipay.enable ? true : false;
  827. let provider = [];
  828. if (wxpay) provider.push("wxpay");
  829. if (alipay) provider.push("alipay");
  830. return {
  831. errCode: 0,
  832. errMsg: "ok",
  833. wxpay,
  834. alipay,
  835. provider
  836. };
  837. }
  838. /**
  839. * 验证iosIap苹果内购支付凭据
  840. * let payTypes = await service.pay.verifyReceiptFromAppleiap();
  841. */
  842. async verifyReceiptFromAppleiap(data) {
  843. let {
  844. out_trade_no,
  845. appleiap_account_token,
  846. transaction_receipt,
  847. transaction_identifier,
  848. clientInfo,
  849. } = data;
  850. if (!out_trade_no) {
  851. if (!appleiap_account_token) {
  852. return {
  853. errCode: 0,
  854. errMsg: "Invalid out_trade_no"
  855. }
  856. }
  857. appleiap_account_token = appleiap_account_token.toLowerCase(); // 转小写
  858. let payOrderInfo = await dao.uniPayOrders.find({
  859. provider: "appleiap",
  860. appleiap_account_token
  861. });
  862. if (!payOrderInfo || !payOrderInfo.out_trade_no) {
  863. return {
  864. errCode: 0,
  865. errMsg: "Invalid out_trade_no"
  866. }
  867. }
  868. out_trade_no = payOrderInfo.out_trade_no;
  869. }
  870. let payOrderInfo = await dao.uniPayOrders.find({
  871. out_trade_no,
  872. });
  873. if (!payOrderInfo) {
  874. throw { errCode: ERROR[52001] };
  875. }
  876. const verifyReceipt = async (uniPayConifg) => {
  877. const jwt = libs.jsonwebtoken;
  878. const fs = require('fs');
  879. const privateKey = fs.readFileSync(uniPayConifg.appCertPath, 'utf8');
  880. const header = {
  881. alg: 'ES256',
  882. kid: uniPayConifg.appId, // 替换为您的密钥ID
  883. typ: "JWT"
  884. };
  885. const nowTime = Date.now();
  886. const bundleId = uniPayConifg.sandbox ? uniPayConifg.devBundleId || uniPayConifg.bundleId : uniPayConifg.bundleId;
  887. const payload = {
  888. iss: uniPayConifg.issuerId, // 替换为您的团队ID
  889. iat: Math.floor(nowTime / 1000), // 当前时间戳
  890. exp: Math.floor(nowTime / 1000) + 3600, // 当前时间戳加1小时
  891. aud: 'appstoreconnect-v1',
  892. bid: bundleId
  893. };
  894. const iapToken = jwt.sign(payload, privateKey, {
  895. algorithm: 'ES256',
  896. header: header
  897. });
  898. const serviceUrl = uniPayConifg.sandbox ? "https://api.storekit-sandbox.itunes.apple.com" : "https://api.appstoreconnect.apple.com";
  899. const url = `${serviceUrl}/inApps/v1/transactions/${transaction_identifier}`;
  900. let requestRes;
  901. // 如果请求苹果服务器失败,则重试5次
  902. for (let i = 0; i <= 5; i++) {
  903. try {
  904. requestRes = await uniCloud.request({
  905. method: "GET",
  906. header: {
  907. 'Authorization': `Bearer ${iapToken}`,
  908. 'Content-Type': 'application/json'
  909. },
  910. url
  911. });
  912. break;
  913. } catch (err) {
  914. // console.log('errCode: ', err.code || err.errCode, 'errMsg: ', err.message || err.errMsg)
  915. }
  916. }
  917. if (requestRes.statusCode !== 200) {
  918. return {};
  919. }
  920. const signedInfoTokenArr = requestRes.data.signedTransactionInfo.split('.');
  921. const signedInfoString = Buffer.from(signedInfoTokenArr[1], 'base64').toString('utf8');
  922. const verifyReceiptRes = JSON.parse(signedInfoString);
  923. const appAccountToken = verifyReceiptRes.appAccountToken.toLowerCase();
  924. verifyReceiptRes.tradeState = verifyReceiptRes.inAppOwnershipType === "PURCHASED" && payOrderInfo.appleiap_account_token === appAccountToken ? "SUCCESS" : "fail";
  925. return verifyReceiptRes;
  926. };
  927. let uniPayConifg = await this.getUniPayConfig({ provider: "appleiap", provider_pay_type: "app" });
  928. let verifyReceiptRes = await verifyReceipt(uniPayConifg);
  929. let userOrderSuccess = false;
  930. let pay_date;
  931. if (verifyReceiptRes.tradeState !== "SUCCESS") {
  932. // 尝试使用相反的环境再次验证
  933. console.log('尝试使用相反的环境再次验证: ');
  934. verifyReceiptRes = await verifyReceipt({
  935. ...uniPayConifg,
  936. sandbox: !uniPayConifg.sandbox
  937. });
  938. if (verifyReceiptRes.tradeState !== "SUCCESS") {
  939. // 如果还是不成功,则校验不通过
  940. throw { errCode: ERROR[54002] };
  941. }
  942. }
  943. //console.log('verifyReceiptRes: ', verifyReceiptRes)
  944. let isSubscribe = false;
  945. if (["Auto-Renewable Subscription"].indexOf(verifyReceiptRes.type) > -1) {
  946. isSubscribe = true; // 标记为自动订阅订单
  947. }
  948. // 支付成功
  949. pay_date = Number(verifyReceiptRes.purchaseDate);
  950. let quantity = verifyReceiptRes.quantity; // 购买数量
  951. let product_id = verifyReceiptRes.productId; // 对应的内购产品id
  952. let transaction_id = verifyReceiptRes.transactionId; // 本次交易id
  953. let original_transaction_id = verifyReceiptRes.originalTransactionId; // 原始交易id
  954. if ((Date.now() - 1000 * 3600 * 72) > pay_date && !isSubscribe) {
  955. // 非自动订阅订单,若超72小时,不做处理,通知前端直接关闭订单。
  956. return {
  957. errCode: 0,
  958. errMsg: "ok"
  959. };
  960. }
  961. if (isSubscribe && original_transaction_id !== transaction_id) {
  962. let findOrderInfo = await dao.uniPayOrders.find({
  963. appleiap_account_token: payOrderInfo.appleiap_account_token,
  964. user_order_success: _.exists(true)
  965. });
  966. if (findOrderInfo) {
  967. // 自动订阅产品自动续期时需要创建新的支付订单
  968. let quantity = verifyReceiptRes.quantity;
  969. let goods_price = parseFloat((verifyReceiptRes.price / 1000).toFixed(2));
  970. let total_fee = parseFloat((goods_price * 100 * quantity).toFixed(2));
  971. let description = "[自动续期]" + payOrderInfo.description.replace(/\[自动续期\]/g, '');
  972. // 添加数据库(数据库的out_trade_no字段需设置为唯一索引)
  973. let stat_platform = clientInfo.platform;
  974. if (stat_platform === "app") {
  975. stat_platform = clientInfo.os;
  976. }
  977. // 创建新的支付订单
  978. let addId = await dao.uniPayOrders.add({
  979. provider: payOrderInfo.provider,
  980. provider_pay_type: payOrderInfo.provider_pay_type,
  981. uni_platform: clientInfo.platform,
  982. status: 0,
  983. type: payOrderInfo.type,
  984. order_no: payOrderInfo.order_no,
  985. out_trade_no: transaction_id,
  986. user_id: payOrderInfo.user_id,
  987. nickname: payOrderInfo.nickname,
  988. device_id: clientInfo.deviceId,
  989. client_ip: clientInfo.client_ip,
  990. openid: payOrderInfo.openid,
  991. description,
  992. total_fee,
  993. refund_fee: 0,
  994. refund_count: 0,
  995. provider_appid: uniPayConifg.appId,
  996. appid: clientInfo.appId,
  997. custom: payOrderInfo.custom,
  998. create_date: Date.now(),
  999. expand_data: payOrderInfo.expand_data,
  1000. appleiap_account_token, // 苹果虚拟支付专用字段
  1001. stat_data: {
  1002. platform: stat_platform,
  1003. app_version: clientInfo.appVersion,
  1004. app_version_code: clientInfo.appVersionCode,
  1005. app_wgt_version: clientInfo.appWgtVersion,
  1006. os: clientInfo.os,
  1007. ua: clientInfo.ua,
  1008. channel: clientInfo.channel ? clientInfo.channel : String(clientInfo.scene),
  1009. scene: clientInfo.scene
  1010. }
  1011. });
  1012. payOrderInfo = await dao.uniPayOrders.find({
  1013. _id: addId,
  1014. });
  1015. out_trade_no = transaction_id;
  1016. }
  1017. }
  1018. // 查询该transaction_id是否使用过,如果已使用,则不做处理,通知前端直接关闭订单。
  1019. let findOrderInfo = await dao.uniPayOrders.find({
  1020. transaction_id,
  1021. });
  1022. const repeatReceipt = () => {
  1023. return {
  1024. errCode: 0,
  1025. errMsg: "ok",
  1026. repeat: true, // 代表重复通知了
  1027. };
  1028. };
  1029. if (findOrderInfo) {
  1030. // 不允许重复通知
  1031. return repeatReceipt();
  1032. }
  1033. // 否则,执行用户回调
  1034. // 用户自己的逻辑处理 开始-----------------------------------------------------------
  1035. let orderPaySuccess;
  1036. try {
  1037. // 加载自定义异步回调函数
  1038. orderPaySuccess = require(`../notify/${payOrderInfo.type}`);
  1039. } catch (err) {
  1040. console.log(err);
  1041. }
  1042. if (typeof orderPaySuccess === "function") {
  1043. let newPayOrderInfo = await dao.uniPayOrders.updateAndReturn({
  1044. whereJson: {
  1045. status: 0, // status:0 为必须条件,防止重复推送时的错误
  1046. out_trade_no: out_trade_no, // 商户订单号
  1047. },
  1048. dataJson: {
  1049. status: 1, // 设置为已付款
  1050. transaction_id: transaction_id, // 第三方支付单号
  1051. pay_date: pay_date,
  1052. notify_date: pay_date,
  1053. original_data: verifyReceiptRes
  1054. }
  1055. });
  1056. if (!newPayOrderInfo) {
  1057. // 不允许重复通知
  1058. return repeatReceipt();
  1059. }
  1060. payOrderInfo = newPayOrderInfo;
  1061. console.log('用户自己的回调逻辑 - 开始执行');
  1062. userOrderSuccess = await orderPaySuccess({
  1063. verifyResult: verifyReceiptRes,
  1064. data: payOrderInfo,
  1065. });
  1066. console.log('用户自己的回调逻辑 - 执行完成');
  1067. payOrderInfo = await dao.uniPayOrders.updateAndReturn({
  1068. whereJson: {
  1069. status: 1,
  1070. out_trade_no,
  1071. },
  1072. dataJson: {
  1073. user_order_success: userOrderSuccess,
  1074. }
  1075. });
  1076. } else {
  1077. payOrderInfo = await dao.uniPayOrders.find({
  1078. out_trade_no,
  1079. });
  1080. }
  1081. console.log('userOrderSuccess', userOrderSuccess);
  1082. // 用户自己的逻辑处理 结束-----------------------------------------------------------
  1083. //console.log('verifyReceiptRes: ', verifyReceiptRes);
  1084. return {
  1085. errCode: 0,
  1086. errMsg: "ok",
  1087. has_paid: true, // 标记用户是否已付款成功(此参数只能表示用户确实付款了,但系统的异步回调逻辑可能还未执行完成)
  1088. out_trade_no, // 支付插件订单号
  1089. transaction_id, // 支付平台订单号
  1090. status: payOrderInfo.status, // 标记当前支付订单状态 -1:已关闭 0:未支付 1:已支付 2:已部分退款 3:已全额退款
  1091. user_order_success: payOrderInfo.user_order_success, // 用户异步通知逻辑是否全部执行完成,且无异常(建议前端通过此参数是否为true来判断是否支付成功)
  1092. pay_order: payOrderInfo,
  1093. is_subscribe: isSubscribe
  1094. };
  1095. }
  1096. /**
  1097. * 获取对应支付配置
  1098. * let uniPayConifg = await this.getUniPayConfig({ provider, provider_pay_type });
  1099. */
  1100. async getUniPayConfig(data = {}) {
  1101. let {
  1102. provider,
  1103. provider_pay_type,
  1104. } = data;
  1105. if (config && config[provider] && config[provider][provider_pay_type]) {
  1106. let uniPayConfig = config[provider][provider_pay_type];
  1107. if (!uniPayConfig.appId && provider !== "appleiap") {
  1108. throw new Error(`uni-pay配置${provider}.${provider_pay_type}节点下的appId不能为空`);
  1109. }
  1110. return uniPayConfig;
  1111. } else {
  1112. throw new Error(`${provider}_${provider_pay_type} : 商户支付配置错误`);
  1113. }
  1114. }
  1115. /**
  1116. * 初始化uniPayInstance
  1117. * let uniPayInstance = await service.pay.initUniPayInstance({ provider, provider_pay_type });
  1118. */
  1119. async initUniPayInstance(data = {}) {
  1120. let {
  1121. provider,
  1122. } = data;
  1123. let uniPayConifg = await this.getUniPayConfig(data);
  1124. let uniPayInstance;
  1125. if (provider === "wxpay") {
  1126. // 微信
  1127. if (uniPayConifg.version === 3) {
  1128. try {
  1129. uniPayInstance = uniPay.initWeixinV3(uniPayConifg);
  1130. } catch (err) {
  1131. console.error(err);
  1132. let errMsg = err.message;
  1133. if (errMsg && errMsg.indexOf("invalid base64 body") > -1) {
  1134. throw { errCode: ERROR[53005] };
  1135. }
  1136. throw err;
  1137. }
  1138. } else {
  1139. uniPayInstance = uniPay.initWeixin(uniPayConifg);
  1140. }
  1141. } else if (provider === "alipay") {
  1142. // 支付宝
  1143. uniPayInstance = uniPay.initAlipay(uniPayConifg);
  1144. } else if (provider === "appleiap") {
  1145. // 苹果虚拟支付
  1146. uniPayInstance = uniPay.initAppleIapPayment(uniPayConifg);
  1147. } else if (provider === "wxpay-virtual") {
  1148. // 微信虚拟支付
  1149. // 还需要额外传accessToken
  1150. uniPayConifg.accessToken = await this.getAccessToken(data);
  1151. uniPayInstance = uniPay.initWeixinVirtualPayment(uniPayConifg);
  1152. } else {
  1153. throw new Error(`${provider} : 不支持的支付方式`);
  1154. }
  1155. return uniPayInstance;
  1156. }
  1157. /**
  1158. * 获取accessToken
  1159. * let uniPayInstance = await service.pay.getAccessToken({ provider, provider_pay_type });
  1160. */
  1161. async getAccessToken(data = {}) {
  1162. let uniPayConifg = await this.getUniPayConfig(data);
  1163. let cacheKey = {
  1164. appId: uniPayConifg.appId,
  1165. platform: "weixin-mp"
  1166. }
  1167. let cacheInfo = await dao.opendbOpenData.getAccessToken(cacheKey);
  1168. if (cacheInfo) {
  1169. // 缓存有值
  1170. return cacheInfo.access_token;
  1171. } else {
  1172. // 缓存无值
  1173. let getAccessTokenRes = await libs.wxpay.getAccessToken(uniPayConifg);
  1174. let accessToken = getAccessTokenRes.accessToken;
  1175. // 缓存accessToken
  1176. await dao.opendbOpenData.setAccessToken(cacheKey, {
  1177. access_token: getAccessTokenRes.accessToken,
  1178. }, getAccessTokenRes.expiresIn);
  1179. return accessToken;
  1180. }
  1181. }
  1182. /**
  1183. * 获取sessionKey
  1184. * let sessionKey = await service.pay.getSessionKey({ provider, provider_pay_type, openid });
  1185. */
  1186. async getSessionKey(data = {}) {
  1187. let {
  1188. openid,
  1189. } = data;
  1190. // 获取用户的sessionKey
  1191. let uniPayConifg = await this.getUniPayConfig(data);
  1192. let { session_key } = await dao.opendbOpenData.getSessionKey({
  1193. appId: uniPayConifg.appId,
  1194. platform: "weixin-mp",
  1195. openid
  1196. });
  1197. return session_key;
  1198. }
  1199. /**
  1200. * 请求微信小程序虚拟支付API
  1201. * let res = await service.pay.requestWxpayVirtualApi(data);
  1202. */
  1203. async requestWxpayVirtualApi(options = {}) {
  1204. let {
  1205. method,
  1206. data = {}
  1207. } = options;
  1208. // 微信虚拟支付固定参数
  1209. let provider = "wxpay-virtual";
  1210. let provider_pay_type = "mp";
  1211. // 获得微信小程序虚拟支付实例
  1212. let uniPayInstance = await this.initUniPayInstance({ provider, provider_pay_type });
  1213. // 调用微信小程序虚拟支付云端API
  1214. if (["currencyPay"].indexOf(method) > -1) {
  1215. if (!data.sessionKey) {
  1216. data.sessionKey = await this.getSessionKey({ ...data, provider, provider_pay_type });
  1217. }
  1218. }
  1219. let res = await uniPayInstance[method](data);
  1220. return res;
  1221. }
  1222. }
  1223. module.exports = new service();