# API/Component Customization

# 1. Registering Custom APIs

If a Mini-Program needs to invoke certain capabilities provided by the Host-App, and these capabilities are not implemented or cannot be implemented by the FinClip Mini-Program SDK, custom APIs can be registered to enable such functionality, allowing the Mini-Program to call APIs registered in the App.

There are two scenarios for registering custom APIs:

  1. Registering custom APIs for use by native Mini-Programs;
  2. Registering custom APIs for use by H5 pages loaded within WebView components in the Mini-Program.

# 1.1 Registering Asynchronous APIs for Mini-Programs

Supported app types

Mini-Program βœ… Mini-Game βœ… H5 Application βœ…

Function to register custom asynchronous APIs:

/**
 Register an extended API
 
 @param extApiName Name of the extended API
 @param handler Callback
 @return Returns registration result
 */
- (BOOL)registerExtensionApi:(NSString *)extApiName handler:(void (^)(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback))handler;

Custom asynchronous API (not involving UI) For example, I will register a custom finclipLogin so that it can be directly used in the Mini-Program.

First, after integrating the SDK into the App, register the custom API:

[[FATClient sharedClient] registerExtensionApi:@"finclipLogin" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
     // param is the input parameter
    // Return success and output parameters
    callback(FATExtensionCodeSuccess, @{
                @"token" : @"abcdefg",
                @"name" : @"Xiao Ming"
    });
}];

Next, create a FinClipConf.js file in the root directory of the Mini-Program with the following configuration:

module.exports = {
  extApi:[
    { // Ordinary interaction API
      name: 'finclipLogin', // Extended API name; this API must be implemented on the Native side
      sync: false, // Whether it's a synchronous API
      params: { // Parameter format of the extended API; only required properties need to be listed
        url: ''
      }
    }
  ]
}

Note: extApi is an array, so you can register multiple custom APIs.

For more information on custom API configurations on the Mini-Program side, refer to ft.loadExtApi.

Finally, call the custom API in the Mini-Program as follows:

ft.finclipLogin({
    url:'https://www.baidu.com',
    success: function (res) {
        console.log("Custom API call success");
        console.log(res);
    },
    fail: function (res) {
        console.log("Custom API call failed");
        console.log(res);
    }
});

Custom asynchronous API (opening a native page) For instance, register a custom payment API (finclipPay).

[[FATClient sharedClient] registerExtensionApi:@"msPay" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
    // 1. Get the Mini-Program's payment parameters
    // 2. Navigate to the payment page
    UIViewController *topVC = [[UIApplication sharedApplication] fat_topViewController]; // Utility method provided by the SDK to get the topmost view controller
    FinTestViewController *payVC = [[FinTestViewController alloc] init];
    payVC.param = param;
    payVC.completion = ^(NSDictionary * _Nonnull result) {
        callback(FATExtensionCodeSuccess, result);
    };
    [topVC presentViewController:payVC animated:YES completion:nil];
}];

Create FinClipConf.js in the root directory of the Mini-Program, with content as follows:

module.exports = {
  extApi:[
    { // Login API
      name: 'finclipLogin', // Extended API name; this API must be implemented on the Native side
      sync: false, // Whether it's a synchronous API
      params: { // Parameter format of the extended API; only required properties need to be listed
       url: ''
      }
    },
    { // Payment API
      name: 'finclipPay', // Extended API name; this API must be implemented on the Native side
      sync: false, // Whether it's a synchronous API
      params: { // Parameter format of the extended API; only required properties need to be listed
       name: '',
       price:'',
      }
    }
  ]
}

Finally, invoke the payment functionality in the Mini-Program.

ft.msPay({
    name:'Ultraman Zero',
    price:26.2,
    success: function (res) {
        console.log("Payment call success");
        console.log(res);
    },
    fail: function (res) {
        console.log("Payment call failed");
        console.log(res);
    }
});

# 1.2 Registering Synchronous APIs for Mini-Programs

Supported app types

Mini-Program βœ… Mini-Game βœ… H5 Application 🚫

APIs used in Mini-Programs include both asynchronous and synchronous APIs. Starting from version 2.36.1, the FinClip Mini-Program SDK also supports registering custom synchronous APIs.

Function to register custom synchronous APIs:

/**
 Register a synchronous extended API
 @param syncExtApiName Name of the extended API
 @param handler Callback
 @return Returns registration result
 */
- (BOOL)registerSyncExtensionApi:(NSString *)syncExtApiName handler:(NSDictionary *(^)(FATAppletInfo *appletInfo, id param))handler;

For example, I will register a synchronous Mini-Program API:

1). After initializing the SDK, register and implement the synchronous API.

[[FATClient sharedClient] registerSyncExtensionApi:@"finclipTestSync" handler:^NSDictionary *(FATAppletInfo *appletInfo, id param) {
    NSLog(@"%p, param:%@", __func__, param);
    NSDictionary *resultDict = @{
                                 @"content":@"This is the content returned by the synchronous API",
                                 @"title":@"This is the title returned by the synchronous API"
    };
    return resultDict;
}];

2). Create a FinClipConf.js file in the root directory of the Mini-Program and add this synchronous API.

module.exports = {
  extApi:[
    { // Ordinary interaction API
      name: 'finclipLogin', // Extended API name; this API must be implemented on the Native side
      sync: false, // Whether it's a synchronous API
      params: { // Parameter format of the extended API; only required properties need to be listed
        url: ''
      }
    },
    {
        name: 'finclipTestSync',
        sync: true, // Whether it's a synchronous API
        params: {
            name:'',
            title:''
        }
    }
  ]
}

For more information on custom API configurations on the Mini-Program side, refer to ft.loadExtApi.

3). Invoke the API in the Mini-Program.

const res = ft.finclipTestSync({'name':'Zhang San', 'title':'Finclip'});
console.log(res.title);

Note: The input parameter for a custom synchronous API is a dictionary, and the return value must also be a dictionary type, which cannot contain objects that cannot be JSON serialized (e.g., views, custom models). Parameters declared in FinClipConf.js must be passed when invoking the API. For example, if I declare name and title parameters in the above example, using const res = ft.finclipTestSync({'name':'Zhang San'}), const res = ft.finclipTestSync({}), or const res = ft.finclipTestSync() will all cause errors, preventing the event from being sent to the native side. Therefore, it’s best not to include parameters in FinClipConf.js, or declare them as {}.

# 1.3 Registering Custom APIs (with Custom Scope)

Supported app types

Mini-Program βœ… Mini-Game βœ… H5 Application 🚫

When a custom API wants to bind a custom dialog box, this API can be used for registration. When calling the custom API in the Mini-Program, you can choose to display the dialog box first, and then execute the logic of the custom API after the user allows it.

/**
 Register a permission-based asynchronous extended API
 Note: The asynchronously returned result in the handler must be a dictionary that can be converted to JSON. Use [NSJSONSerialization isValidJSONObject:xxxx] to verify.
 @param extApiName API name
 @return Returns registration result
 */
- (BOOL)registerScopeExtensionApi:(NSString *)extApiName handler:(void (^)(FATAppletInfo *appletInfo, id param, FATScopeChecker *scopeChecker,FATExtensionApiCallback callback))handler;

The specific implementation is as follows: 1). Register a custom API with a custom scope.

    [[FATClient sharedClient] registerScopeExtensionApi:@"finclipLogin" handler:^(FATAppletInfo *appletInfo, id param, FATScopeChecker *scopeChecker, FATExtensionApiCallback callback) {
        
    }];

2). In the custom API implementation, control whether to display a custom permission dialog box.

    [[FATClient sharedClient] registerScopeExtensionApi:@"finclipLogin" handler:^(FATAppletInfo *appletInfo, id param, FATScopeChecker *scopeChecker, FATExtensionApiCallback callback) {
        FATScopeCustomView *customView = [[[NSBundle mainBundle] loadNibNamed:@"FATScopeCustomView" owner:self options:nil] lastObject];
        customView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300);
        [scopeChecker checkScopeWithView:customView];
        customView.scopeAuthCompleteHandler = ^(NSInteger result, NSArray<FATAppletScope *> * _Nonnull scopeArray) {
            [scopeChecker dismissViewWithScopeList:scopeArray];
            
            if (result == 0) {
                // Denied
                callback(FATExtensionCodeFailure, nil);
            } else {
                // Execute specific business logic
              
                // Trigger callback, which can be either success or failure
                callback(FATExtensionCodeSuccess, nil);
            }
        };
    }];

3). Create the FinClipConf.js file in the root directory of the Mini-Program and add this custom API

module.exports = {
  extApi:[
    { // Ordinary interactive API
      name: 'finclipExtScope', // Extended API name. This API must be implemented by the Native side.
      sync: false, // Whether it is a synchronous API
      params: { // Parameter format for the extended API. Only required properties need to be listed.
        url: ''
      }
    }
  ]
}

4). Call this custom API in the Mini-Program

ft.finclipExtScope({
    success: function (res) {
        console.log("Custom API call succeeded");
        console.log(res);
    },
    fail: function (res) {
        console.log("Custom API call failed");
        console.log(res);
    }
});

# 1.4 Register JS API

Supported app types

Mini-Program βœ… Mini-Game 🚫 H5 Application 🚫

The Mini-Program can use the web-view component to load H5. If you want the H5 to also call a certain capability of the Host-App API, you can register an API using this method.

/// Register the native API to be called for HTML
/// @param webApiName Name of the native API
/// @param handler Callback
- (BOOL)fat_registerWebApi:(NSString *)webApiName handler:(void (^)(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback))handler;

Here, I registered a method named js2AppFunction for the H5 within the Mini-Program:

    [[FATClient sharedClient] fat_registerWebApi:@"js2AppFunction" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
        NSString *name = param[@"name"];
//        id params = param[@"data"];
        if ([name isEqualToString:@"getLocation"]) {
            // Execute location logic
            
            // Return result to HTML
            NSDictionary *dict = @{@"errno":@"403", @"errmsg":@"No Permission", @"result": @{@"address":@"Guangdong Province, Shenzhen City, Nanshan District, Aerospace Science and Technology Plaza"}};
            callback(FATExtensionCodeSuccess, dict);
        } else if ([name isEqualToString:@"getColor"]) {
            // Execute other logic
            
            // Return result to HTML
            NSDictionary *dict = @{@"r":@"110",@"g":@"150",@"b":@"150"};
            callback(FATExtensionCodeSuccess, dict);
        }
    }];

In the H5, reference our bridging JSSDK file to call the above registered method.

Example of calling the registered method in HTML:

window.ft.miniProgram.callNativeAPI('js2AppFunction', {name:'getLocation'}, (result) => {
    console.log(result)
});

# 2. Native Calling JS API

Supported app types

Mini-Program βœ… Mini-Game 🚫 H5 Application βœ…

Similarly, if the Host-App wants to call a method in the H5 loaded by the Mini-Program, this API can be used.

/**
 Native calls JS functions in HTML (foreground running Mini-Program)
 @param eventName Function name
 @param paramString JSON converted from the function's parameter dictionary
 @param pageId webView ID, optional; defaults to calling the function in the topmost page’s H5
 @param handler Callback for the invocation result: error code FATErrorCodeAppletNotFound means no foreground running Mini-Program was found
 */
- (void)fat_callWebApi:(NSString *)eventName paramString:(NSString *)paramString pageId:(NSNumber *)pageId handler:(void (^)(id result, NSError *error))handler;

/**
 Native calls JS functions in HTML (Mini-Program specified by appletId)
 @param eventName Function name
 @param appletId Mini-Program ID, specifying which Mini-Program to call
 @param paramString JSON converted from the function's parameter dictionary
 @param pageId webView ID, optional; defaults to calling the function in the topmost page’s H5
 @param handler Callback for the invocation result: error code FATErrorCodeForegroundAppletNotFound means no Mini-Program with the specified appletId was found
*/
- (void)fat_callWebApi:(NSString *)eventName applet:(NSString *)appletId paramString:(NSString *)paramString pageId:(NSNumber *)pageId handler:(void (^)(id result, NSError *error))handler;

First, reference our bridging JSSDK file in the H5.

Then, register the method in the HTML, for example, a method named app2jsFunction.

window.ft.onNativeAPIHandler('app2jsFunction', function(res) {
    // app2jsFunction callback
})

Finally, the native side calls the following API to invoke the JS function in the HTML:

NSString *jsonParams = @""; // This should be a JSON string converted from the parameter dictionary.
NSNumber *pageId = @(1234); // This is the pageId passed from the HTML.
[[FATClient sharedClient] fat_callWebApi:@"app2jsFunction" paramString:jsonParams pageId:pageId handler:^(id result, NSError *error) {
        
}];

# 3. Register Native Components

Supported app types

Mini-Program βœ… Mini-Game 🚫 H5 Application 🚫

If you want to use native components from the app within the Mini-Program, we can achieve this by registering native components.

Note: The Camera, live-pusher, and live-player components are now implemented within the SDK and no longer support these three components.

# 3.1 Implement Custom Native Components

First, create the component view and implement its protocol methods.

.h

#import <UIKit/UIKit.h>
#import <FinApplet/FATAppletNativeProtocol.h>

NS_ASSUME_NONNULL_BEGIN

@interface FATNativeView : UIView <FATAppletNativeViewProtocol>
@property (nonatomic, strong) NSNumber *nativeViewId;
@property (nonatomic, strong) NSString *type;

@end

NS_ASSUME_NONNULL_END

.m

@implementation FATNativeView
+ (UIView *)onCreateView:(NSDictionary *)param {
    return [[self alloc] initWithParam:param];
}

- (instancetype)initWithParam:(NSDictionary *)param {
    CGRect frame = CGRectZero;
    NSDictionary *style = [param objectForKey:@"style"];
    if (style) {
        CGFloat x = [[style objectForKey:@"left"] floatValue];
        CGFloat y = [[style objectForKey:@"top"] floatValue];
        CGFloat height = [[style objectForKey:@"height"] floatValue];
        CGFloat width = [[style objectForKey:@"width"] floatValue];
        frame = CGRectMake(x, y, width, height);
    }
    self = [super initWithFrame:frame];
    if (self) {
        _type = param[@"type"];
        _nativeViewId = param[@"nativeViewId"];
    }
    return self;
}

- (void)onUpdateView:(NSDictionary *)param {
    NSDictionary *style = [param objectForKey:@"style"];
    if (style) {
        CGRect frame = CGRectZero;
        CGFloat x = [[style objectForKey:@"left"] floatValue];
        CGFloat y = [[style objectForKey:@"top"] floatValue];
        CGFloat height = [[style objectForKey:@"height"] floatValue];
        CGFloat width = [[style objectForKey:@"width"] floatValue];
        frame = CGRectMake(x, y, width, height);
        self.frame = frame;
    }
}

- (void)onDestroyView:(NSDictionary *)param {
    NSLog(@"Destroyed %@",param);
}

@end

Then, set the component's view class and inject the corresponding type of native component class.

[[FATClient sharedClient].nativeViewManager registerNativeViewType:@"native-view" nativeViewClass: [FATNativeView class]];

Finally, use the corresponding component in the Mini-Program.

<native-view type="native-view" style="left: 0px; top: 0px; width: 100px; height: 100px;">123</native-view>

# 3.2 Native Sending Messages to Components

The Host-App sends messages to the native component through the nativeViewManager.

/// Send events to nativeView (foreground running Mini-Program)
/// @param eventName Event name
/// @param nativeViewId native-view id
/// @param detail Detailed event parameters
/// @param completion Completion callback: error code FATErrorCodeAppletNotFound means no foreground running Mini-Program was found
- (void)sendEvent:(NSString *)eventName nativeViewId:(NSNumber *)nativeViewId detail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;

/// Send events to nativeView (Mini-Program specified by appletId)
/// @param eventName Event name
/// @param appletId Mini-Program appId, cannot be empty
/// @param nativeViewId native-view id
/// @param detail Detailed event parameters
/// @param completion Completion callback: error code FATErrorCodeForegroundAppletNotFound means no Mini-Program with the specified appletId was found
- (void)sendEvent:(NSString *)eventName applet:(NSString *)appletId nativeViewId:(NSNumber *)nativeViewId detail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;

Sample code:

[[FATClient sharedClient].nativeViewManager sendEvent:@"eventName" nativeViewId:@(1234) detail:@{} completion:^(id result, FATError *error) {
            
}];

# 4. Native Sending Global Messages to Mini-Programs

Supported app types

Mini-Program βœ… Mini-Game βœ… H5 Application βœ…

You can send global messages to Mini-Programs via the following API.

/// Send global events (foreground running Mini-Program)
/// @param detail Detailed event parameters
/// @param completion Completion callback: error code FATErrorCodeAppletNotFound means no foreground running Mini-Program was found
- (void)sendCustomEventWithDetail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;

/// Send global events (Mini-Program specified by appletId)
/// @param detail Detailed event parameters
/// @param appletId Mini-Program appId, cannot be empty
/// @param completion Completion callback: error code FATErrorCodeForegroundAppletNotFound means no Mini-Program with the specified appletId was found
- (void)sendCustomEventWithDetail:(NSDictionary *)detail applet:(NSString *)appletId completion:(void (^)(id result, NSError *error))completion;

Sample code:

[[FATClient sharedClient].nativeViewManager sendCustomEventWithDetail:@{} completion:^(id result, NSError *error) {    
}];
© FinClip with ❀ , Since 2017