鸿蒙接入微信支付

1,154 阅读3分钟

1.开发准备

根据微信文档做好基本的微信后台配置

注意:Identifier的获取

image.png

获取Identifier的方法

import { bundleManager } from '@kit.AbilityKit'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
import { hilog } from '@kit.PerformanceAnalysisKit'; 
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO 
try { bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { 
    hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data));
}).catch((err: BusinessError) => { 
    hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message); 
    }); 
} catch (err) { 
    let message = (err as BusinessError).message; hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', message); 
 }

打印data之后,需要的Identifierdata->signaturelnfo->appldentifier

参考链接:鸿蒙中微信开放平台中需要设置Identifier如何获取

2.SDK接入

  • 配置SDK依赖

修改项目中的oh-package.json5文件,在dependencies中加入微信 opensdk 的依赖项:

{
2  "name": "demo",
3  "version": "1.0.0",
4  "description": "Please describe the basic information.",
5  "main": "",
6  "author": "",
7  "license": "",
8   "dependencies": {
9    "@tencent/wechat_open_sdk": "1.0.0"
10  }
11}

2.1SDK的安装

安装SDK移步到:ohpm.openharmony.cn/#/cn/detail…

注意当前安装上的版本是1.0.6,上面👆🏻dependencies要改成对应的接入的版本号

在工程终端下面运行: ohpm i @tencent/wechat_open_sdk

2.2 关键代码接入

2.2.1 在业务调用中

结合微信提供的demo,关键代码在"Pay.ets"中:

import * as wxopensdk from '@tencent/wechat_open_sdk';

build() {
  Column({ space: 20 }) {
    Text("跳转支付").fontSize(20).fontWeight("bold").width('100%').padding(16)
    Button("跳转支付").onClick(async () => {

      let req = new wxopensdk.PayReq
      req.partnerId = '2480306091'
      req.appId = 'wx05b3e2e9fc730840'
      req.packageValue = 'Sign=WXPay'
      req.prepayId = 'wx26161523845794ecced251acf2b6860000'
      req.nonceStr = 'vmall_240926161523_993_2774'
      req.timeStamp = '1727338524'
      req.sign = 'rAqsrx5yLfRNBGvlHYuLhUsNK0OPeOLQ5xlvhxFo9guPU4HeNtzRdPaGAXAzXvn7V5chVe8sj3BfvDgwXlCKctCcFIllOgheyZbZ7btFC++9bW0QTijhWo1hZ6LhvjcKQ1zf53RGX7zf7GBu9sheqWPKlWqJJzynBZo8UH5Wow9t/WK5fanNj6ST2U2zPQGxuCH+DBMOKJAhhaalrOXlqj+feEiz1bLAzEmhLzIREgcWJQyZmdI5VO0B8r11ND+o1iBYgoohDUuJc+bd9r6RvmZBSE+HqggWE4p3D0/NzY7mQH+51u0osfOfaTHVLqlUM3IMoXi1vH4a0Qrg1P6c0g=='
      req.extData = 'extData'

      let finished = await this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req)
      console.log("send request finished: ", finished)
    }).width('80%')

    Text(this.payResultText)
      .width('80%')
      .fontSize(17)
      .lineHeight(20)
  }
}

在demo的这个文件中,定义了一些回调,如果要直接使用demo里的方法,也要把WXApiWrap.ets也实现了,这里定义并实现了一些wxopensdk里的初始化和回调监听。

2.2.1.1 参数说明
  • v2版本

image.png v2参数说明

  • v3版本

image.png v2和v3关于sign的加密方式不一样,注意接入版本,最新版加密是使用商户私钥对_待签名串_进行SHA256 with RSA签名,并对签名结果进行Base64编码得到签名值。

2.2.2在EntryAbility中
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)
  }
}
2.2.3 判断微信是否安装
2.2.3.1 判断方法

文档中让使用方法WXApi.isWXAppInstalled()进行判断,该方法是在wxopensdk中的WXApi中封装的方法,实际实现是在WXAPIFactory中

isWXAppInstalled(): boolean {
  try {
    return bundleManager.canOpenLink("weixin://")
  } catch (e) {
    let code = (e as BusinessError)?.code
    let msg = (e as BusinessError)?.message ?? ''
    if (code !== undefined) {
      if (code === 17700056) {
        msg += ` Please include "weixin" inside the "querySchemes" element of module.json5 in your app module.`
      }
      Log.e(kTag, `isWXAppInstalled get error ${msg}`)
    } else {
      Log.e(kTag, `isWXAppInstalled get error ${e}`)
    }
    return false
  }
}

注意引用正确,或者直接使用demo里文件WXApiWrap.ets,对WXApi进行了引用。

2.2.3.2 添加相关配置

在开发者的 App module的 module.json5 里加入下方声明:

image.png

至此,SDK的配置和关键代码接入完毕,点击能顺利拉起微信。good luck!