pay.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import sheep from '@/sheep';
  2. // #ifdef H5
  3. import $wxsdk from '@/sheep/libs/sdk-h5-weixin';
  4. // #endif
  5. import {
  6. getRootUrl
  7. } from '@/sheep/helper';
  8. import PayOrderApi from '@/sheep/api/pay/order';
  9. import {
  10. t
  11. } from '@/locale';
  12. /**
  13. * 支付
  14. *
  15. * @param {String} payment = ['wechat','alipay','wallet','mock'] - 支付方式
  16. * @param {String} orderType = ['goods','recharge','groupon'] - 订单类型
  17. * @param {String} id - 订单号
  18. * @param {String} orderType2 = ['1','2'] - 中星订单类型,1商品 2消费分充值
  19. */
  20. export default class SheepPay {
  21. constructor(payment, orderType, id, orderType2) {
  22. this.payment = payment;
  23. this.id = id;
  24. this.orderType = orderType;
  25. this.orderType2 = orderType2;
  26. this.payAction();
  27. }
  28. payAction() {
  29. const payAction = {
  30. WechatOfficialAccount: {
  31. wechat: () => {
  32. this.wechatOfficialAccountPay();
  33. },
  34. JSAPI:() => {
  35. this.fuYouWechatOfficialAccountPay();
  36. },
  37. alipay: () => {
  38. this.redirectPay(); // 现在公众号可以直接跳转支付宝页面
  39. },
  40. wallet: () => {
  41. this.walletPay();
  42. },
  43. mock: () => {
  44. this.mockPay();
  45. },
  46. wx_pub:() => {
  47. payAction.WechatOfficialAccount.wechat();
  48. }
  49. },
  50. WechatMiniProgram: {
  51. wechat: () => {
  52. this.wechatMiniProgramPay();
  53. },
  54. JSAPI:() => {
  55. this.fuYouWechatOfficialAccountPay();
  56. },
  57. alipay: () => {
  58. this.copyPayLink();
  59. },
  60. wallet: () => {
  61. this.walletPay();
  62. },
  63. mock: () => {
  64. this.mockPay();
  65. },
  66. wx_pub:() => {
  67. this.wechatMiniProgramPay();
  68. }
  69. },
  70. App: {
  71. wechat: () => {
  72. this.wechatAppPay();
  73. },
  74. JSAPI:() => {
  75. this.fuYouWechatOfficialAccountPay();
  76. },
  77. alipay: () => {
  78. this.alipay();
  79. },
  80. wallet: () => {
  81. this.walletPay();
  82. },
  83. mock: () => {
  84. this.mockPay();
  85. }
  86. },
  87. H5: {
  88. wechat: () => {
  89. this.wechatWapPay();
  90. },
  91. JSAPI:() => {
  92. this.fuYouWechatOfficialAccountPay();
  93. },
  94. alipay: () => {
  95. this.redirectPay();
  96. },
  97. wallet: () => {
  98. this.walletPay();
  99. },
  100. mock: () => {
  101. this.mockPay();
  102. },
  103. wx_pub:() => {
  104. payAction.WechatOfficialAccount.wechat();
  105. }
  106. },
  107. };
  108. // console.log(payAction[sheep.$platform.name],this.payment)
  109. return payAction[sheep.$platform.name][this.payment]();
  110. }
  111. // 预支付
  112. prepay(channel) {
  113. return new Promise(async (resolve, reject) => {
  114. let data = {
  115. id: this.id,
  116. channelCode: channel,
  117. channelExtras: {},
  118. orderType:this.orderType2
  119. };
  120. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid
  121. if (['wx_pub', 'wx_lite'].includes(channel)) {
  122. const openid = await sheep.$platform.useProvider('wechat').getOpenid(true);
  123. // 如果获取不到 openid,微信无法发起支付,此时需要引导
  124. if (!openid) {
  125. this.bindWeixin();
  126. return;
  127. }
  128. data.channelExtras.openid = openid;
  129. }
  130. // 发起预支付 API 调用
  131. PayOrderApi.submitOrder(data).then((res) => {
  132. // 成功时
  133. res.code === 0 && resolve(res);
  134. // 失败时
  135. if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {
  136. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况
  137. if (res.msg.indexOf('无效的openid') >= 0 // 获取的 openid 不正确时,或者随便输入了个 openid
  138. ||
  139. res.msg.indexOf('下单账号与支付账号不一致') >= 0
  140. ){ // https://developers.weixin.qq.com/community/develop/doc/00008c53c347804beec82aed051c00
  141. this.bindWeixin();
  142. }
  143. }
  144. });
  145. });
  146. }
  147. // 富友预支付
  148. fuYouPrePay(channel) {
  149. return new Promise(async (resolve, reject) => {
  150. let data = {
  151. id: this.id,
  152. channelCode:channel,
  153. orderType:this.orderType2,
  154. req: {
  155. trade_type: channel,
  156. }
  157. };
  158. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid
  159. if (['wx_pub', 'wx_lite','JSAPI'].includes(channel)) {
  160. const openid = await sheep.$platform.useProvider('wechat').getOpenid(true);
  161. // 如果获取不到 openid,微信无法发起支付,此时需要引导
  162. if (!openid) {
  163. this.bindWeixin();
  164. return;
  165. }
  166. data.req.sub_openid = openid;
  167. }
  168. // console.log("富友支付",data)
  169. // 发起预支付 API 调用
  170. PayOrderApi.fuYouSubmitOrder(data).then((res) => {
  171. // 成功时
  172. res.code === 0 && resolve(res);
  173. // 失败时
  174. if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {
  175. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况
  176. if (res.msg.indexOf('无效的openid') >= 0 // 获取的 openid 不正确时,或者随便输入了个 openid
  177. ||
  178. res.msg.indexOf('下单账号与支付账号不一致') >= 0
  179. ) { // https://developers.weixin.qq.com/community/develop/doc/00008c53c347804beec82aed051c00
  180. this.bindWeixin();
  181. }
  182. }
  183. });
  184. });
  185. }
  186. // #ifdef H5
  187. // 富友微信公众号 JSSDK 支付
  188. async fuYouWechatOfficialAccountPay(orderType2) {
  189. // console.log("富友微信公众号 JSSDK 支付");
  190. let {
  191. code,
  192. data
  193. } = await this.fuYouPrePay('JSAPI');
  194. if (code !== 0) {
  195. return;
  196. }
  197. let newJsonString = data.replace(/"sdk_package":/g, '"packageValue":');
  198. const payConfig = JSON.parse(newJsonString);
  199. // console.log('payConfig',payConfig);
  200. // return;
  201. $wxsdk.wxpay(payConfig, {
  202. success: () => {
  203. this.payResult('success');
  204. },
  205. cancel: () => {
  206. sheep.$helper.toast(t('common.payment_manually_cancelled'));
  207. },
  208. fail: (error) => {
  209. if (error.errMsg.indexOf('chooseWXPay:没有此SDK或暂不支持此SDK模拟') >= 0) {
  210. sheep.$helper.toast('发起微信支付失败,原因:可能是微信开发者工具不支持,建议使用微信打开网页后支付');
  211. return
  212. }
  213. this.payResult('fail');
  214. },
  215. });
  216. }
  217. // 微信公众号 JSSDK 支付
  218. async wechatOfficialAccountPay(orderType2) {
  219. let {
  220. code,
  221. data
  222. } = await this.prepay('wx_pub');
  223. if (code !== 0) {
  224. return;
  225. }
  226. const payConfig = JSON.parse(data.displayContent);
  227. $wxsdk.wxpay(payConfig, {
  228. success: () => {
  229. this.payResult('success');
  230. },
  231. cancel: () => {
  232. sheep.$helper.toast(t('common.payment_manually_cancelled'));
  233. },
  234. fail: (error) => {
  235. if (error.errMsg.indexOf('chooseWXPay:没有此SDK或暂不支持此SDK模拟') >= 0) {
  236. sheep.$helper.toast('发起微信支付失败,原因:可能是微信开发者工具不支持,建议使用微信打开网页后支付');
  237. return
  238. }
  239. this.payResult('fail');
  240. },
  241. });
  242. }
  243. // 浏览器微信 H5 支付 TODO 非繁人:待接入
  244. async wechatWapPay() {
  245. const {
  246. error,
  247. data
  248. } = await this.prepay();
  249. if (error === 0) {
  250. const redirect_url =
  251. `${getRootUrl()}pages/pay/result?id=${this.id}&payment=${this.payment}&orderType=${this.orderType}`;
  252. location.href = `${data.pay_data.h5_url}&redirect_url=${encodeURIComponent(redirect_url)}`;
  253. }
  254. }
  255. // 支付链接 TODO 非繁人:待接入
  256. async redirectPay() {
  257. let {
  258. error,
  259. data
  260. } = await this.prepay();
  261. if (error === 0) {
  262. const redirect_url =
  263. `${getRootUrl()}pages/pay/result?id=${this.id}&payment=${this.payment}&orderType=${this.orderType}`;
  264. location.href = data.pay_data + encodeURIComponent(redirect_url);
  265. }
  266. }
  267. // #endif
  268. // 微信小程序支付
  269. async wechatMiniProgramPay() {
  270. // let that = this;
  271. let {
  272. code,
  273. data
  274. } = await this.prepay('wx_lite');
  275. if (code !== 0) {
  276. return;
  277. }
  278. // 调用微信小程序支付
  279. const payConfig = JSON.parse(data.displayContent);
  280. uni.requestPayment({
  281. provider: 'wxpay',
  282. timeStamp: payConfig.timeStamp,
  283. nonceStr: payConfig.nonceStr,
  284. package: payConfig.packageValue,
  285. signType: payConfig.signType,
  286. paySign: payConfig.paySign,
  287. success: (res) => {
  288. this.payResult('success');
  289. },
  290. fail: (err) => {
  291. if (err.errMsg === 'requestPayment:fail cancel') {
  292. sheep.$helper.toast(t('common.payment_manually_cancelled'));
  293. } else {
  294. this.payResult('fail');
  295. }
  296. },
  297. });
  298. }
  299. // 余额支付
  300. async walletPay() {
  301. const {
  302. code
  303. } = await this.prepay('wallet');
  304. code === 0 && this.payResult('success');
  305. }
  306. // 模拟支付
  307. async mockPay() {
  308. const {
  309. code
  310. } = await this.prepay('mock');
  311. code === 0 && this.payResult('success');
  312. }
  313. // 支付宝复制链接支付 TODO 非繁人:待接入
  314. async copyPayLink() {
  315. let that = this;
  316. let {
  317. error,
  318. data
  319. } = await this.prepay();
  320. if (error === 0) {
  321. // 引入showModal 点击确认 复制链接;
  322. uni.showModal({
  323. title: t('common.alipay_payment'),
  324. content: t('common.copy_link_to_browser'),
  325. confirmText: t('common.copy_link'),
  326. success: (res) => {
  327. if (res.confirm) {
  328. sheep.$helper.copyText(data.pay_data);
  329. }
  330. },
  331. });
  332. }
  333. }
  334. // 支付宝支付 TODO 非繁人:待接入
  335. async alipay() {
  336. let that = this;
  337. const {
  338. error,
  339. data
  340. } = await this.prepay();
  341. if (error === 0) {
  342. uni.requestPayment({
  343. provider: 'alipay',
  344. orderInfo: data.pay_data, //支付宝订单数据
  345. success: (res) => {
  346. that.payResult('success');
  347. },
  348. fail: (err) => {
  349. if (err.errMsg === 'requestPayment:fail [paymentAlipay:62001]user cancel') {
  350. sheep.$helper.toast(t('common.payment_manually_cancelled'));
  351. } else {
  352. that.payResult('fail');
  353. }
  354. },
  355. });
  356. }
  357. }
  358. // 微信支付 TODO 非繁人:待接入
  359. async wechatAppPay() {
  360. let that = this;
  361. let {
  362. error,
  363. data
  364. } = await this.prepay();
  365. if (error === 0) {
  366. uni.requestPayment({
  367. provider: 'wxpay',
  368. orderInfo: data.pay_data, //微信订单数据(官方说是string。实测为object)
  369. success: (res) => {
  370. that.payResult('success');
  371. },
  372. fail: (err) => {
  373. err.errMsg !== 'requestPayment:fail cancel' && that.payResult('fail');
  374. },
  375. });
  376. }
  377. }
  378. // 支付结果跳转,success:成功,fail:失败
  379. payResult(resultType) {
  380. // console.log(this.id)
  381. sheep.$router.redirect('/pages/pay/resultYuan', {
  382. id: this.id,
  383. orderType: this.orderType,
  384. payState: resultType
  385. });
  386. }
  387. // 引导绑定微信
  388. bindWeixin() {
  389. uni.showModal({
  390. title: t('common.wechat_payment'),
  391. content: t('common.bind_wechat_for_payment'),
  392. confirmText: t('common.bind'),
  393. success: function(res) {
  394. if (res.confirm) {
  395. sheep.$platform.useProvider('wechat').bind();
  396. }
  397. },
  398. });
  399. }
  400. }
  401. export function getPayMethods(channels) {
  402. // console.log("来拿支付渠道",channels)
  403. let payMethods = [
  404. {
  405. icon: '/static/images/wechat.png',
  406. title: t('common.wechat_payment'),
  407. value: 'wx_pub',
  408. disabled: false,
  409. },
  410. {
  411. icon: '/static/images/wechat.png',
  412. title: t('common.wechat_payment'),
  413. value: 'JSAPI',
  414. disabled: false,
  415. },
  416. {
  417. icon: '/static/images/alipay.png',
  418. title: t('common.alipay_payment'),
  419. value: 'alipay',
  420. disabled: false,
  421. },
  422. {
  423. icon: '/static/images/wallet.png',
  424. title: t('common.balance_payment'),
  425. value: 'wallet',
  426. disabled: false,
  427. },
  428. {
  429. icon: '/static/images/apple.png',
  430. title: 'Apple Pay',
  431. value: 'apple',
  432. disabled: false,
  433. },
  434. {
  435. icon: '/static/images/wallet.png',
  436. title: t('common.mock_payment'),
  437. value: 'mock',
  438. disabled: false,
  439. }
  440. ];
  441. const platform = sheep.$platform.name
  442. // 1. 处理【微信支付】
  443. const wechatMethod = payMethods[0];
  444. if ((platform === 'WechatOfficialAccount' && channels.includes('wx_pub')) ||
  445. (platform === 'WechatMiniProgram' && channels.includes('wx_lite')) ||
  446. (platform === 'App' && channels.includes('wx_app'))) {
  447. wechatMethod.disabled = false;
  448. }
  449. // 2. 处理【支付宝支付】
  450. const alipayMethod = payMethods[1];
  451. if ((platform === 'WechatOfficialAccount' && channels.includes('alipay_wap')) ||
  452. platform === 'WechatMiniProgram' && channels.includes('alipay_wap') ||
  453. platform === 'App' && channels.includes('alipay_app')) {
  454. alipayMethod.disabled = false;
  455. }
  456. // 3. 处理【余额支付】
  457. const walletMethod = payMethods[2];
  458. if (channels.includes('wallet')) {
  459. walletMethod.disabled = false;
  460. }
  461. // 4. 处理【苹果支付】TODO 非繁人:未来接入
  462. // 5. 处理【模拟支付】
  463. const mockMethod = payMethods[4];
  464. if (channels.includes('mock')) {
  465. mockMethod.disabled = false;
  466. }
  467. function filterPayMethods(payMethods, channels) {
  468. for (let i = payMethods.length - 1; i >= 0; i--) {
  469. if (!channels.includes(payMethods[i].value)) {
  470. payMethods.splice(i, 1);
  471. }
  472. }
  473. }
  474. // 示例:channels 只包含 'wechat' 和 'alipay'
  475. filterPayMethods(payMethods,channels);
  476. console.log(payMethods)
  477. return payMethods;
  478. }