外部H5端使用支付宝预授权

关于如何使用

需要配合支付宝小程序来实现预授权,H5通过scheme的方式调起支付宝中的小程序完成授权

注意点

H5端从服务器获取的orderStr需要进行两次encodeURIComponent操作,然后像如下规则拼接在一起,注意:必须在scheme再次encodeURIComponent一次,否则小程序端onLoad中无法接收到参数

页面参数的方式来传递orderStr

H5端处理代码

let orderStr = res.data //从服务端获取的orderStr
if (orderStr) {
	orderStr = encodeURIComponent(orderStr)
	orderStr = encodeURIComponent(orderStr)
	let scheme =
		`alipays://platformapi/startapp?appId=20210xxxxxx&page=pages/index/index?orderStr=${orderStr}`
	let url = `https://ds.alipay.com/?scheme=${encodeURIComponent(scheme)}`
	//H5 唤起预授权
	window.location.href  = url
}

支付宝小程序处理代码

Page({
  onLoad(query) {
    // 页面加载
    this.apply(query)
  },
  //唤起预授权
  apply(query) {
    let orderStr = query.orderStr //获取传递过来的orderStr
    if (!orderStr) {
      my.showToast({
        type: "none",
        content: '订单参数获取失败,请重试'
      })
      return
    }
    my.tradePay({
      // 调用资金冻结接口(alipay.fund.auth.order.app.freeze),获取支付宝预授权参数
      orderStr: orderStr,
      success: (res) => {
        my.showToast({
          type: "none",
          content: res.memo
        })
      },
      fail: (res) => {
        my.showToast({
          type: "none",
          content: res
        })
      }
    });
  }
});

query启动参数的方式来传递orderStr

H5端处理代码

let orderStr = res.data //从服务端获取的orderStr
if (orderStr) {
	orderStr = encodeURIComponent(orderStr)
	orderStr = encodeURIComponent(orderStr)
	let scheme =
		`alipays://platformapi/startapp?appId=20210xxxxxx&page=pages/index/index&query=orderStr=${orderStr}`
	let url = `https://ds.alipay.com/?scheme=${encodeURIComponent(scheme)}`
	//H5 唤起预授权
	window.location.href  = url
}

支付宝小程序处理代码

Page({
  data: {
    orderStr: ''
  },
  onLoad(query) {
    // 页面加载
    const options = my.getEnterOptionsSync();  //获取冷、热启动参数
    if (options.query && options.query.orderStr) {
      this.setData({
        orderStr: options.query.orderStr
      })
    }
    this.apply()
  },
  //唤起预授权
  apply() {
    let orderStr = this.data.orderStr
    if (!orderStr) {
      my.showToast({
        type: "none",
        content: '订单参数获取失败,请重试'
      })
      return
    }
    my.tradePay({
      // 调用资金冻结接口(alipay.fund.auth.order.app.freeze),获取支付宝预授权参数
      orderStr: orderStr,
      success: (res) => {
        my.showToast({
          type: "none",
          content: res.memo
        })
      },
      fail: (res) => {
        my.showToast({
          type: "none",
          content: res
        })
      }
    });
  }
});

问题记录

我自己是把生成好的scheme传给向下一个页面中的webview中使用,整个url是带参数的,当时未将拼接的url进行encodeURIComponent,导致传递到下一个页面上时参数都丢失了,所以传递参数是带参数的url需经过encodeURIComponent处理一下

encodeURI()和encodeURIComponent()都是Javascript中对URL编码的函数。
区别在于:
encodeURI()着眼于对整个URL进行编码,特殊含义的符号"; / ? : @ & = + $ , #“不进行编码
encodeURIComponent()对URL的组成部分进行个别编码,所以”; / ? : @ & = + $ , #"在这里是可以进行编码

http路径采用encodeURI进行编码,但是在路径中携带的参数采用encodeURIComponent进行编码

参考官方文档

Android端测试scheme是否可用支付宝官方应用
支付宝官方小程序预授权开发文档
支付宝官方文档scheme拼接规则介绍

猜你喜欢

转载自blog.csdn.net/Admin_yws/article/details/126350851