在 UniApp 中用 UTS 封装钉钉登录(HarmonyOS)
插件开发背景
业务需要在鸿蒙端提供一键授权登录的统一能力。钉钉开放平台已提供标准 ArkTS 能力,通过 ArkUI 组件与 UTS 的嵌入式原生组件机制,将授权登录流程抽象为一个可复用的页面 <embed> 组件。目标是:最少的页面接入代码、清晰的事件回调、可控的依赖与权限声明。仅考虑 ArkTS API。
这里用到了嵌入原生组件能力。
鸿蒙原生实现(ArkUI + OpenAuth)
核心在 ETS 侧完成交互和授权触发,依赖 @dingtalk/openauth:
// utssdk/app-harmony/button.ets(示意结构)
import { NativeEmbedBuilderOptions, defineNativeEmbed } from "@dcloudio/uni-app-runtime"
import { DDAuthApiFactory, AuthLoginParam } from '@dingtalk/openauth'
interface ButtonBuilderOptions extends NativeEmbedBuilderOptions {
label: string
// 其他自定义参数,如登录场景、回调地址等
}
@Component
struct ButtonComponent {
@Prop label: string
onButtonClick?: Function
build() {
Button(this.label)
.width('100%')
.height('100%')
.onClick(() => {
if (this.onButtonClick) {
const param: AuthLoginParam = {
// 根据业务填充必要参数,例如 appId、scope、state 等
}
DDAuthApiFactory.createDDAuthApi(param).authLogin(this)
this.onButtonClick({ detail: { status: 'pending' } })
}
})
}
}
@Builder
function ButtonBuilder(options: ButtonBuilderOptions) {
ButtonComponent({
label: options.label,
onButtonClick: options?.on?.get('buttonclick')
})
.width(options.width)
.height(options.height)
}
defineNativeEmbed('button', { builder: ButtonBuilder })
要点说明:
Button负责视觉与交互,授权调用走DDAuthApiFactory。- *通过
options.on映射到组件内部回调,事件名约定为全小写(如buttonclick)。 - UTS/ETS 不支持结构化类型等价,事件
detail与自定义参数类型要统一定义和复用。
UTS 封装实现(目录、依赖、导出)
目录结构:
uni_modules/harmony-dingding-login/
└─ utssdk/
├─ app-harmony/
│ ├─ index.uts
│ ├─ button.ets
│ ├─ config.json
│ └─ module.json5
└─ interface.uts
关键文件:
utssdk/app-harmony/config.json引入三方依赖(已内置):
{
"dependencies": {
"@dingtalk/openauth": "^1.1.0"
}
}
utssdk/app-harmony/index.uts负责激活原生组件:
// 内容即导入 ETS,触发注册
import './button.ets'
utssdk/interface.uts建议集中声明:事件细节、错误码、可选参数类型,确保 UTS/ETS 双侧一致。
用户使用说明(页面接入)
最少 3 步:
- 在页面引入插件:
import '@/uni_modules/harmony-dingding-login' - 在模板中使用
<embed>:指定tag="button"、绑定@buttonclick - 组织
options:包含按钮文案、宽高、以及钉钉授权所需参数
示例:
<template>
<view>
<embed class="dd-login" tag="button" :options="options" @buttonclick="onLogin" />
</view>
<!-- 建议宽高固定,避免布局跳动 -->
</template>
<script>
import '@/uni_modules/harmony-dingding-login'
export default {
data() {
return {
options: {
width: 200,
height: 44,
label: '钉钉登录',
on: new Map(), // 可按需传入,也可使用 @buttonclick 监听
// 可放置与授权相关的业务参数,以便在 ETS 读取
// appId、scope、state 等
}
}
},
methods: {
onLogin(e) {
// e.detail 建议包含授权阶段/结果数据
console.log('dingding auth:', e.detail)
// 与后端交换 code/token,完成会话建立
}
}
}
</script>
<style scoped>
.dd-login { display: block; width: 200px; height: 44px; }
</style>
注意事项
- 依赖已内置:
@dingtalk/openauth版本^1.1.0写入utssdk/app-harmony/config.json。
有疑问可留言说明
遇到授权参数、事件结构、标签命名、真机兼容等问题,直接留言描述运行环境与报错信息(含系统版本、设备型号、必要截图)。
5 个评论
要回复文章请先登录或注册
青衫行者
DCloud_UNI_LXH
人物略有不同
绛珠
人物略有不同