尚拙

一个分享技术、学习成长的个人博客网站

0%

HarmonyOS Next 微信支付开发指南

详细记录一下鸿蒙系统版本的微信支付开发过程,避免日后踩坑。

一、微信后台添加应用并配置鸿蒙应用信息

首先要在微信开放平台(https://open.weixin.qq.com)添加应用,配置鸿蒙应用信息并审核通过。

Bundle ID:指的是鸿蒙应用的包名

Identifier:指的是鸿蒙应用的 appIdentifier

获取方法一:华为应用后台获取

华为应用管理 —> 我的项目 —> 项目设置 —> OAuth 2.0客户端ID —> Client ID

Client ID 就是鸿蒙应用的 appIdentifier

获取方法二:代码获取

bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO).then((info) => {
let appIdentifier = info.signatureInfo.appIdentifier
LogUtil.debug("[EntryAbility]appIdentifier:" + appIdentifier)
})

二、引入微信SDK

在项目级或者应用级的oh-package.json5文件中的dependencies增加微信sdk库,注意修改sdk最新的版本号

"dependencies": {
"@tencent/wechat_open_sdk": "1.0.14"
}

三、增加微信SDK回调类

新建文件WXApiWrap.ets,代码如下

import * as wxopensdk from '@tencent/wechat_open_sdk';
import { LogUtil } from '../utils/LogUtil';

export type OnWXReq = (req: wxopensdk.BaseReq) => void
export type OnWXResp = (resp: wxopensdk.BaseResp) => void

const kTag = "WXApiEventHandlerImpl"

class WXApiEventHandlerImpl implements wxopensdk.WXApiEventHandler {
private onReqCallbacks: Map<OnWXReq, OnWXReq> = new Map
private onRespCallbacks: Map<OnWXResp, OnWXResp> = new Map

registerOnWXReqCallback(on: OnWXReq) {
this.onReqCallbacks.set(on, on)
}
unregisterOnWXReqCallback(on: OnWXReq) {
this.onReqCallbacks.delete(on)
}

registerOnWXRespCallback(on: OnWXResp) {
this.onRespCallbacks.set(on, on)
}
unregisterOnWXRespCallback(on: OnWXResp) {
this.onRespCallbacks.delete(on)
}

onReq(req: wxopensdk.BaseReq): void {
wxopensdk.Log.i(kTag, "onReq:%s", JSON.stringify(req))
LogUtil.debug("[WXApiEventHandlerImpl]onReq",JSON.stringify(req))
this.onReqCallbacks.forEach((on) => {
on(req)
})
}

onResp(resp: wxopensdk.BaseResp): void {
wxopensdk.Log.i(kTag, "onResp:%s", JSON.stringify(resp))
LogUtil.debug("[WXApiEventHandlerImpl]onResp",JSON.stringify(resp))
this.onRespCallbacks.forEach((on) => {
on(resp)
})
}
}

export const WXApi = wxopensdk.WXAPIFactory.createWXAPI("填写微信后台移动应用的APPID")
export const WXEventHandler = new WXApiEventHandlerImpl

四、在EntryAbility中响应来自微信的回调

在应用启动类EntryAbility.ets中添加如下代码:

export default class EntryAbility extends UIAbility {
onCreate(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
this.handleWeChatCallIfNeed(want)
}

onNewWant(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
this.handleWeChatCallIfNeed(want)
}

private handleWeChatCallIfNeed(want: Want) {
WXApi.handleWant(want, WXEventHandler)
}
}

主要是添加handleWeChatCallIfNeed函数,然后在EntryAbility的onCreate和onNewWant生命周期中调用该函数

五、生成订单

1、服务端需要集成微信支付SDK

2、客户端调用服务端接口,进行预下单,并返回订单信息partnerId、prepayId、noncestr、timestamp、sign等字段

六、调用微信支付

1、定义微信wxApi、wxEventHandler对象和OnWXResp回调

@State payResultText: string = ''
private wxApi = WXApi
private wxEventHandler = WXEventHandler
private onWXResp: OnWXResp = (resp) => {
this.payResultText = JSON.stringify(resp ?? {}, null, 2)
LogUtil.debug("[BuyVipPage]onWXResp payResultText",this.payResultText)
if(resp["errCode"] === ErrCode.ERR_OK ){
emitter.emit(MessageEvent.BUY_VIP_SUCCESS,{priority:emitter.EventPriority.HIGH})
router.back()
}else if (resp["errCode"] === ErrCode.ERR_USER_CANCEL){
promptAction.showToast({
message: "取消支付",
duration: 1000
})
}else {
promptAction.showToast({
message: "支付失败,请稍后重试或联系客服",
duration: 3000
})
}
}

2、注册微信登录回调

在aboutToAppear生命周期中注册微信登录回调,在aboutToDisappear生命周期中销毁微信登录回调

aboutToAppear(): void {
this.wxEventHandler.registerOnWXRespCallback(this.onWXResp)
}

aboutToDisappear(): void {
this.wxEventHandler.unregisterOnWXRespCallback(this.onWXResp)
}

3、发起支付

let req = new wxopensdk.PayReq
req.partnerId = orderInfo.partnerId
req.appId = WechatConstants.APPID
req.packageValue = 'Sign=WXPay'
req.prepayId = orderInfo.prepayId
req.nonceStr = orderInfo.noncestr
req.timeStamp = orderInfo.timestamp
req.sign = orderInfo.sign
let finished = await this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req)
console.log("send request finished: ", finished)

支付结束后,会在onWXResp回调里面返回支付结果