支付宝支付
当前我们有现成的支付宝H5端支付能力,所以需要我们采用混合开发的模式进行操作,所谓混合开发就是鸿蒙原生内嵌一个支付宝的h5页面,经过互相通信实现整个支付流程
- 使用Web组件通过src发起支付宝接口请求(携带订单id参数)
- 监听Web组件的网络请求变化,如果发现/pay/redirect 关键标识,证明支付已经完成
- 解析回调参数(如果payResult参数为true,即为成功)
import { promptAction } from '@kit.ArkUI'
import { webview } from '@kit.ArkWeb'@Component
struct PayOrder {@Consume navPathStack: NavPathStack@State orderId: string = ''webController: WebviewController = new webview.WebviewController()aboutToAppear(): void {const result = this.navPathStack.getParamByName('PayOrder') as string[]const id = result[0]if (id) {// 正常this.orderId = id} else {// 异常promptAction.showToast({message: '订单获取失败'})}}build() {Column() {Web({//支付页面的地址:https://meikou-api.itheima.net/pay/wap/aliPay?orderId=src: 'https://meikou-api.itheima.net/pay/wap/aliPay?orderId=' + this.orderId,controller: this.webController}).onPageBegin((event) => {// 根据页面url的变化,判断是否支付完成,支付完成:"pay/redirect"if (event.url.includes('https://meikou-api.itheima.net/pay/redirect')) {// 支付完成,返回首页(清空路由栈是为了不让用户返回之前支付的页面)this.navPathStack.clear()}})}.width('100%').height('100%')}
}@Builder
function PayOrderBuilder() {NavDestination() {PayOrder()}.hideTitleBar(true)
}
}