# Delegate Methods
Some business logic in Mini-Programs is abstractly defined. These abstract business functions are exposed to the outside through interfaces, allowing external implementations to handle specific business logic.
If the function signature requires returning a boolean type to indicate whether to prevent default behavior, return
trueto block the default behavior, otherwise returnfalse.
The parameters
appIdandapiServerin the function represent the information of the triggered Mini-Program. Different logic can be executed for different Mini-Programs based on these two pieces of data.
# 1. CapsuleHandler
The delegate class for the capsule button.
// namespace IFinProxyHandlerItem
class CapsuleHandler {
/**
* Triggered when the close button is clicked
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Return true if the Host-App handles it independently; return false if the Host-App completes handling but still executes subsequent default operations
*/
public onCloseButtonClick(appId: string, apiServer: string): boolean
/**
* Triggered when the more button is clicked
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Return true if the Host-App handles it independently; return false if the Host-App completes handling but still executes subsequent default operations
*/
public onMoreButtonClick(appId: string, apiServer: string): boolean
}
Example code:
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
import { promptAction } from '@kit.ArkUI'
class CapsuleHandler extends IFinProxyHandlerItem.CapsuleHandler {
onCloseButtonClick(appId: string, apiServer: string): boolean {
this.promptMsg(`${appId}, Close button clicked`)
return false
}
onMoreButtonClick(appId: string, apiServer: string): boolean {
this.promptMsg(`${appId}, More button clicked`)
return false
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.capsuleHandler = new CapsuleHandler()
# 2. MoreMenuHandler
The delegate class for the more menu.
// namespace IFinProxyHandlerItem
class MoreMenuHandler {
/**
* Triggered when receiving data returned by the Mini-Program
* @param contentInfo Information returned by the Mini-Program
* @returns
*/
public onCustomMenuItemClickWithInfo(appId: string, apiServer: string,
contentInfo: IFinAppProxy.IMoreMenuItemContentInfo)
/**
* Triggered when the more menu button is clicked
* @param type Unique identifier of the menu button
* @param currentPath Current page path of the Mini-Program
* @returns
*/
public onMoreMenuItemClick(appId: string, apiServer: string, type: string, currentPath: string): boolean | void
/**
* Get the list of buttons in the more menu
* @returns List of buttons in the more menu
*/
public getMoreMenuItems(): IFinAppProxy.IMoreMenuItem[]
/**
* Delegate method triggered when adding to desktop
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param appletInfo Mini-Program information
* @param context UIAbilityContext
* @returns
*/
public async addToDesktop(appId: string, apiServer: string, appletInfo: IFinApplet.IAppletInfo,
context: common.UIAbilityContext)
}
Example code:
import { FinAppProxyHandlerManager, IFinApplet, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { common } from '@kit.AbilityKit'
import { request } from '@kit.BasicServicesKit'
import { productViewManager } from '@kit.AppGalleryKit'
import { fileIo } from '@kit.CoreFileKit'
import { promptAction } from '@kit.ArkUI'
class MoreMenuHandler extends IFinProxyHandlerItem.MoreMenuHandler {
onCustomMenuItemClickWithInfo(appId: string, apiServer: string,
contentInfo: IFinAppProxy.IMoreMenuItemContentInfo) {
this.promptMsg(`Mini-Program ${apiServer} ${appId}'s ${contentInfo.path} page menu ${contentInfo.menuId} was clicked, returned data: ${JSON.stringify(contentInfo.params)}`)
}
onMoreMenuItemClick(appId: string, apiServer: string, menuItemId: string, currentPath: string): boolean | void {
this.promptMsg(`Mini-Program ${apiServer} ${appId}'s ${currentPath} page menu ${menuItemId} was clicked`)
}
getMoreMenuItems(): IFinAppProxy.IMoreMenuItem[] {
return [
{
label: 'Custom',
icon: $r('app.media.app_icon'),
menuItemId: 'custom',
menuType: 'onMiniProgram'
}
]
}
public async addToDesktop(appId: string, apiServer: string, appletInfo: IFinApplet.IAppletInfo,
uiContext: common.UIAbilityContext) {
try {
const shortcutId = appletInfo.name
const label = appletInfo.name
const foregroundIcon = uiContext.tempDir + '/icon.png'
if (fileIo.accessSync(foregroundIcon)) {
await fileIo.unlink(foregroundIcon)
}
if (appletInfo.logo) {
await this.downloadFile(uiContext, appletInfo.logo, foregroundIcon)
}
const backgroundIcon = ''
// Verify if the shortcut is allowed to be added to the desktop using custom resources and return the verification result.
const result = await productViewManager.checkPinShortcutPermitted(uiContext, shortcutId, {
bundleName: uiContext.abilityInfo.bundleName,
abilityName: uiContext.abilityInfo.name,
moduleName: uiContext.abilityInfo.moduleName,
parameters: {
shortCutKey: 'startApplet',
appId,
apiServer
}
}, label, foregroundIcon, backgroundIcon)
await productViewManager.requestNewPinShortcut(uiContext, result.tid)
this.promptMsg('Added successfully')
} catch (err) {
this.promptMsg(`Add failed: ${err.message}`)
}
}
private async downloadFile(context: common.UIAbilityContext, url: string, tempSaveAbsPath: string): Promise<void> {
return new Promise(async (resolve) => {
const downloadTask = await request.downloadFile(context, {
url,
filePath: tempSaveAbsPath
})
downloadTask.on('complete', () => {
resolve()
})
})
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.moreMenuHandler = new MoreMenuHandler()
// Mini-Program side
Page({
onCustomButtonHandler(){
return {
appInfo:'this is appInfo'
}
}
})
IMoreMenuItem
| Property | Type | Required | Description |
|---|---|---|---|
| label | String | Yes | Mini-Program id |
| icon | ResourceStr | Yes | Image resource for the menu button |
| disableIcon | ResourceStr | No | Disabled image resource for the menu button |
| darkIcon | ResourceStr | No | Dark mode image resource for the menu button |
| disableDarkIcon | ResourceStr | No | Disabled dark mode image resource for the menu button |
| menuItemId | String | Yes | Unique identifier for the menu button, i.e., type in onMoreMenuItemClick |
| hover | Boolean | No | Whether to enable hover effect |
| disable | Boolean | No | Whether to disable |
IMoreMenuItemContentInfo
| Property | Type | Description |
|---|---|---|
| title | String | Mini-Program name |
| logo | String | Mini-Program logo |
| description | String | Mini-Program description |
| path | String | Current page path |
| menuId | String | Unique identifier for the menu button |
| params | IMoreMenuItemParams | Raw data returned by the Mini-Program |
IMoreMenuItemParams
| Property | Type |
|---|---|
| title | String |
| desc | String |
| path | String |
| appInfo | object |
# 3. PrivacyHandler
The delegate class for privacy agreements.
// namespace IFinProxyHandlerItem
export class PrivacyHandler {
/**
* @param scope Current requested permission; if empty, it refers to the privacy agreement displayed on the about page
* @returns IFinApplet.IPrivacy
*/
public getPrivacyInfo(appId: string, apiServer: string, scope?: string): IFinApplet.IPrivacy | void
}
Example code:
import { FinAppProxyHandlerManager, IFinApplet, IFinProxyHandlerItem } from '@finclip/sdk'
class PrivacyHandler extends IFinProxyHandlerItem.PrivacyHandler {
getPrivacyInfo(appId: string, apiServer: string, scope?: string): IFinApplet.IPrivacy | void {
return {
title: 'Custom authorization popup title',
docName: 'Custom privacy agreement document name',
docUrl: 'https://super-apps.ai',
copyWriting: 'Custom authorization popup text, privacy agreement document name is "Custom Privacy Agreement Document Name"'
}
}
}
FinAppProxyHandlerManager.privacyHandler = new PrivacyHandler()
IFinApplet.IPrivacy
| Property | Type | Required | Description |
|---|---|---|---|
| title | String | Yes | Custom privacy authorization popup title |
| copyWriting | String | Yes | Custom privacy authorization popup text, including the custom privacy policy document name |
| docName | String | Yes | Custom privacy policy document name |
| docUrl | String | Yes | Custom privacy policy document link |
# 4. ScopeHandler
Custom permission proxy class
// namespace IFinProxyHandlerItem
export class ScopeHandler {
/**
* Whether to customize the Mini-Program permission settings page
*/
public isAppletCustomizeSettingPage: boolean = false
/**
* Customize the Mini-Program permission settings page
* @param applet
* @param scopes
* @param updateScopes Method to update scopes
* @returns boolean Whether the proxy is implemented; if false, it indicates that the proxy is not implemented and will follow the default logic
*/
public openSettingPage(applet: IFinApplet.IAppletInfo, scopes: IFinApplet.IScope[],
updateScopes: (result: IFinAppProxy.ISettingListParams) => void): boolean
/**
* Register custom permissions
* @param appId
* @param apiServer
* @returns Custom permission list
*/
public getCustomScopes(appId: string, apiServer: string): IFinApplet.IScope[]
/**
* Custom popup, implementation can refer to the example code. It is recommended to implement either this or getCustomPartialView.
* @returns Popup builder
*/
public getCustomView(): (() => void) | void
/**
* Partial customization of the permission popup.
* Different builders can be returned based on appId, apiServer, and scope.
* It is recommended to implement either this or getCustomView.
*
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param scope Current permission identifier
* @returns Popup builder
*/
public getCustomPartialView(appId: string, apiServer: string,
scope: string): IFinAppProxy.ICustomPartialViewBuilder | void
/**
* Whether to hide the built-in permission title and description in the Scope permission popup, default is false, meaning not hidden.
*
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param scope Current permission identifier
* @returns Whether to hide
*/
public isHideTitleAndDescription(appId: string, apiServer: string, scope: string): boolean
/**
* Whether to hide the additional background location permission options in the Scope permission popup, default is false, meaning not hidden.
*
* For background location permissions, there are two extra options in the popup compared to other permissions: 【While using the Mini-Program】 and 【While using the Mini-Program and after leaving】.
*
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param scope Current permission identifier
* @returns Whether to hide
*/
public isHideLocationScopeOption(appId: string, apiServer: string, scope: string): boolean
/**
* Whether to hide the built-in 【Deny】 and 【Allow】 buttons in the Scope permission popup, default is false, meaning not hidden.
* If these two buttons are hidden, it is necessary to implement corresponding buttons in the custom layout within `getCustomPartialView`.
*
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param scope Current permission identifier
* @returns Whether to hide
*/
public isHideButton(appId: string, apiServer: string, scope: string): boolean
/**
* @param api The API name triggered by the Mini-Program
* @param context The context of the current Ability
* @param scopes Permission list, including built-in and custom permissions
* @param callback API callback function; if the user grants permission via callback passing true, subsequent logic will follow the custom API logic, otherwise it will follow the fail logic
* @param params Parameters received by the custom API
* @returns boolean Whether the proxy is implemented; if false, it indicates that the proxy is not implemented and will follow the default permission logic
*/
public onCustomApiInvoke(appId: string, apiServer: string, api: string, context: common.UIAbilityContext,
scopes: IFinApplet.IScope[], callback: (res: boolean) => void, params?: object): boolean
}
Example Code
import { FinAppProxyHandlerManager, IFinApplet, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { promptAction } from '@kit.ArkUI'
import { ISettingRouterParams } from '../../pages/Setting'
import { getFinAppClient } from '../FinAppClient'
import { customView,customPartialView } from './customView'
import { common } from '@kit.AbilityKit'
class ScopeHandler extends IFinProxyHandlerItem.ScopeHandler {
isAppletCustomizeSettingPage = true
openSettingPage(applet: IFinApplet.IAppletInfo, scopes: IFinApplet.IScope[],
updateScopes: (result: IFinAppProxy.ISettingListParams) => void): boolean {
const param: ISettingRouterParams = {
applet,
scopes
}
// Initialize with Navigation, use Navigation to navigate to the authorization management page
getFinAppClient().getEntryInfo().routerState?.pushPath({
name: 'Setting',
param,
onPop: (info) => {
const param = info.result as ISettingRouterParams
updateScopes({
scopes: param.scopes,
applet: param.applet
})
}
})
return true
}
getCustomScopes(appId: string, apiServer: string): IFinApplet.IScope[] {
return [
{
scope: 'idCard',
scopeName: 'ID Card',
title: 'Obtain ID card information',
desc: "Obtain your ID card information for XXXXXX",
scopeStatus: 0
}
]
}
// Implement either this or getCustomPartialView
getCustomView(): (() => void) | void {
return customView
}
// Implement either this or getCustomView
getCustomPartialView(appId: string, apiServer: string, scope: string): void | IFinAppProxy.ICustomPartialViewBuilder {
if (scope === 'scope.userLocation') {
return customPartialView
}
}
isHideTitleAndDescription(appId: string, apiServer: string, scope: string): boolean {
return true
}
isHideLocationScopeOption(appId: string, apiServer: string, scope: string): boolean {
return true
}
isHideButton(appId: string, apiServer: string, scope: string): boolean {
return true
}
onCustomApiInvoke(appId: string, apiServer: string, api: string, context: common.UIAbilityContext,
scopes: IFinApplet.IScope[], callback: (res: boolean) => void, params?: object): boolean {
const scope = scopes.find(i => i.scope === 'idCard')
if (scope?.scopeStatus === 0) {
context.eventHub.emit('showCustomToast', api)
context.eventHub.on('onShowCustomToast', (res: boolean) => {
scope.scopeStatus = res ? 3 : 1
callback(res)
context.eventHub.off('onShowCustomToast')
})
} else {
callback(true)
}
return true
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.scopeHandler = new ScopeHandler()
// customView.ets
import { EPermissionState, IFinApplet, IFinAppProxy } from '@finclip/sdk'
import { common } from '@kit.AbilityKit'
@Builder
export function customView() {
CustomViewComponent()
}
@Component
struct CustomViewComponent {
@State show: boolean = false
private context = getContext(this) as common.UIAbilityContext
aboutToAppear() {
this.context.eventHub.on('showCustomToast', () => {
this.show = true
})
}
handlePermission(res: boolean) {
this.context.eventHub.emit('onShowCustomToast', res)
this.show = false
}
@Builder
toast() {
Stack({ alignContent: Alignment.Bottom }) {
Row() {
}
.height('100%')
.width('100%')
.backgroundColor('rgba(0,0,0,0.5)')
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween }) {
Row() {
Button('Deny').onClick(() => {
this.handlePermission(false)
})
Button('Agree').onClick(() => {
this.handlePermission(true)
})
}
.width('100%')
}
.padding({
top: 24,
left: 18,
right: 18,
bottom: 24
})
.width('100%')
.height(241)
.backgroundColor('#F5F6F6')
.clip(true)
.borderRadius({ topLeft: 16, topRight: 16 })
.zIndex(10)
}
}
build() {
if (this.show) {
this.toast()
}
}
}
@Builder
export function customPartialView(appId: string, apiServer: string, scope: string,
callback: (state: EPermissionState) => void) {
CustomPartialViewComponent({
appId,
apiServer,
scope,
callback
})
}
@Component
struct CustomPartialViewComponent {
@Prop appId: string
@Prop apiServer: string
@Prop scope: string
callback?: (state: EPermissionState) => void
allowState = EPermissionState.ALLOW
private context = getContext(this) as common.UIAbilityContext
aboutToAppear() {
}
@Builder
Selector() {
if (this.scope === 'locationBackground') {
Row() {
Text('Allow while using')
Radio({ value: 'Radio1', group: 'radioGroup' })
.checked(false)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.allowState = EPermissionState.ALLOW_WHEN_USING
}
})
}
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
Row() {
Text('Always allow')
Radio({ value: 'Radio2', group: 'radioGroup' })
.checked(true)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.allowState = EPermissionState.ALLOW
}
})
}
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
}
}
build() {
Column() {
Text(`appId:${this.appId}`)
Text(`apiServer:${this.apiServer}`)
Text(`scope:${this.scope}`)
this.Selector()
Row() {
Button('Allow')
.onClick(() => {
this.callback?.(this.allowState)
})
Button('Deny')
.backgroundColor(Color.Red)
.onClick(() => {
this.callback?.(EPermissionState.DISALLOW)
})
}
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
}
}
}
TIP
The specific value of the scope parameter can be referenced in scope permissions
IFinApplet.IScope
| Property | Type | Required | Description |
|---|---|---|---|
| scope | String | Yes | Permission identifier |
| title | String | Yes | Permission title |
| desc | String | Yes | Permission description |
| scopeStatus | EPermissionState | Yes | Permission status |
| scopeName | String | Yes | Settings page description |
EPermissionState
| Property | Value | Description |
|---|---|---|
| UNSET | 0 | Not set |
| DISALLOW | 1 | Not allowed |
| ALLOW_WHEN_USING | 2 | When using Mini-Program |
| ALLOW | 3 | Allowed |
IFinApplet.IAppletInfo
| Property | Type | Required | Description |
|---|---|---|---|
| appId | string | Yes | Mini-Program ID |
| name | string | Yes | Mini-Program name |
| logo | string | No | Mini-Program logo URL |
IFinAppProxy.ISettingListParams
| Property | Type | Required | Description |
|---|---|---|---|
| applet | IFinApplet.IAppletInfo | Yes | Mini-Program information |
| scopes | IFinApplet.IScope[] | Yes | Permission list |
IFinAppProxy.ICustomPartialViewBuilder
/**
* @param appId - The ID of the Mini-Program.
* @param apiServer - The API server associated with the Mini-Program.
* @param scope - Permission identifier, the name of built-in permissions is consistent with ft.authorize parameters
* @param callback Callback function used to notify permission status
*/
type ICustomPartialViewBuilder = (appId: string, apiServer: string, scope: string, callback: (state: EPermissionState) =>void) => void
# 5.GrayReleaseHandler
Gray release related proxy class
// namespace IFinProxyHandlerItem
export class GrayReleaseHandler {
/**
* This method is called when obtaining Mini-Program information. Custom gray release data can be defined, and the SDK will merge custom data with built-in data for sending. If property names are the same, custom data will be used.
* @param appId
* @param apiServer
* @returns Data to be appended to the gray release configuration
*/
public getGrayExtension(appId: string, apiServer: string): Record<string, string>
}
Example code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
class GrayReleaseHandler extends IFinProxyHandlerItem.GrayReleaseHandler {
getGrayExtension(appId: string, apiServer: string): Record<string, string> {
return {
'customKey': 'customValue',
'xUserId': '130000000'
}
}
}
FinAppProxyHandlerManager.grayReleaseHandler = new GrayReleaseHandler()
# 6.AppletLifeCycleHandler
Mini-Program lifecycle related
// namespace IFinProxyHandlerItem
export class AppletLifeCycleHandler {
/**
* Triggered when the Mini-Program is opened.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onOpen(appId: string, apiServer: string)
/**
* Triggered when the Mini-Program initialization is completed.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onInitCompletion(appId: string, apiServer: string)
/**
* Triggered when the Mini-Program is closed.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onClose(appId: string, apiServer: string)
/**
* Triggered when an error occurs in the Mini-Program.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
* @param code Error code.
* @param message Error message.
*/
public onError(appId: string, apiServer: string, code: string, message: string)
/**
* Triggered when the Mini-Program is ready.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onReady(appId: string, apiServer: string)
/**
* Triggered when the Mini-Program is displayed.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onShow(appId: string, apiServer: string)
/**
* Triggered when the Mini-Program is hidden.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onHide(appId: string, apiServer: string)
/**
* Triggered when the Mini-Program is destroyed.
* @param appId The ID of the Mini-Program.
* @param apiServer The API server associated with the Mini-Program.
*/
public onDestroy(appId: string, apiServer: string)
}
Example code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
import { promptAction } from '@kit.ArkUI'
class AppletLifeCycleProxy extends IFinProxyHandlerItem.AppletLifeCycleHandler {
onOpen(appId: string, apiServer: string) {
this.promptMsg(`${appId} onOpen`)
}
onInitCompletion(appId: string, apiServer: string) {
this.promptMsg(`${appId} onInitCompletion`)
}
onClose(appId: string, apiServer: string) {
this.promptMsg(`${appId} onClose`)
}
onError(appId: string, apiServer: string, code: string, message: string) {
this.promptMsg(`${appId} onError,code:${code},message:${message}`)
}
onReady(appId: string, apiServer: string) {
this.promptMsg(`${appId} onReady`)
}
onShow(appId: string, apiServer: string) {
this.promptMsg(`${appId} onShow`)
}
onHide(appId: string, apiServer: string) {
this.promptMsg(`${appId} onHide`)
}
onDestroy(appId: string, apiServer: string) {
this.promptMsg(`${appId} onDestroy`)
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.appletLifeCycleHandler = new AppletLifeCycleProxy()
# 7.CustomLayoutHandler
Custom layout related proxy class
// namespace IFinProxyHandlerItem
export class CustomLayoutHandler {
/**
* Customize subpackage download error page
* @returns Builder for custom subpackage download error page
*/
public getDownloadSubpackageFileFailedLayout(): ((appId: string, apiServer: string, path: string,
reload: () => void) => void) | void
/**
* Customize loading error page
* @returns Builder for custom loading error page
*/
public getLoadFailedLayout(): ((appId: string, apiServer: string, title: string, label: string) => void) | void
/**
* Triggered when the page is ready, the loading component will be destroyed after this function ends
* @returns
*/
public async onPageLoadingLayoutReady(): Promise<void>
/**
* Triggered when the Mini-Program is ready, the loading page will be destroyed after this function ends
* @returns
*/
public async onLoadingLayoutReady(): Promise<void>
/**
* Customize page loading component
* @returns Builder for custom page loading
*/
public getPageCustomLoadingLayout(): ((appId: string, apiServer: string, path: string) => void) | void
/**
* Get the method for custom loading page layout
* @returns Builder for custom loading page
*/
public getCustomLoadingLayout(): (() => void) | void
/**
* Get the method for custom Toast
* @returns Builder for custom Toast
*/
public getCustomToastLayout(): (() => void) | void
/**
* Get the builder for custom overlay, which will be rendered above the Mini-Program page
* @returns Builder for custom overlay
*/
public getCustomOverlayLayout(): ((appId: string, apiServer: string) => void) | void
/**
* Get the builder for custom subpackage loading Toast
* @returns Builder for custom subpackage loading Toast
*/
public getCustomSubpackageLoadingLayout(): ((appId: string, apiServer: string) => void) | void
}
# 7.1 Custom Subpackage Download Error Page
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
@Builder
export function DownloadSubpackageFileFailedLayout(appId: string, apiServer: string, path: string,
reload: () => void) {
CustomViewComponent({
appId,
apiServer,
path,
reload
})
}
@Component
struct CustomViewComponent {
@Prop appId: string
@Prop apiServer: string
@Prop path: string
reload?: () => void
build() {
Flex({
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center,
direction: FlexDirection.Column
}) {
Column() {
Text('appId: ' + this.appId)
Text('apiServer: ' + this.apiServer)
Text('path: ' + this.path)
Button('Reload').onClick(() => {
this.reload?.()
})
}
}
.backgroundColor(Color.White)
.width('100%')
.height('100%')
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
/**
* Custom subpackage download error page
* @returns Custom subpackage download error page builder
*/
getDownloadSubpackageFileFailedLayout(): ((appId: string, apiServer: string, path: string,
reload: () => void) => void) | void {
return DownloadSubpackageFileFailedLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.2 Custom Load Error Page
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
@Builder
export function LoadFailedLayout(appId: string, apiServer: string, title: string, label: string, code: string) {
CustomViewComponent({
appId,
apiServer,
title,
label,
code
})
}
@Component
struct CustomViewComponent {
@Prop appId: string
@Prop apiServer: string
@Prop title: string
@Prop label: string
@Prop code: string
build() {
Flex({
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center,
direction: FlexDirection.Column
}) {
Column() {
Text('appId: ' + this.appId)
Text('apiServer: ' + this.apiServer)
Text('title: ' + this.title)
Text('label: ' + this.label)
Text('code: ' + this.code)
}
}
.backgroundColor(Color.White)
.width('100%')
.height('100%')
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
getLoadFailedLayout(){
return LoadFailedLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.3 Custom Loading Page
import { FinAppProxyHandlerManager, IFinProxyHandlerItem, IFinAppProxy } from '@finclip/sdk'
@Builder
export function CustomLoadingLayout() {
CustomViewComponent()
}
@Component
struct CustomViewComponent {
@Consume layoutParams: IFinAppProxy.ICustomLoadingLayoutParams = {
appId: '',
apiServer: '',
name: '',
logo: ''
}
build() {
Flex({
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center,
direction: FlexDirection.Column
}) {
Column() {
Text('Custom loading')
Text('appId: ' + this.layoutParams.appId)
Text('apiServer: ' + this.layoutParams.apiServer)
Text('path: ' + this.layoutParams.name)
Image(this.layoutParams.logo)
.width('100%')
.height('100%')
.padding(5)
.border({
width: 0.5,
radius: 30,
color: 'rgba(222,222,222,1)'
})
.draggable(false)
}
}
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.backgroundColor(Color.White)
.width('100%')
.height('100%')
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
onLoadingLayoutReady(): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 200)
})
}
getCustomLoadingLayout(): (() => void) | void {
return CustomLoadingLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.4 Custom Page Loading Page
import { FinAppProxyHandlerManager, IFinProxyHandlerItem, IFinAppProxy } from '@finclip/sdk'
@Builder
export function PageCustomLoadingLayout(appId: string, apiServer: string, path: string) {
CustomViewComponent({
appId,
apiServer,
path,
})
}
@Component
struct CustomViewComponent {
@Prop appId: string
@Prop apiServer: string
@Prop path: string
build() {
Flex({
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center,
direction: FlexDirection.Column
}) {
Column() {
Text('Page custom loading')
Text('appId: ' + this.appId)
Text('apiServer: ' + this.apiServer)
Text('path: ' + this.path)
}
}
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.backgroundColor(Color.White)
.width('100%')
.height('100%')
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
onPageLoadingLayoutReady(): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 200)
})
}
getPageCustomLoadingLayout(): ((appId: string, apiServer: string, path: string) => void) | void {
return PageCustomLoadingLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.5 Custom Toast
import { FinAppProxyHandlerManager, IFinProxyHandlerItem, IFinAppProxy } from '@finclip/sdk'
@Builder
export function CustomToast() {
CustomViewComponent()
}
@Component
struct CustomViewComponent {
@Consume toastInfo: IFinAppProxy.ICustomToastLayoutParams
build() {
this.toastWithMask()
}
@Builder
toastImage() {
if (this.toastInfo.image) {
Image(this.toastInfo.image)
.width(40)
.height(40)
} else if (this.toastInfo.icon) {
if (this.toastInfo.icon === 'loading') {
Text('Loading icon')
}
if (this.toastInfo.icon === 'success') {
Text('Success icon')
}
if (this.toastInfo.icon === 'error') {
Text('Error icon')
}
}
}
@Builder
toast() {
if (this.toastInfo.icon === 'none') {
Column() {
Text(this.toastInfo.title)
.fontSize(14)
.fontColor('rgba(255, 255, 255, 0.9)')
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(2)
.textAlign(TextAlign.Center)
}
.constraintSize({
maxWidth: 200,
minHeight: 48
})
.padding({
left: 12,
right: 12,
top: 14,
bottom: 14
})
// Add a placeholder space to make vertical centering slightly upward
.margin({
bottom: 120
})
.backgroundColor('rgba(0, 0, 0, 0.7)')
.align(Alignment.Center)
.justifyContent(FlexAlign.Center)
.opacity(1)
.borderRadius(10)
.clip(true)
} else {
Column() {
this.toastImage()
Text(this.toastInfo.title)
.fontSize(14)
.fontColor('rgba(255, 255, 255, 0.9)')
.margin({ top: 12 })
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(2)
.textAlign(TextAlign.Center)
}
.width(130)
.height(130)
.padding({
left: 14,
right: 14
})
// Add a placeholder space to make the vertical center slightly upward
.margin({
bottom: 120
})
.backgroundColor('rgba(0, 0, 0, 0.7)')
.align(Alignment.Center)
.justifyContent(FlexAlign.Center)
.opacity(1)
.borderRadius(10)
.clip(true)
}
}
@Builder
toastWithMask() {
Flex({
direction: FlexDirection.Column,
justifyContent: FlexAlign.Center,
alignItems: ItemAlign.Center
}) {
this.toast()
}
.width('100%')
.height('100%')
.backgroundColor('transparent')
// Slightly smaller than modal and actionsheet
.zIndex(110)
.position({
top: 0,
left: 0
})
.hitTestBehavior(this.toastInfo.mask ? HitTestMode.Default : HitTestMode.Transparent)
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
getCustomToastLayout(): (() => void) | void {
return CustomToast
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.6 Custom Overlay
import { FinAppProxyHandlerManager, IFinProxyHandlerItem, IFinAppProxy } from '@finclip/sdk'
@Builder
export function CustomOverlayLayout(appId: string, apiServer: string) {
Column() {
Text('CustomLayout')
Text(appId)
Text(apiServer)
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
getCustomOverlayLayout() {
return CustomOverlayLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
# 7.7 Custom Subpackage Loading Loading
import { FinAppProxyHandlerManager, IFinProxyHandlerItem, IFinAppProxy } from '@finclip/sdk'
@Builder
export function CustomOverlayLayout(appId: string, apiServer: string) {
Column() {
Text('CustomLayout')
Text(appId)
Text(apiServer)
}
}
class CustomLayoutHandler extends IFinProxyHandlerItem.CustomLayoutHandler {
getCustomSubpackageLoadingLayout() {
return CustomOverlayLayout
}
}
FinAppProxyHandlerManager.customLayoutHandler = new CustomLayoutHandler()
IFinAppProxy.ICustomLoadingLayoutParams
| Property | Type | Description |
|---|---|---|
| name | String | Mini-Program name, default is empty when Mini-Program details are not obtained |
| logo | ResourceStr | Mini-Program icon, returns a default icon if Mini-Program details or the icon field in Mini-Program details is empty; developers can choose whether to use it |
| appId | String | Mini-Program appId, default is empty when Mini-Program details are not obtained |
| apiServer | String | Mini-Program apiServer, default is empty when Mini-Program details are not obtained |
# 8.ButtonOpenTypeHandler
The button in the Mini-Program has a series of open-type events. Some behaviors need to be implemented by the Host-App, so corresponding events will also be triggered through proxy methods.
// namespace IFinProxyHandlerItem
export class ButtonOpenTypeHandler {
/**
* When calling the getUserProfile API, this proxy method will be triggered.
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Promise<IFinApplet.IUserProfile | void>
*
*/
public async getUserProfile(appId: string, apiServer: string): Promise<IFinApplet.IUserProfile | void>
/**
* Triggered when calling the getUserInfo API or clicking a Button with open-type attribute as getUserInfo
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Promise<IFinApplet.IUserInfo | void>
*
*/
public async getUserInfo(appId: string, apiServer: string): Promise<IFinApplet.IUserInfo | void>
/**
* Triggered when the user clicks the forward button or a Button with open-type attribute as share
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param forwardInfo Parameters carried during forwarding
* @returns Promise<void>
*
*/
public async forwardAppletWithInfo(appId: string, apiServer: string, forwardInfo: IFinAppProxy.IForwardInfo): Promise<void>
/**
* Triggered when clicking a Button with open-type attribute as getPhoneNumber
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param callback Same as custom API's callback, handled by the host for returning results
* @returns Promise<void>
*
*/
public async getPhoneNumber(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback): Promise<void>
/**
* Triggered when clicking a Button with open-type attribute as launchApp
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param callback Same as custom API's callback, handled by the host for returning results
* @param appParameter Parameters passed to the APP when opening the APP
* @returns Promise<void>
*
*/
public async launchApp(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback, appParameter: string): Promise<void>
/**
* Triggered when clicking a Button with open-type attribute as feedback
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Promise<boolean> Default returns false, returning true indicates that the logic is implemented by the proxy, returning false indicates opening the complaint feedback page in the more menu.
*
*/
public async feedback(appId: string, apiServer: string): Promise<boolean>
/**
* Triggered when clicking a Button with open-type attribute as chooseAvatar
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param callback Same as custom API's callback, handled by the host for returning results
* @returns Promise<void>
*
*/
public async chooseAvatar(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback): Promise<void>
/**
* Triggered when clicking a Button with open-type attribute as contact
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param callback Same as custom API's callback, handled by the host for returning results
* @param sessionFrom Session source
* @param sendMessageTitle Title of the message card in the session
* @param sendMessagePath Path to jump to the Mini-Program when clicking the message card in the session
* @param sendMessageImg Image of the message card in the session
* @param showMessageCard Mini-Program information
* @returns Promise<void>
*/
public async contact(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback, sessionFrom: string, sendMessageTitle: string, sendMessagePath: string, sendMessageImg: string, showMessageCard: boolean): Promise<void>
}
Example code
import { FinAppProxyHandlerManager, IFinApplet, IFinProxyHandlerItem } from '@finclip/sdk'
class ButtonOpenTypeHandler extends IFinProxyHandlerItem.ButtonOpenTypeHandler {
async getUserProfile(appId: string, apiServer: string): Promise<IFinApplet.IUserProfile | void> {
return {
nickName: "Nickname",
avatarUrl: "Avatar URL",
gender: "Gender",
province: "Province",
city: "City",
country: "Country",
}
}
async getUserInfo(appId: string, apiServer: string): Promise<IFinApplet.IUserInfo | void> {
return {
nickName: "Nickname",
avatarUrl: "Avatar URL",
gender: "Gender",
province: "Province",
city: "City",
country: "Country",
}
}
async forwardAppletWithInfo(appId: string, apiServer: string, forwardInfo: IFinAppProxy.IForwardInfo): Promise<void> {
this.promptMsg(JSON.stringify(forwardInfo))
}
async feedback(appId: string, apiServer: string): Promise<boolean> {
this.promptMsg(`Feedback triggered`)
return false
}
async chooseAvatar(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback) {
this.promptMsg(`chooseAvatar triggered`)
callback.onSuccess({})
}
async launchApp(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback,
appParameter: string): Promise<void> {
this.promptMsg(`launchApp triggered, appParameter${appParameter}`)
callback.onSuccess({})
}
async getPhoneNumber(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback): Promise<void> {
this.promptMsg(`getPhoneNumber triggered`)
const res: IButtonOpenTypeHandler.IGetPhoneNumberRes = {
phone: 123456789
}
callback.onSuccess(res)
}
async contact(appId: string, apiServer: string, callback: IApiManager.IInvokeCallback, sessionFrom: string,
sendMessageTitle: string, sendMessagePath: string, sendMessageImage: string, showMessageCard: boolean) {
this.promptMsg(`contact triggered\n sessionFrom:${sessionFrom}\n sendMessageTitle:${sendMessageTitle}\n sendMessagePath:${sendMessagePath}\n sendMessageImage:${sendMessageImage}\n showMessageCard:${showMessageCard}`)
callback.onSuccess({})
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.buttonOpenTypeHandler = new ButtonOpenTypeHandler()
IFinApplet.IUserInfo
| Property | Type |
|---|---|
| nickName | String |
| avatarUrl | String |
| gender | String |
| province | String |
| city | String |
| country | String |
IFinApplet.IUserProfile
type IUserInfo = string | number | boolean | null | Serializable[] | { [key: string]: Serializable }
# 9.onAppBackPressHandler
Swipe Delegate
// namespace IFinProxyHandlerItem
export class onAppBackPressHandler {
/**
* Triggered when the user swipes from the edge
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param path The triggered Mini-Program page path
* @returns Return true indicates that the Host-App handles it by itself, return false indicates that after the Host-App handles it, the subsequent default operation will still be executed
*/
public onBackPress(appId: string, apiServer: string, path?:string): boolean | void
}
Sample Code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
import { promptAction } from '@kit.ArkUI'
class onAppBackPressHandler extends IFinProxyHandlerItem.onAppBackPressHandler {
onBackPress(appId: string, apiServer: string) {
// Only effective for Mini-Programs
// Returning true indicates that the Host-App handles it by itself
// Returning false indicates that after the Host-App handles it, the subsequent default operation will still be executed
this.promptMsg(`Swipe delegate triggered`)
return false
}
private promptMsg(message: string) {
promptAction.showToast({
message
})
}
}
FinAppProxyHandlerManager.onAppBackPressHandler = new onAppBackPressHandler()
# 10. LogHandler
Log Proxy Class
// namespace IFinProxyHandlerItem
export class LogHandler {
/**
* Whether to enable console output, default is false
*/
public isConsoleLog: boolean = false;
/**
* Whether to write to file, default is true
*/
public writeFile: boolean = true;
/**
* Set log file retention time in seconds (default 10 days, at least 1 day)
*/
public logFileAliveDuration: number = 60 * 60 * 24 * 10
/**
* Full sandbox path for log output
* Default path /data/app/el2/100/base/package name/haps/entry/files/Applet/logs
*/
public logDir?: string
/**
* This method will be executed when log is triggered. If you want to handle log files yourself, you can set writeFile to false and then process the log content in this method
*/
public onLog(level: IFinAppConfig.ILogLevel, log: string)
}
Sample Code
import { FinAppProxyHandlerManager, IFinAppConfig, IFinProxyHandlerItem } from '@finclip/sdk';
class LogHandler extends IFinProxyHandlerItem.LogHandler {
isConsoleLog: boolean = true;
writeFile: boolean = true;
onLog(level: IFinAppConfig.ILogLevel, log: string): void {
console.log(`level:${level},log:${log}`)
}
}
FinAppProxyHandlerManager.logHandler = new LogHandler()
# 11. WatermarkHandler
Watermark Proxy Class
// namespace IFinProxyHandlerItem
class WatermarkHandler {
/**
* Get watermark builder
* @returns Watermark builder
*/
public getWatermarkLayout(): ((appId: string, apiServer: string) => void) | void {
}
}
Sample Code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk';
@Component
struct Watermark {
@Prop appId: string
@Prop apiServer: string
watermarkWidth: number = 120;
watermarkHeight: number = 120;
watermarkText: string = this.getWatermarkText();
rotationAngle: number = -30;
fillColor: string | number | CanvasGradient | CanvasPattern = '#10000000';
font: string = '16vp';
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
draw() {
this.context.fillStyle = this.fillColor;
this.context.font = this.font;
const colCount = Math.ceil(this.context.width / this.watermarkWidth);
const rowCount = Math.ceil(this.context.height / this.watermarkHeight);
for (let col = 0; col <= colCount; col++) {
let row = 0;
for (; row <= rowCount; row++) {
const angle = this.rotationAngle * Math.PI / 180;
this.context.rotate(angle);
const positionX = this.rotationAngle > 0 ? this.watermarkHeight * Math.tan(angle) : 0;
const positionY = this.rotationAngle > 0 ? 0 : this.watermarkWidth * Math.tan(-angle);
this.context.fillText(this.watermarkText, positionX, positionY);
this.context.rotate(-angle);
this.context.translate(0, this.watermarkHeight);
}
this.context.translate(0, -this.watermarkHeight * row);
this.context.translate(this.watermarkWidth, 0);
}
}
getWatermarkText() {
return `finclip--${this.appId}`
}
build() {
Canvas(this.context)
.width('100%')
.height('100%')
.hitTestBehavior(HitTestMode.Transparent)
.onReady(() => this.draw())
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP])
}
}
@Builder
function watermarkBuilder(appId: string, apiServer: string) {
Watermark({
appId,
apiServer
})
}
class WatermarkHandler extends IFinProxyHandlerItem.WatermarkHandler {
public getWatermarkLayout(): ((appId: string, apiServer: string) => void) | void {
return watermarkBuilder
}
}
FinAppProxyHandlerManager.watermarkHandler = new WatermarkHandler()
# 12. AppletTraceHandler
Mini-Program Traceable Proxy Class
export class AppletTraceHandler {
/**
* Request user authorization
* @returns Returns the authorization result
*/
public async requestUserAuthorization(): Promise<boolean> {
return true
}
}
Sample Code
import { FinAppProxyHandlerManager, IFinAppConfig, IFinProxyHandlerItem } from '@finclip/sdk';
import { promptAction } from '@kit.ArkUI';
class AppletTraceHandler extends IFinProxyHandlerItem.AppletTraceHandler {
requestUserAuthorization(): Promise<boolean> {
return new Promise((resolve, reject)=>{
promptAction.showDialog({
title: 'Enable recording?',
buttons: [
{
text: 'Confirm',
color: '#409EFF'
},
{
text: 'Cancel',
color: '#000000'
}
]
}).then(data => {
resolve(data.index !== 1)
})
})
}
}
FinAppProxyHandlerManager.appletTraceHandler = new AppletTraceHandler()
# 13. AppletWebViewLoadHandler
web-view Component Loading H5 Link Proxy
class AppletWebViewLoadHandler {
/**
* Host-App controls whether webview can load H5 links
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @returns Return true indicates allowing loading, return false indicates rejecting loading, still execute subsequent default operations
*/
public webviewCanLoadUrl(appId: string, apiServer: string, url: string): Promise<boolean>
/**
* Host-App handles webview onPermissionRequest
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param event Parameters returned by system onPermissionRequest
* @returns
*/
public onPermissionRequest(appId: string, apiServer: string, event: OnPermissionRequestEvent)
}
Sample Code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk'
import { promptAction } from '@kit.ArkUI'
class AppletWebViewLoadHandler extends IFinProxyHandlerItem.AppletWebViewLoadHandler {
public async webviewCanLoadUrl(appId: string, apiServer: string, url: string): Promise<boolean> {
try {
const res = await promptAction.showActionMenu({
title: `load url:${url}`,
buttons: [
{
text: 'Allow',
color: '#409EFF'
},
{
text: 'Deny',
color: '#ff0000'
},
]
})
if (res.index === 0) {
return true
} else {
return false
}
} catch (e) {
}
return true
}
public onPermissionRequest(appId: string, apiServer: string, event: OnPermissionRequestEvent) {
// Handle webview permission events based on business requirements
}
}
FinAppProxyHandlerManager.appletWebViewLoadHandler = new AppletWebViewLoadHandler()
# 14. XComponentHandler
Custom Component Proxy
class XComponentHandler {
/**
* Get XComponent builder
* @returns XComponent builder
*/
public getXComponentLayout(): ((appId: string, apiServer: string, controller: IFinAppProxy.XComponentController) => void) | void
}
Sample Code
import { FinAppProxyHandlerManager, IApiManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
@Component
struct XComponentProxy {
@Prop appId: string
@Prop apiServer: string
controller: IFinAppProxy.XComponentController = new IFinAppProxy.XComponentController()
@State tag: string = ''
@State componentId: string = ''
@State data: string = ''
@State domId: string = ''
@State xComponentWidth: number = 0
@State xComponentHeight: number = 0
@State count: number = 0
scrollerForScroll: Scroller = new Scroller()
aboutToAppear(): void {
// Listen for data update events
this.controller.on('valueUpdated', () => {
this.onValueUpdated()
})
// Listen for events sent by the Mini-Program through context, and custom data can be returned to the Mini-Program
this.controller.handleXComponentEvent = async (eventName: string, params: object) => {
let res: IApiManager.IInvokeBaseResponse = { errMsg: '' }
this.count++
switch (eventName) {
case 'appletEvent':
res.data = `fromArkTs,data:${JSON.stringify(params)}`
break
}
return res
}
this.onValueUpdated()
}
onValueUpdated() {
this.tag = this.controller.getTag() // The tag attribute of the Mini-Program component
this.componentId = this.controller.getId() // The unique ID of the native component
this.data = JSON.stringify(this.controller.getData()) // The data attribute of the Mini-Program component
this.xComponentWidth = this.controller.getWidth() // The width of the native component container
this.xComponentHeight = this.controller.getHeight() // The height of the native component container
this.domId = this.controller.getDomId() // The id attribute of the Mini-Program component
}
build() {
Scroll(this.scrollerForScroll) {
Column() {
Text('XComponent')
Text(`appletEvent count:${this.count}`)
Text(`id:${this.componentId}`)
Text(`domId:${this.domId}`)
Text(`tag:${this.tag}`)
Text(`data:${this.data}`)
Text(`xComponentWidth:${this.xComponentWidth}`)
Text(`xComponentHeight:${this.xComponentHeight}`)
Button('send onTestEvent').onClick(() => {
// Events can be sent to the Mini-Program via emitToApplet, which listens on the Mini-Program side using context.on
this.controller.emitToApplet('onTestEvent', { from: 'arkts' } as ESObject)
})
}
.backgroundColor(Color.Red)
.width(this.xComponentWidth)
.height(this.xComponentHeight)
}
// By default, native components consume gesture events internally, meaning that scrolling within the native component will not scroll the page. To enable page scrolling within the native component, use Scroll with the onScrollFrameBegin method.
.onScrollFrameBegin((offset: number, state: ScrollState) => {
this.controller.onScrollFrameBegin(offset, state, this.scrollerForScroll)
return { offsetRemain: 0 }
})
.width(this.xComponentWidth) // According to the same-layer rendering specification, the width of the root component must match the width of the Mini-Program container component; otherwise, rendering issues may occur.
.height(this.xComponentHeight) // According to the same-layer rendering specification, the height of the root component must match the height of the Mini-Program container component; otherwise, rendering issues may occur.
}
}
@Builder
function XComponentProxyBuilder(appId: string, apiServer: string, controller: IFinAppProxy.XComponentController) {
XComponentProxy({
appId,
apiServer,
controller
})
}
class XComponentHandler extends IFinProxyHandlerItem.XComponentHandler {
public getXComponentLayout(): void | ((appId: string, apiServer: string,
controller: IFinAppProxy.XComponentController) => void) {
return XComponentProxyBuilder
}
}
FinAppProxyHandlerManager.xComponentHandler = new XComponentHandler()
# 15. AppletCustomJSInjectionHandler
Proxy for loading external JS files
class AppletCustomJSInjectionHandler {
/**
* Get the JS string to be loaded
* @param context
* @param appId
* @param apiServer
* @returns Array of JS strings
*/
public async getJSContentList(context: common.UIAbilityContext, appId: string,
apiServer: string): Promise<string[]>
}
Sample Code
class AppletCustomJSInjectionProxy extends IFinProxyHandlerItem.AppletCustomJSInjectionHandler {
public async getJSContentList(context: common.UIAbilityContext, appId: string, apiServer: string): Promise<string[]> {
return ['console.log("inject success")']
}
}
FinAppProxyHandlerManager.appletCustomJSInjectionHandler = new AppletCustomJSInjectionProxy()
# 16. ACLPermissionHandler
Proxy involving ACL permissions. If the certificate does not have ACL permissions, this proxy class can be used to override and execute the corresponding methods.
class ACLPermissionHandler {
/**
* Method to save images or videos to the album. Starting from version 1.3.3, it will throw an error by default. The app needs to implement this method itself or integrate @finclip/album-sdk.
* @param type The media type to be saved
* @param realPath The full path of the file
* @param context
* @returns No return value is needed upon success. If it fails, please reject with the corresponding error message, such as reject('auth deny').
*/
public saveMediaToPhotosAlbum(type: 'image' | 'video', realPath: string,context: common.UIAbilityContext): Promise<void>
}
Sample Code
import { FinAppProxyHandlerManager, IFinProxyHandlerItem } from '@finclip/sdk';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
class ACLPermissionHandler extends IFinProxyHandlerItem.ACLPermissionHandler {
// Here, a popup-based authorization method is used to complete the saving logic. This can be implemented according to specific business logic.
public saveMediaToPhotosAlbum(type: 'image' | 'video', realPath: string,
context: common.UIAbilityContext): Promise<void> {
return new Promise((resolve, reject) => {
const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
// Specify the URI of the image in the app sandbox to be saved to the media library.
let srcFileUri = realPath
let srcFileUris: Array<string> = [
realPath
];
// Specify the creation options for the photos to be saved, including file extension and photo type. Title and photo subtype are optional.
const photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [];
if (type === 'image') {
photoCreationConfigs.push({
fileNameExtension: this.getFileExtension(srcFileUri),
photoType: photoAccessHelper.PhotoType.IMAGE,
})
} else if (type === 'video') {
photoCreationConfigs.push({
fileNameExtension: this.getFileExtension(srcFileUri),
photoType: photoAccessHelper.PhotoType.VIDEO,
})
}
// Use a popup-based authorization method to obtain the target URI in the media library.
phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs).then((desFileUris) => {
if (!desFileUris.length) {
reject('User canceled')
}
try {
// Write the content of the photo from the app sandbox to the target URI in the media library.
let desFile: fileIo.File = fileIo.openSync(desFileUris[0], fileIo.OpenMode.WRITE_ONLY);
let srcFile: fileIo.File = fileIo.openSync(srcFileUri, fileIo.OpenMode.READ_ONLY);
fileIo.copyFileSync(srcFile.fd, desFile.fd);
fileIo.closeSync(srcFile);
fileIo.closeSync(desFile);
resolve()
} catch (e) {
reject(e.message)
}
}).catch((e: BusinessError) => {
reject(e.message)
})
})
}
private getFileExtension(filePath: string): string {
if (!filePath) {
return ''
}
// Extract the filename from the file path
const fileName = filePath.split('/').pop();
// Extract the file extension from the filename
const fileExtension = fileName!.split('.').pop();
return fileExtension || '';
}
}
FinAppProxyHandlerManager.ACLPermissionHandler = new ACLPermissionHandler()
# 17. ShareAppletHandler
Starting from version 1.3.6, a "Share" button will be added to the Mini-Program's "More" menu (the hideShareAppletMenu in uiConfig needs to be set to false for the share button to appear in the "More" menu). The ShareSDK can be used with simple configuration to implement the Mini-Program sharing feature, or you can implement the ShareAppletHandler interface yourself to achieve the corresponding functionality.
/**
* Sharing Delegate
*/
export class ShareAppletHandler {
/**
* Triggered when the share button in the more panel is clicked
* @param context UIAbilityContext
* @param appInfo Mini-Program information
* @param appletPagePath Full current page path of the Mini-Program, e.g., pages/index/index?a=b
* @returns
*/
public onShareApplet(context: common.UIAbilityContext, appInfo: IFinApplet.IAppletInfo, appletPagePath: string)
/**
* Get the builder for the sharing interface; if not needed, this method can remain unimplemented
* @returns
*/
public getShareLayout(): ((appId: string, apiServer: string) => void) | void
}
Sample Code
import { FinAppProxyHandlerManager, IFinApplet, IFinProxyHandlerItem } from '@finclip/sdk';
import { common } from '@kit.AbilityKit';
class ShareController {
static instanceMap: Map<string, ShareController> = new Map()
appId: string
apiServer: string
uiContext?: UIContext
appInfo?: IFinApplet.IAppletInfo
private context: common.UIAbilityContext
constructor(appId: string, apiServer: string, context: common.UIAbilityContext) {
this.appId = appId
this.apiServer = apiServer
this.context = context
}
static getInstance(appId: string, apiServer: string, context: common.UIAbilityContext) {
const key = `${appId}__${apiServer}`
let instance = ShareController.instanceMap.get(key)
if (!instance) {
instance = new ShareController(appId, apiServer, context)
ShareController.instanceMap.set(key, instance)
}
return instance
}
onShareApplet: (appInfo: IFinApplet.IAppletInfo, appletPagePath: string) => void = () => {
}
}
@Component
struct ShareToast {
@Prop appId: string
@Prop apiServer: string
@State showShareMenu: boolean = false
@State appletPagePath: string = ''
uiContext = this.getUIContext()
context = this.uiContext.getHostContext() as common.UIAbilityContext
shareController: ShareController = ShareController.getInstance(this.appId, this.apiServer, this.context)
aboutToAppear(): void {
this.shareController.onShareApplet = (appInfo, path) => {
this.onToggleShareMenus(appInfo, path)
}
}
onToggleShareMenus(appInfo: IFinApplet.IAppletInfo, appletPagePath: string) {
this.shareController.appInfo = appInfo
this.appletPagePath = appletPagePath
this.toggleShareMenus()
}
toggleShareMenus() {
this.showShareMenu = !this.showShareMenu
}
@Builder
previewBuilder() {
Column() {
Text(`appId:${this.appId}`)
Text(`apiServer:${this.apiServer}`)
Text(`name:${this.shareController.appInfo?.name}`)
Text(`appletPagePath:${this.appletPagePath}`)
}
.backgroundColor(Color.White)
}
@Builder
share() {
Stack() {
Row() {
}
.width('100%')
.height('100%')
.backgroundColor('#6a000000')
.onClick(() => {
this.toggleShareMenus()
})
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
Column({}) {
this.previewBuilder()
}
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.transition(
TransitionEffect.move(TransitionEdge.BOTTOM).animation({
duration: 150
})
)
.zIndex(999)
.width('100%')
.border({
radius: {
topLeft: 12,
topRight: 12
}
})
.clip(true)
}
.width('100%')
}
build() {
if (this.showShareMenu) {
this.share()
}
}
}
@Builder
function shareToastBuilder(appId: string, apiServer: string) {
ShareToast({
appId,
apiServer
})
}
class ShareAppletHandler extends IFinProxyHandlerItem.ShareAppletHandler {
public onShareApplet(context: common.UIAbilityContext, appInfo: IFinApplet.IAppletInfo,
appletPagePath: string): void {
const instance = ShareController.getInstance(appInfo.appId, appInfo.apiServer, context)
instance.onShareApplet(appInfo, appletPagePath)
}
public getShareLayout(): void | ((appId: string, apiServer: string) => void) {
return shareToastBuilder
}
}
FinAppProxyHandlerManager.shareAppletHandler = new ShareAppletHandler()
# 18.AppletInteractionHandler
/**
* Long Press Delegate
*/
export class AppletInteractionHandler {
/**
* Triggered when media components like previewMedia, previewImage, image are long-pressed
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param uiContext context
* @param mediaInfo Media data that triggered the event, including media type and media address
* @returns boolean If the delegate is implemented, return true to indicate that the long press event is handled externally; if false, the SDK will continue handling the long press event internally.
*/
public async mediaLongPressed(appId: string, apiServer: string, uiContext: UIContext, mediaInfo: IFinAppProxy.FinMediaInfo): Promise<boolean>
/**
* Triggered when the text component is long-pressed
* @param appId Mini-Program id
* @param apiServer Mini-Program apiServer
* @param uiContext context
* @param text Selected text
* @returns boolean If the delegate is implemented, return true to indicate that the long press event is handled externally; if false, the SDK will continue handling the long press event internally.
*/
public async textLongPressed(appId: string, apiServer: string, uiContext: UIContext, text: string): Promise<boolean>
}
Sample Code
import { FinAppProxyHandlerManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk';
class AppletInteractionHandler extends IFinProxyHandlerItem.AppletInteractionHandler {
public async mediaLongPressed(appId: string, apiServer: string,
uiContext: UIContext, mediaInfo: IFinAppProxy.FinMediaInfo): Promise<boolean> {
uiContext.getPromptAction().showToast({
message: `mediaLongPressed:${JSON.stringify(mediaInfo)}`
})
return true
}
public async textLongPressed(appId: string, apiServer: string, uiContext: UIContext,
text: string): Promise<boolean> {
uiContext.getPromptAction().showToast({
message: `textLongPressed:${text}`
})
return true
}
}
FinAppProxyHandlerManager.appletInteractionHandler = new AppletInteractionHandler()
# 19. AppletNetWorkRequestHandler
The implementation class for network proxy, used to take over the three types of network capabilities in Mini-Programs: request, uploadFile, and downloadFile.
# 19.1 Proxy Management Method
Network proxies are managed uniformly through FinAppProxyHandlerManager.appletNetWorkRequestHandler.
import { FinAppProxyHandlerManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { http } from '@kit.NetworkKit'
import { common } from '@kit.AbilityKit'
class AppletNetWorkRequestProxy extends IFinProxyHandlerItem.AppletNetWorkRequestHandler {
/**
* Take over regular requests.
* @param appId The appId of the Mini-Program.
* @param apiServer The server address corresponding to the Mini-Program.
* @param context The context object of the UIAbility.
* @param params Normalized parameters for regular requests.
* @param controller The controller for the request task, used to pass back headers, data, and final results.
* @returns Promise<boolean> Return true to indicate that the Host-App takes over the subsequent lifecycle of the request.
*/
public async request(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
params: IFinAppProxy.IAppletRequestRequest,
controller: IFinAppProxy.IAppletRequestTaskController
): Promise<boolean>
/**
* Take over file uploads.
* @param appId The appId of the Mini-Program.
* @param apiServer The server address corresponding to the Mini-Program.
* @param context The context object of the UIAbility.
* @param params Normalized parameters for file uploads.
* @param controller The controller for the upload task, used to pass back progress, headers, and final results.
* @returns Promise<boolean> Return true to indicate that the Host-App takes over the subsequent lifecycle of the upload.
*/
public async uploadFile(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
params: IFinAppProxy.IAppletUploadFileRequest,
controller: IFinAppProxy.IAppletUploadTaskController
): Promise<boolean>
/**
* Take over file downloads.
* @param appId The appId of the Mini-Program.
* @param apiServer The server address corresponding to the Mini-Program.
* @param context The context object of the UIAbility.
* @param params Normalized parameters for file downloads.
* @param controller The controller for the download task, used to pass back headers and final results.
* @returns Promise<boolean> Return true to indicate that the Host-App takes over the subsequent lifecycle of the download.
*/
public async downloadFile(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
params: IFinAppProxy.IAppletDownloadFileRequest,
controller: IFinAppProxy.IAppletDownloadTaskController
): Promise<boolean>
}
# 19.2 Controller Agreement
The network proxy method receives a controller, through which the host passes the result back to the SDK. The meanings of the controller methods are as follows:
| Method | Function |
|---|---|
registerAbort(handler) | Registers an abort callback, which is executed when the SDK triggers taskAbort, timeout, or destruction |
emitHeaders(statusCode?, header, cookies) | Passes back response headers for the SDK to dispatch the request.onTaskHeadersReceived event. In chunked scenarios, undefined can be passed first, and the status code can be finalized later via success |
emitProgress(processedBytes, totalBytes) | Passes back upload or download progress for the SDK to dispatch the request.onTaskProgressUpdate event |
emitDataReceived(data) | Passes back stream data chunks of the request for the SDK to dispatch the request.onTaskDataReceived event |
success(payload) | Passes back successful results, allowing the SDK to complete the final Mini-Program-side callback |
fail(errMsg) | Passes back failure results, causing the SDK to terminate the current network task in a failed state |
The invocation timing of emitHeaders aligns with the reference implementation:
- In non-
chunkedscenarios, obtain the full response first, then callemitHeaders(responseCode, header, cookies), followed bysuccess(...). - In
chunkedscenarios, callemitHeaders(undefined, header, cookies)within theheadersReceivecallback, and finalize withsuccess(...)after the request ends.
The following describes the payload fields corresponding to request:
| Field | Type | Description |
|---|---|---|
statusCode | Number | Response status code |
header | Record<string, string> | Response headers |
cookies | String[] | List of cookies parsed from the response headers |
data | String | Object | ArrayBuffer | Response body content |
The following describes the payload fields corresponding to uploadFile:
| Field | Type | Description |
|---|---|---|
statusCode | Number | Response status code |
header | Record<string, string> | Response headers |
cookies | String[] | List of cookies parsed from the response headers |
data | String | ArrayBuffer | Response body content |
contentType | String | Response body content type |
The following describes the payload fields corresponding to downloadFile:
| Field | Type | Description |
|---|---|---|
statusCode | Number | Response status code |
header | Record<string, string> | Response headers |
cookies | String[] | List of cookies parsed from the response headers |
# 19.3 Full Version
Complete examples for request, uploadFile, and downloadFile are unified into a single section, directly referencing the full implementation in the Host-App. This version includes task lifecycle, multipart boundary assembly, download persistence, header/cookies normalization, and exception handling.
class AppletNetWorkRequestProxy extends IFinProxyHandlerItem.AppletNetWorkRequestHandler {
/**
* request proxy; returning true indicates that the Host-App takes over subsequent task lifecycle management
*/
public async request(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletRequestRequest,
controller: IFinAppProxy.IAppletRequestTaskController): Promise<boolean> {
// First, prepare the underlying httpRequest configuration based on the normalized parameters from the SDK.
const httpRequest = http.createHttp()
const timeout = params.timeout > 0 ? params.timeout : 60000
const method = (params.method || 'GET').toUpperCase() as http.RequestMethod
const requestHeader = this.cloneRequestHeader(params.header)
const expectDataType =
params.responseType === 'arraybuffer' ? http.HttpDataType.ARRAY_BUFFER : http.HttpDataType.STRING
let requestData = params.data
if (method === http.RequestMethod.GET) {
requestData = undefined
}
let isFinished: boolean = false
let isAborted: boolean = false
let isHeaderEmitted: boolean = false
let responseCode: number = 200
const responseHeader: Record<string, string> = {}
const responseCookies: string[] = []
const destroyHttpRequest = () => {
try {
httpRequest.destroy()
} catch (e) {
}
}
const emitHeadersIfNeeded = () => {
if (isHeaderEmitted) {
return
}
// In non-chunked scenarios, headers are emitted before success to ensure protocol integrity even if the Host-App does not explicitly dispatch them.
controller.emitHeaders(responseCode, responseHeader, responseCookies)
isHeaderEmitted = true
}
const emitHeadersImmediately = () => {
if (isHeaderEmitted) {
return
}
// In chunked scenarios, headers must be notified to the JS side as soon as they are received to maintain consistency with the SDK's default implementation.
controller.emitHeaders(undefined, responseHeader, responseCookies)
isHeaderEmitted = true
}
controller.registerAbort(() => {
if (isFinished || isAborted) {
return
}
// When the request task is aborted by the SDK, only the underlying request is terminated, and the final state is managed by the SDK.
isAborted = true
destroyHttpRequest()
})
try {
if (params.enableChunked) {
// In chunked mode, headers and data are continuously pushed to the SDK controller as streaming events.
httpRequest.on("headersReceive", (rawHeaders: Object) => {
this.appendResponseHeaders(rawHeaders as Record<string, string | string[]>, responseHeader, responseCookies)
emitHeadersImmediately()
});
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
if (!isFinished && !isAborted) {
controller.emitDataReceived(data)
}
})
responseCode = await httpRequest.requestInStream(params.url, {
method,
header: requestHeader,
extraData: requestData,
expectDataType: http.HttpDataType.ARRAY_BUFFER,
readTimeout: timeout,
connectTimeout: timeout,
})
if (!isAborted) {
// After chunked completion, only the final state is patched, without reassembling the body, as body chunks have already been progressively reported in dataReceive.
isFinished = true
emitHeadersIfNeeded()
controller.success({
statusCode: responseCode,
header: responseHeader,
cookies: responseCookies,
data: '',
})
}
} else {
const response = await httpRequest.request(params.url, {
method,
header: requestHeader,
extraData: requestData,
expectDataType,
readTimeout: timeout,
connectTimeout: timeout,
})
if (!isAborted) {
// In non-chunked mode, after obtaining the full response, headers and success are pushed back at once.
isFinished = true
this.appendResponseHeaders(response.header as Record<string, string | string[]>, responseHeader,
responseCookies)
this.appendResponseCookie(response.cookies, responseCookies)
emitHeadersIfNeeded()
controller.success({
statusCode: response.responseCode as number,
header: responseHeader,
cookies: responseCookies,
data: response.result,
})
}
}
} catch (e) {
if (!isAborted) {
isFinished = true
controller.fail(e.message)
}
} finally {
destroyHttpRequest()
}
return true
}
/**
* uploadFile proxy; returning true indicates that the Host-App takes over subsequent task lifecycle management
*/
public async uploadFile(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletUploadFileRequest,
controller: IFinAppProxy.IAppletUploadTaskController): Promise<boolean> {
// The default upload implementation constructs a multipart request entirely based on the input parameters, no longer relying on old Boolean short-circuit logic.
const httpRequest = http.createHttp()
const timeout = params.timeout > 0 ? params.timeout : 60000
const boundary = `----FinClipBoundary${Date.now()}`
const fileName = params.filePath.split('/').pop() || 'file'
const contentType = this.getUploadContentType(fileName)
// The Host-App's default upload implementation still manually assembles the body as multipart/form-data to ensure consistency with the Mini-Program uploadFile semantics.
const bodyContent =
this.buildUploadBody(boundary, params.name, fileName, this.readUploadFileBuffer(params.filePath),
contentType, params.formData)
const requestHeader = this.cloneRequestHeader(params.header)
// Content-Type and Content-Length are uniformly overridden by the SDK to avoid mismatched headers from the Host-App.
this.setRequestHeader(requestHeader, 'Content-Type', `multipart/form-data; boundary=${boundary}`)
this.setRequestHeader(requestHeader, 'Content-Length', `${bodyContent.byteLength}`)
let isFinished: boolean = false
let isAborted: boolean = false
const destroyHttpRequest = () => {
try {
httpRequest.destroy()
} catch (e) {
}
}
controller.registerAbort(() => {
if (isFinished || isAborted) {
return
}
// When the upload task is aborted by the SDK, only the underlying request is terminated here, while the final state remains controlled by the SDK.
isAborted = true
destroyHttpRequest()
})
try {
// Progress during the upload process is directly pushed back to the SDK controller by the underlying httpRequest.
httpRequest.on('dataSendProgress', (progress: http.DataSendProgressInfo) => {
if (!isFinished && !isAborted) {
controller.emitProgress(progress.sendSize, progress.totalSize)
}
})
const response = await httpRequest.request(params.url, {
method: http.RequestMethod.POST,
header: requestHeader,
expectDataType: http.HttpDataType.ARRAY_BUFFER,
readTimeout: timeout,
connectTimeout: timeout,
extraData: bodyContent
})
if (isAborted) {
return true
}
// After a successful upload, normalize the response headers, cookies, and body, then pass them to the SDK for final handling.
isFinished = true
const responseHeader: Record<string, string> = {}
const responseCookies: string[] = []
this.appendResponseHeaders(response.header as Record<string, string | string[]>, responseHeader,
responseCookies)
this.appendResponseCookie(response.cookies, responseCookies)
controller.emitHeaders(response.responseCode as number, responseHeader, responseCookies)
controller.success({
statusCode: response.responseCode as number,
header: responseHeader,
cookies: responseCookies,
data: response.result instanceof ArrayBuffer ? response.result :
(typeof response.result === 'string' ? response.result : JSON.stringify(response.result)),
contentType: this.getHeaderValue(responseHeader, 'content-type')
})
} catch (e) {
if (!isAborted) {
isFinished = true
controller.fail(e.message)
}
} finally {
destroyHttpRequest()
}
return true
}
/**
* downloadFile proxy; returning true indicates that the Host-App takes over subsequent task lifecycle management
*/
public async downloadFile(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletDownloadFileRequest,
controller: IFinAppProxy.IAppletDownloadTaskController): Promise<boolean> {
// The default download implementation is responsible only for actual streaming and persistence; the final filePath/tempFilePath is still determined by the SDK side.
const httpRequest = http.createHttp()
const targetDir = params.targetAbsPath.split('/').slice(0, -1).join('/')
const timeout = params.timeout > 0 ? params.timeout : 60000
const requestHeader = this.cloneRequestHeader(params.header)
let targetFile: fs.File | undefined = undefined
let responseCode: number = 200
const responseHeader: Record<string, string> = {}
const responseCookies: string[] = []
let isHeaderEmitted: boolean = false
let isResponseCodeReady: boolean = false
let isFinished: boolean = false
let isAborted: boolean = false
const closeTargetFile = () => {
if (!targetFile) {
return
}
try {
fs.closeSync(targetFile.fd)
} catch (e) {
}
targetFile = undefined
}
const destroyHttpRequest = () => {
try {
httpRequest.destroy()
} catch (e) {
}
}
const tryEmitHeaders = () => {
if (isHeaderEmitted || !isResponseCodeReady) {
return
}
// Headers are only dispatched when the status code is available to avoid disguising error states as 200.
controller.emitHeaders(responseCode, responseHeader, responseCookies)
isHeaderEmitted = true
}
const finishFail = (errMsg: string) => {
if (isFinished || isAborted) {
return
}
// When download fails, it's necessary to clean up the file handle, underlying request, and incomplete files simultaneously.
isFinished = true
closeTargetFile()
destroyHttpRequest()
this.clearDownloadTargetFile(params.targetAbsPath)
controller.fail(errMsg)
}
const finishSuccess = () => {
if (isFinished || isAborted || !isResponseCodeReady) {
return
}
// Success can only be finalized after the status code is ready to ensure headers/success don't receive incomplete states.
isFinished = true
closeTargetFile()
tryEmitHeaders()
destroyHttpRequest()
controller.success({
statusCode: responseCode,
header: responseHeader,
cookies: responseCookies
})
}
controller.registerAbort(() => {
if (isFinished || isAborted) {
return
}
// When taskAbort / timeout / destroy occurs, only the underlying resources are cleaned up. The final state is unified by the SDK task state machine.
isAborted = true
closeTargetFile()
destroyHttpRequest()
this.clearDownloadTargetFile(params.targetAbsPath)
})
try {
this.ensureDirSync(targetDir)
this.clearDownloadTargetFile(params.targetAbsPath)
// The target file is written directly by the Host Environment proxy; the SDK is only responsible for preparing the directory and cleaning up incomplete files.
targetFile = fs.openSync(params.targetAbsPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
// Headers, progress, and chunked writes of the download stream are handled independently to prevent a single callback from taking on too many responsibilities.
httpRequest.on("headersReceive", (rawHeaders: Object) => {
this.appendResponseHeaders(rawHeaders as Record<string, string | string[]>, responseHeader, responseCookies)
tryEmitHeaders()
});
httpRequest.on('dataReceiveProgress', (progress: http.DataReceiveProgressInfo) => {
if (!isFinished && !isAborted) {
controller.emitProgress(progress.receiveSize, progress.totalSize)
}
})
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
if (isFinished || isAborted || !targetFile) {
return
}
try {
fs.writeSync(targetFile.fd, data)
} catch (e) {
finishFail(e.message)
}
})
responseCode = await httpRequest.requestInStream(params.url, {
expectDataType: http.HttpDataType.ARRAY_BUFFER,
method: http.RequestMethod.GET,
header: requestHeader,
readTimeout: timeout,
connectTimeout: timeout,
})
isResponseCodeReady = true
finishSuccess()
} catch (e) {
if (!isAborted) {
finishFail(e.message)
}
}
return true
}
private encodeString(value: string): ArrayBuffer {
return buffer.from(value, 'utf-8').buffer
}
private mergeArrayBuffers(buffers: Array<ArrayBuffer>): ArrayBuffer {
let totalLength = 0
buffers.forEach((currentBuffer: ArrayBuffer) => {
totalLength += currentBuffer.byteLength
})
const mergedBuffer = new ArrayBuffer(totalLength)
const mergedView = new Uint8Array(mergedBuffer)
let offset = 0
buffers.forEach((currentBuffer: ArrayBuffer) => {
const currentView = new Uint8Array(currentBuffer)
mergedView.set(currentView, offset)
offset += currentView.byteLength
})
return mergedBuffer
}
private getUploadContentType(fileName: string): string {
const extension = fileName.split('.').pop()?.toLowerCase()
switch (extension) {
case 'txt':
return 'text/plain'
case 'jpg':
case 'jpeg':
return 'image/jpeg'
case 'png':
return 'image/png'
default:
return 'application/octet-stream'
}
}
private cloneRequestHeader(header: Record<string, string>): Record<string, string> {
const requestHeader: Record<string, string> = {}
Object.keys(header).forEach((key: string) => {
requestHeader[key] = header[key]
})
return requestHeader
}
private setRequestHeader(header: Record<string, string>, key: string, value: string) {
let matchedKey: string | undefined = undefined
Object.keys(header).forEach((headerKey: string) => {
if (headerKey.toLowerCase() === key.toLowerCase()) {
matchedKey = headerKey
}
})
if (matchedKey) {
header[matchedKey] = value
} else {
header[key] = value
}
}
private getHeaderValue(header: Record<string, string>, key: string): string | undefined {
let targetValue: string | undefined = undefined
Object.keys(header).forEach((headerKey: string) => {
if (headerKey.toLowerCase() === key.toLowerCase()) {
targetValue = header[headerKey]
}
})
return targetValue
}
private appendResponseCookie(cookie: string | undefined, responseCookies: string[]) {
if (cookie) {
responseCookies.push(cookie)
}
}
private appendResponseHeaderValue(key: string, value: string | string[] | undefined,
responseHeader: Record<string, string>, responseCookies: string[]) {
if (value === undefined) {
return
}
if (key.toLowerCase() === 'set-cookie') {
if (Array.isArray(value)) {
value.forEach((cookie: string) => {
this.appendResponseCookie(cookie, responseCookies)
})
responseHeader[key] = value.join(',')
} else {
this.appendResponseCookie(value, responseCookies)
responseHeader[key] = value
}
return
}
responseHeader[key] = Array.isArray(value) ? value.join(',') : value
}
private appendResponseHeaders(rawHeaders: Record<string, string | string[]>, responseHeader: Record<string, string>,
responseCookies: string[]) {
Object.keys(rawHeaders).forEach((key: string) => {
this.appendResponseHeaderValue(key, rawHeaders[key], responseHeader, responseCookies)
})
}
private readUploadFileBuffer(filePath: string): ArrayBuffer {
const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY)
try {
const stat = fs.statSync(filePath)
const fileBuffer = new ArrayBuffer(stat.size)
fs.readSync(file.fd, fileBuffer)
return fileBuffer
} finally {
try {
fs.closeSync(file.fd)
} catch (e) {
}
}
}
private buildUploadBody(boundary: string, fileFieldName: string, fileName: string, fileContent: ArrayBuffer,
contentType: string, formData: Record<string, string>): ArrayBuffer {
const buffers: Array<ArrayBuffer> = []
// The multipart body order remains as follows: file part -> additional formData part -> ending boundary.
const fileHeader =
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="${fileFieldName}"; filename="${fileName}"\r\n` +
`Content-Type: ${contentType}\r\n\r\n`
buffers.push(this.encodeString(fileHeader))
buffers.push(fileContent)
buffers.push(this.encodeString('\r\n'))
// Additional form fields reuse the same boundary rule and are appended after the file part.
Object.keys(formData).forEach((key: string) => {
const value = formData[key]
const formHeader =
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="${key}"\r\n\r\n` +
`${value}\r\n`
buffers.push(this.encodeString(formHeader))
})
buffers.push(this.encodeString(`--${boundary}--\r\n`))
return this.mergeArrayBuffers(buffers)
}
private clearDownloadTargetFile(targetAbsPath: string) {
try {
if (fs.accessSync(targetAbsPath)) {
fs.unlinkSync(targetAbsPath)
}
} catch (e) {
}
}
private ensureDirSync(dirPath: string) {
const isExist = fs.accessSync(dirPath)
if (!isExist) {
fs.mkdirSync(dirPath, true)
}
}
}
export function initAppletNetWorkRequestHandler() {
FinAppProxyHandlerManager.appletNetWorkRequestHandler = new AppletNetWorkRequestProxy()
}
# 19.4 Simplified Version
If only basic request, upload, and download functionalities are required, you can refer to this lighter implementation. It retains the handling of header and cookies but does not maintain additional logic such as task management, progress tracking, or chunking.
import { FinAppProxyHandlerManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { http } from '@kit.NetworkKit'
import { common } from '@kit.AbilityKit'
import { fileIo as fs } from '@kit.CoreFileKit'
import { buffer } from '@kit.ArkTS'
type THttpHeaders = Record<string, string | string[]>
class AppletNetWorkRequestProxy extends IFinProxyHandlerItem.AppletNetWorkRequestHandler {
public async request(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletRequestRequest,
controller: IFinAppProxy.IAppletRequestTaskController): Promise<boolean> {
const httpRequest = http.createHttp()
const timeout = params.timeout > 0 ? params.timeout : 60000
const method = (params.method || 'GET').toUpperCase() as http.RequestMethod
try {
const response = await httpRequest.request(params.url, {
method,
header: this.cloneRequestHeader(params.header),
extraData: method === http.RequestMethod.GET ? undefined : params.data,
expectDataType: params.responseType === 'arraybuffer'
? http.HttpDataType.ARRAY_BUFFER
: http.HttpDataType.STRING,
readTimeout: timeout,
connectTimeout: timeout,
})
controller.success({
statusCode: response.responseCode as number,
header: this.normalizeResponseHeader(response.header as THttpHeaders),
cookies: this.normalizeResponseCookies(response.cookies),
data: response.result
})
} catch (e) {
controller.fail(e.message)
} finally {
try {
httpRequest.destroy()
} catch (e) {
}
}
return true
}
public async uploadFile(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletUploadFileRequest,
controller: IFinAppProxy.IAppletUploadTaskController): Promise<boolean> {
const httpRequest = http.createHttp()
const timeout = params.timeout > 0 ? params.timeout : 60000
const boundary = `----FinClipBoundary${Date.now()}`
const fileName = params.filePath.split('/').pop() || 'file'
const bodyContent = this.buildMultipartBody(boundary, params.name, fileName,
this.readFileBuffer(params.filePath), params.formData)
const requestHeader = this.cloneRequestHeader(params.header)
requestHeader['Content-Type'] = `multipart/form-data; boundary=${boundary}`
requestHeader['Content-Length'] = `${bodyContent.byteLength}`
try {
const response = await httpRequest.request(params.url, {
method: http.RequestMethod.POST,
header: requestHeader,
extraData: bodyContent,
expectDataType: http.HttpDataType.ARRAY_BUFFER,
readTimeout: timeout,
connectTimeout: timeout,
})
controller.success({
statusCode: response.responseCode as number,
header: this.normalizeResponseHeader(response.header as THttpHeaders),
cookies: this.normalizeResponseCookies(response.cookies),
data: response.result
})
} catch (e) {
controller.fail(e.message)
} finally {
try {
httpRequest.destroy()
} catch (e) {
}
}
return true
}
public async downloadFile(appId: string, apiServer: string, context: common.UIAbilityContext,
params: IFinAppProxy.IAppletDownloadFileRequest,
controller: IFinAppProxy.IAppletDownloadTaskController): Promise<boolean> {
const httpRequest = http.createHttp()
const timeout = params.timeout > 0 ? params.timeout : 60000
const targetDir = params.targetAbsPath.split('/').slice(0, -1).join('/')
try {
const response = await httpRequest.request(params.url, {
method: http.RequestMethod.GET,
header: this.cloneRequestHeader(params.header),
expectDataType: http.HttpDataType.ARRAY_BUFFER,
readTimeout: timeout,
connectTimeout: timeout,
})
this.ensureDirSync(targetDir)
this.writeResponseToFile(params.targetAbsPath, response.result)
controller.success({
statusCode: response.responseCode as number,
header: this.normalizeResponseHeader(response.header as THttpHeaders),
cookies: this.normalizeResponseCookies(response.cookies)
})
} catch (e) {
controller.fail(e.message)
} finally {
try {
httpRequest.destroy()
} catch (e) {
}
}
return true
}
private cloneRequestHeader(header: Record<string, string>): Record<string, string> {
const requestHeader: Record<string, string> = {}
Object.keys(header).forEach((key: string) => {
requestHeader[key] = header[key]
})
return requestHeader
}
private normalizeResponseHeader(header: THttpHeaders | undefined): Record<string, string> {
const responseHeader: Record<string, string> = {}
if (!header) {
return responseHeader
}
Object.keys(header).forEach((key: string) => {
const value = header[key]
responseHeader[key] = Array.isArray(value) ? value.join(',') : value
})
return responseHeader
}
private normalizeResponseCookies(cookies?: string | string[]): string[] {
if (!cookies) {
return []
}
if (Array.isArray(cookies)) {
return cookies
}
return [cookies]
}
private buildMultipartBody(boundary: string, fileFieldName: string, fileName: string, fileContent: ArrayBuffer,
formData: Record<string, string>): ArrayBuffer {
const buffers: Array<ArrayBuffer> = []
buffers.push(this.encodeString(
`--${boundary}\r\nContent-Disposition: form-data; name="${fileFieldName}"; filename="${fileName}"\r\n` +
`Content-Type: application/octet-stream\r\n\r\n`
))
buffers.push(fileContent)
buffers.push(this.encodeString('\r\n'))
Object.keys(formData).forEach((key: string) => {
buffers.push(this.encodeString(
`--${boundary}\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${formData[key]}\r\n`
))
})
buffers.push(this.encodeString(`--${boundary}--\r\n`))
return this.mergeArrayBuffers(buffers)
}
private writeResponseToFile(filePath: string, data: ArrayBuffer | string | Object) {
const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC)
try {
const bufferData = data instanceof ArrayBuffer
? data
: typeof data === 'string'
? this.encodeString(data)
: this.encodeString(JSON.stringify(data))
fs.writeSync(file.fd, bufferData)
fs.fsyncSync(file.fd)
} finally {
try {
fs.closeSync(file.fd)
} catch (e) {
}
}
}
private readFileBuffer(filePath: string): ArrayBuffer {
const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY)
try {
const stat = fs.statSync(filePath)
const fileBuffer = new ArrayBuffer(stat.size)
fs.readSync(file.fd, fileBuffer)
return fileBuffer
} finally {
try {
fs.closeSync(file.fd)
} catch (e) {
}
}
}
private ensureDirSync(dirPath: string) {
const isExist = fs.accessSync(dirPath)
if (!isExist) {
fs.mkdirSync(dirPath, true)
}
}
private encodeString(value: string): ArrayBuffer {
return buffer.from(value, 'utf-8').buffer
}
private mergeArrayBuffers(buffers: Array<ArrayBuffer>): ArrayBuffer {
let totalLength = 0
buffers.forEach((currentBuffer: ArrayBuffer) => {
totalLength += currentBuffer.byteLength
})
const mergedBuffer = new ArrayBuffer(totalLength)
const mergedView = new Uint8Array(mergedBuffer)
let offset = 0
buffers.forEach((currentBuffer: ArrayBuffer) => {
mergedView.set(new Uint8Array(currentBuffer), offset)
offset += currentBuffer.byteLength
})
return mergedBuffer
}
}
FinAppProxyHandlerManager.appletNetWorkRequestHandler = new AppletNetWorkRequestProxy()
# 20. AuthRequestHandler
The Mini-Program permission request proxy class is used for pre-processing permission requests by the Host-App before the SDK displays the permission dialog. It also receives the final authorization result after the SDK's permission process ends.
# 20.1 Proxy Management Method
The permission request proxy is managed uniformly through FinAppProxyHandlerManager.authRequestHandler.
import { FinAppProxyHandlerManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { common } from '@kit.AbilityKit'
class AuthRequestHandler extends IFinProxyHandlerItem.AuthRequestHandler {
/**
* Permission request interception.
*
* @param appId The appId of the current Mini-Program.
* @param apiServer The apiServer bound to the current Mini-Program.
* @param context The UIAbilityContext of the current Host-App.
* @param auth The type of permission being requested.
* @returns Promise<boolean> Returning true indicates continuing with the SDK's default permission dialog flow; returning false indicates that the Host-App rejects this request, and the SDK directly handles it as a failure.
*/
public async onAuthRequest(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
auth: IFinAppProxy.AuthEnum
): Promise<boolean>
/**
* Permission result callback.
*
* @param appId The appId of the current Mini-Program.
* @param apiServer The apiServer bound to the current Mini-Program.
* @param context The UIAbilityContext of the current Host-App.
* @param auth The type of permission requested.
* @param result The final authorization result, where true indicates the permission request was successful, and false indicates it was denied.
*/
public onAuthResult(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
auth: IFinAppProxy.AuthEnum,
result: boolean
): void
}
FinAppProxyHandlerManager.authRequestHandler = new AuthRequestHandler()
# 20.2 Invocation Timing
onAuthRequestwill be triggered before the SDK displays the permission dialog. The Host-App can display a custom confirmation dialog, perform business validation, or directly reject the current permission request.- When
onAuthRequestreturnstrue, the SDK continues with the default permission dialog process. - When
onAuthRequestreturnsfalse, the SDK no longer displays the default permission dialog and handles it as a failed permission request. onAuthResultwill be triggered after the SDK's permission process is completed. Regardless of whether the final result is allowed or denied, theresultwill be passed back to the Host-App.
# 20.3 AuthEnum Type
The auth parameter uses IFinAppProxy.AuthEnum to represent the type of permission requested this time.
| Enum Value | Description |
|---|---|
AUTH_USERINFO | User information permission |
AUTH_USER_LOCATION | Location information permission |
AUTH_RECORD | Recording permission |
AUTH_CALENDAR | Calendar permission |
AUTH_PHOTO_ALBUM | Photo album permission |
AUTH_CAMERA | Camera permission |
AUTH_BLUETOOTH | Bluetooth permission |
AUTH_CONTACT | Contact permission |
AUTH_PHONE_NUMBER | Phone number permission |
AUTH_OTHER | Other permissions |
# 20.4 Example Code
import { FinAppProxyHandlerManager, IFinAppProxy, IFinProxyHandlerItem } from '@finclip/sdk'
import { common } from '@kit.AbilityKit'
import { promptAction } from '@kit.ArkUI'
class AuthRequestHandler extends IFinProxyHandlerItem.AuthRequestHandler {
public onAuthResult(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
auth: IFinAppProxy.AuthEnum,
result: boolean
) {
promptAction.showDialog({
title: 'Permission Application Result Callback',
message: `Permission: ${auth}, Application Result: ${result}`,
buttons: [
{
text: 'Confirm',
color: '#0000ff'
}
],
})
}
public async onAuthRequest(
appId: string,
apiServer: string,
context: common.UIAbilityContext,
auth: IFinAppProxy.AuthEnum
): Promise<boolean> {
let res = true
try {
const response = await promptAction.showDialog({
title: 'Host-App Pre-handling Permission Request',
message: `Permission: ${auth}`,
buttons: [
{
text: 'Allow',
color: '#0000ff'
},
{
text: 'Deny',
color: '#ff0000'
}
],
})
res = response.index === 0
} catch (e) {
// If there is an exception in the dialog, handle it as default allowed to avoid blocking the SDK's default permission process due to Host-App UI anomalies.
}
return res
}
}
export function initAuthRequestHandler() {
FinAppProxyHandlerManager.authRequestHandler = new AuthRequestHandler()
}