详细记录一下鸿蒙系统版本的微信登录开发,避免日后踩坑。
一、微信后台添加应用并配置鸿蒙应用信息
首先要在微信开放平台(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、定义微信wxApi、wxEventHandler对象和OnWXResp回调
private wxApi = WXApi private wxEventHandler = WXEventHandler @State authResultText: string = '' private onWXResp: OnWXResp = (resp) => { this.authResultText = JSON.stringify(resp ?? {}, null, 2) LogUtil.debug("wechat login result : " + this.authResultText) if(resp["errCode"] !== 0){ promptAction.showToast({ message: resp["errStr"], duration: 3000 }) }else { this.getWechatInfo(resp["code"]) } }
|
2、注册微信登录回调
在aboutToAppear生命周期中注册微信登录回调,在aboutToDisappear生命周期中销毁微信登录回调
aboutToAppear(): void { this.wxEventHandler.registerOnWXRespCallback(this.onWXResp) }
aboutToDisappear(): void { this.wxEventHandler.unregisterOnWXRespCallback(this.onWXResp) }
|
3、启动微信登录
let req = new wxopensdk.SendAuthReq req.isOption1 = false req.nonAutomatic = true req.scope = 'snsapi_userinfo' req.state = 'none' req.transaction = 'test123'
let finished = await this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req) LogUtil.debug("wechat login send request finished:" + finished)
|
4、请求接口获取openid
根据微信登录回调中的code,请求微信接口获取openid和unionid
async getWechatInfo(code:string){ let dto = await efRcpClientApi.get<string>({ url: `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WechatConstants.APPID}&secret=${WechatConstants.APP_SECRET}&code=${code}&grant_type=authorization_code` }); if(dto.data){ LogUtil.debug("getWechatInfo:" + JSON.stringify(dto.data)) let unionid:string = dto.data["unionid"] let openid:string = dto.data["openid"] this.thirdLogin("wechat",unionid) }else { promptAction.showToast({ message: "微信登录异常,请稍后重试", duration: 3000 }) }
}
|