当前位置:   article > 正文

UniApp H5联调 微信支付/支付宝支付(带详细注释)_uniapp h5 微信支付

uniapp h5 微信支付

支付宝支付

1.首先要在HBuilder X 找到 manifest.json  找到App 模块配置 把Payment(支付) 勾选上

2. 因为我做的是H5, 调用支付宝支付的时候, 是通过后端返回的二进制的数据, 前端通过Vue-qrcode 转译成二维码

3. 然后因为这个二维码是微信跟支付宝都可以扫描的, 我们也通常把这个叫做融合支付, 详细的就是说 通过支付宝扫描是直接进入支付宝的环境,通过微信扫描是进入的微信的环境

4 .首先支付宝支付的话,一些基础的数据都是后端给咱们前端返回的

5.  http://192.168.3.63:8080/#/pages/ParkingFee/ParkingFee?app_id=902100013xxxxx1646&source=alipay_wallet&scope=auth_base&state=ZmZjZDk3MDI2OGY2NDY1xxxxQ5NTcxMTdlYzNlYzU%3D&auth_code=3855fa60c6d749219f111b8945xxxX97   这一串是后端给我返回的数据, 前端用到的数据也就没几个, 我来给大家说一下是什么意思

6. http://192.168.3.63:8080/#/pages/ParkingFee/ParkingFee  这个是我页面的路径

7. app_id=902100013xxxxx646   app_id就是获取支付宝授权的唯一标识

8.state=ZmZjZDk3MDI2OGY2xxxMDljNmQ5NTcxMTdlYzNlYzU%3D   商家自定义参数

9.auth_code=3855fa60c6d749219f111bxxxxxx97   用户信息授权的信息

  1. // 首先在onLoad 中接收扫码过后跳转的数据
  2. onLoad(options) {
  3. // 将传递过来的支付信息存储到当前实例的alipayInfo属性中
  4. this.alipayInfo = options;
  5. // 判断当前用户代理是否为支付宝
  6. if (this.userAgent.indexOf('alipay') !== -1) {
  7. // 当用户代理为支付宝时,解析state参数
  8. const encodedString = this.alipayInfo.state;
  9. // 转译Base64
  10. if (encodedString) {
  11. this.randomId = atob(encodedString);
  12. } else {
  13. return; // 如果state参数不存在,直接返回
  14. }
  15. // 调用支付函数,传入支付宝的app_id和auth_code
  16. this.paymentFn(this.alipayInfo.app_id, this.alipayInfo.auth_code);
  17. }
  18. // 调用获取支付订单信息函数,传入randomId
  19. this.getPayOrderInfoFn(this.randomId);
  20. }
  1. export default {
  2. data() {
  3. return {
  4. userAgent,
  5. type: 1,
  6. // 订单详细
  7. info: {},
  8. // 支付信息
  9. alipayInfo: {},
  10. // 支付宝token
  11. access_token: "",
  12. user_id: "",
  13. // 支付宝交易码
  14. tradeNO: "",
  15. // 订单id
  16. randomId: '',
  17. };
  18. },

  1. // 首先获取该条订单的信息数据
  2. getPayOrderInfoFn(randomId) {
  3. // 调用后端接口
  4. getPayOrderInfo(randomId).then((res) => {
  5. this.info = res.data
  6. })
  7. }
  8. // 获取支付宝授权
  9. paymentFn(app_id, auth_code) {
  10. userpay(app_id, auth_code).then((res) => {
  11. // 注意这里需要转一下格式
  12. const parsedResponse = JSON.parse(res);
  13. const oauthResponse = parsedResponse.alipay_system_oauth_token_response;
  14. // 从中取出 access_token 跟 user_id
  15. // 想拉起支付宝收银台这两个是必须要有的(详细看支付宝开发文档)
  16. this.access_token = oauthResponse.access_token;
  17. this.user_id = oauthResponse.user_id;
  18. })
  19. }

10. 现在支付字段已经都准备好了,下面开始调用支付宝收银台

  1. // html 部分
  2. <u-button type="primary" @click="userInfoPayFn">立即缴费</u-button>
  3. // Js 部分
  4. userInfoPayFn() {
  5. // 判断是否在支付宝浏览器
  6. if (userAgent.indexOf('alipay') !== -1) {
  7. let data = {
  8. userId: this.user_id, // 用户id
  9. openId: this.user_id, // 用户id
  10. topUpAmount: this.info.paycharge, // 支付金额
  11. payType: 'ALIPAYCLIENT', // 支付类型
  12. buyerLogonId: this.user_id, // 用户id
  13. orderNo: this.info.id, // 订单号
  14. appAuthToken: this.access_token // 后端返回的token
  15. }
  16. // 获取支付宝交易码
  17. userInfoPay(data).then((res)=> {
  18. // 还是同样的方法 需要转换格式
  19. const parsedResponse = JSON.parse(res.data);
  20. const oauthResponse = parsedResponse.alipay_trade_create_response;
  21. // 40004 这是支付宝官方定义的失败code码
  22. if (oauthResponse.code == 40004) {
  23. uni.showToast({
  24. title: `${oauthResponse.sub_msg}`,
  25. icon: 'none', //如果要纯文本,不要icon,将值设为'none'
  26. duration: 2000 //持续时间为 2秒
  27. })
  28. }
  29. // 拉起支付宝收银台 trade_no = 支付宝交易号
  30. this.callAlipay(oauthResponse.trade_no);
  31. })
  32. }
  33. },
  34. // 拉取支付宝收银台
  35. callAlipay(id) {
  36. // 判断是否存在支付宝的JSBridge
  37. if (window.AlipayJSBridge) {
  38. // 调用支付宝客户端接口,执行支付操作
  39. AlipayJSBridge.call('tradePay', {
  40. tradeNO: id
  41. }, function(result) {
  42. if (result.resultCode === '9000') {
  43. // 支付成功
  44. uni.$u.toast('支付成功!');
  45. setTimeout(() => {
  46. uni.reLaunch({
  47. url: '/pages/success/success'
  48. });
  49. }, 500);
  50. } else {
  51. // 支付失败
  52. uni.$u.toast('支付失败');
  53. setTimeout(() => {
  54. uni.reLaunch({
  55. url: '/pages/fail/fail'
  56. });
  57. }, 500);
  58. }
  59. });
  60. } else {
  61. // 如果支付宝的JSBridge尚未准备好,在文档中添加AlipayJSBridgeReady事件监听器
  62. document.addEventListener('AlipayJSBridgeReady', () => {
  63. // 准备就绪后再次调用支付函数,传入支付数据paymentData
  64. this.callAlipay(paymentData);
  65. });
  66. }
  67. }

11. 说到这里支付宝支付 已经说完了, 支付宝支付前端可以跟后端调试的话得在支付宝沙箱环境下调试

 微信支付

1. .首先要在HBuilder X 找到 manifest.json 把Payment支付勾上 还有就是一个 appid 需要后台给你.

2. 要调后端的预生成 订单 信息接口 去获取订单信息

3. weix.js 组件

  1. // weix.js
  2. // 首先尝试从本地存储中获取,如果不存在则尝试从URL参数中获取code,如果没有code则进行微信授权跳转,最终获取openId。获取过程中使用了getOpenIdBycode接口来获取openId。
  3. import { getOpenIdBycode } from "@/api/mobileCharging.js";
  4. export default {
  5. data() {
  6. return {
  7. openId: "",
  8. appId: ""
  9. };
  10. },
  11. mounted() {
  12. // 获取本地存储的openId和appId
  13. let openId = uni.getStorageSync('wx_openid');
  14. let appId = uni.getStorageSync('wx_appId');
  15. console.log('openId', openId);
  16. if (openId && appId) {
  17. // 如果本地存储中已经存在openId和appId,则直接使用
  18. this.openId = openId;
  19. this.appId = appId;
  20. return true;
  21. }
  22. // 如果本地存储中不存在openId和appId,则尝试从URL参数中获取code
  23. let code = this.getUrlKey('code');
  24. if (!code) {
  25. // 如果URL参数中没有code,则进行微信授权跳转获取code
  26. this.appId = 'wx0b3c40b8569affa2'; // 替换成你的公众号的AppID
  27. uni.setStorageSync('wx_appId', this.appId);
  28. let url =
  29. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=` +
  30. encodeURIComponent(location.href) + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
  31. location.href = url;
  32. } else {
  33. // 如果从URL参数中获取到了code,则调用接口获取openId
  34. getOpenIdBycode(code).then(res => {
  35. this.openId = res.data.openId;
  36. uni.setStorageSync('wx_openid', res.data.openId);
  37. });
  38. }
  39. },
  40. methods: {
  41. getUrlKey(name) {
  42. // 辅助函数,从URL中获取指定名称的参数值
  43. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
  44. }
  45. }
  46. };

4. 主页面

  1. // 首先我是引入了一个组件 (获取微信的openId和appId)
  2. import weix from "@/common/weix.js";
  3. // 这一行从浏览器中获取 userAgent 字符串 userAgent 字符串包含有关用户浏览器 设备和操作系统的信息 通过转换为小写 可以更容易地进行大小写不敏感的检查
  4. const userAgent = navigator.userAgent.toLowerCase();
  5. // 插件 npm i jweixin-module --save
  6. const wx = require('jweixin-module');
  7. export default {
  8. data() {
  9. return {
  10. userAgent,
  11. // 订单详细
  12. info: {},
  13. // 订单id
  14. randomId: '',
  15. }
  16. }
  17. },
  18. mixins: userAgent.indexOf('micromessenger') !== -1 ? [weix] : [],
  19. // 首先在onLoad 中接收扫码过后跳转的数据
  20. onLoad(options) {
  21. // 将传递过来的支付信息存储到当前实例的alipayInfo属性中
  22. this.alipayInfo = options;
  23. // 判断当前用户代理是否为微信
  24. if (this.userAgent.indexOf('micromessenger') !== -1) {
  25. // 订单id 来获取该条订单的全部数据
  26. this.randomId = this.alipayInfo.randomId;
  27. }
  28. // 调用获取支付订单信息函数,传入randomId
  29. this.getPayOrderInfoFn(this.randomId);
  30. },
  31. methods: {
  32. // 首先获取该条订单的信息数据
  33. getPayOrderInfoFn(randomId) {
  34. // 调用后端接口
  35. getPayOrderInfo(randomId).then((res) => {
  36. this.info = res.data
  37. })
  38. },
  39. // 点击缴费
  40. userInfoPayFn() {
  41. // 获取用户的 User Agent 字符串
  42. const userAgent = navigator.userAgent.toLowerCase();
  43. // 判断是否在微信浏览器
  44. if (userAgent.indexOf('micromessenger') !== -1) {
  45. console.log('在微信浏览器');
  46. // 构建支付所需的参数对象
  47. let data = {
  48. userId: this.openId, // 用户id
  49. openId: this.openId, // 用户id
  50. topUpAmount: this.info.paycharge, // 支付金额
  51. payType: 'MICROMESSENGER', // 支付类型
  52. buyerLogonId: this.openId, // 用户id
  53. tradeType: 0, // 停车缴费/月卡
  54. orderNo: this.info.id, // 订单号
  55. // appAuthToken: this.access_token // 后端返回的token
  56. }
  57. // 打印微信支付参数到控制台
  58. console.log('微信支付参数', data);
  59. // 获取微信支付信息
  60. userInfoPay(data).then((res) => {
  61. // 解析后端返回的支付参数
  62. let payParams = JSON.parse(res.data)
  63. // 配置微信支付参数
  64. wx.config({
  65. debug: false,
  66. appId: 'wx0b3c40b8569affa2', // 公众号ID
  67. // appId: uni.getAppBaseInfo().host.appId, // 公众号ID
  68. timestamp: payParams.timestamp, // 时间戳,自1970年以来的秒数
  69. nonceStr: payParams.nonceStr, // 随机串
  70. signature: payParams.sign, // 微信签名方式
  71. jsApiList: ['chooseWXPay']
  72. });
  73. // 初始化微信支付
  74. wx.ready(() => {
  75. // 在这里调用微信支付接口
  76. this.callWechatPay(payParams);
  77. });
  78. })
  79. }
  80. },
  81. // 拉取微信收银台
  82. callWechatPay(params) {
  83. // 调用微信支付接口
  84. wx.chooseWXPay({
  85. timestamp: params.timeStamp, // 时间戳
  86. nonceStr: params.nonceStr, // 随机串
  87. package: params.package, // 订单详情扩展字符串
  88. signType: 'MD5', // 签名方式
  89. paySign: params.sign, // 签名
  90. success: function(res) {
  91. // 支付成功后的回调函数
  92. console.log('Payment succeeded', res);
  93. uni.$u.toast('支付成功!')
  94. setTimeout(() => {
  95. uni.reLaunch({
  96. url: '/pages/success/success'
  97. })
  98. }, 500)
  99. },
  100. fail: function(res) {
  101. // 支付失败后的回调函数
  102. console.error('Payment failed', res);
  103. uni.$u.toast('支付失败')
  104. setTimeout(() => {
  105. uni.reLaunch({
  106. url: '/pages/fail/fail'
  107. })
  108. }, 500)
  109. }
  110. });
  111. },
  112. }

总结:  这是支付宝微信支付 的全部流程,我写的也有不足的地方,但是对接支付完全够用了,望大家采纳!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/700292
推荐阅读
相关标签
  

闽ICP备14008679号