# API/Component Customization
When a Mini-Program needs to call capabilities provided by the Host-App that are not implemented or cannot be implemented by the FinClip Mini-Program SDK, you can achieve this by registering custom APIs, allowing the Mini-Program to call APIs registered in the App.
Similarly, when you need to use components that are not implemented or cannot be implemented, you can also register custom components.
Registering custom APIs is divided into two scenarios:
- Registering custom APIs for use by native Mini-Programs;
- Registering custom APIs for use by H5 pages loaded within the WebView component of a Mini-Program.
# 1. Custom Mini-Program API
There are four steps to register and use a custom Mini-Program API:
- Implement the custom API
- Register the custom API
- Declare the custom API in the Mini-Program configuration
- Call the custom API within the Mini-Program
# 1.1 Register Custom Mini-Program Asynchronous API
Supported App Types
Mini-Program✅ Mini-Game✅ H5 Application✅
- Implement the custom asynchronous API.
# Example: Implementing a Custom Mini-Program Asynchronous API
public class CustomApi extends BaseApi {
public CustomApi(Context context) {
super(context);
}
@Override
public String[] apis() {
return new String[]{"finclipLogin"}; // API name
}
@Override
public void invoke(String event, JSONObject param, ICallback callback) {
if ("finclipLogin".equals(event)) {
val result = JSONObject(); // Simulate obtaining login token, etc.
if (result) {
callback.onSuccess(result)
return;
}
callback.onFail();
}
}
}
- Register it with the
extensionApiManager, supporting individual and batch registration.
Register a Single Custom API
Register Custom APIs in Batch
- Declare the custom API in the Mini-Program configuration file.
Create FinClipConf.js in the Mini-Program root directory and configure the corresponding custom API, or pass the configuration parameters via loadExtApi.
module.exports = {
extApi:[
{ // General Interaction API
name: 'finclipLogin', // Extended API name, must be implemented by the Native side
sync: false, // Whether it is a synchronous API
params: { // Parameter format for the extended API, only list required properties
url: ''
}
},
{
name: 'finclipTestSync',
sync: true, // Whether it is a synchronous API
params: {
name:'',
title:''
}
}
]
}
For more configuration information on the Mini-Program side, refer to ft.loadExtApi.
- Call the custom Mini-Program asynchronous API within the Mini-Program.
ft.finclipLogin({
url:'https://www.baidu.com',
success: function (res) {
console.log("Calling customEvent success");
console.log(res);
},
fail: function (res) {
console.log("Calling customEvent fail");
console.log(res);
}
});
Register Custom API (Open Native Page) For example, register a custom API to open a payment page, and return the result after payment is completed.
First, implement the Activity to be opened. (Assume all payment logic is in this activity)
public class FinClipPayActivity extends AppCompatActivity {
public static final String PAY_RESULT = "pay_result";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fin_clip_pay);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(FinClipPayActivity.this, getString(R.string.fin_clip_input_content_hint), Toast.LENGTH_SHORT).show();
JSONObject payResult = new JSONObject(); // Simulate payment return result
// Pass the result back and close the payment page
String jsonString = payResult.toString();
Intent intent = new Intent();
intent.putExtra(PAY_RESULT, jsonString);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
Then, register the custom API.
public class CustomApi extends BaseApi {
public CustomApi(Context context) {
super(context);
}
@Override
public String[] apis() {
return new String[]{"finclipPay"}; // API name
}
@Override
public void invoke(String event, JSONObject param, ICallback callback) {
Intent intent = new Intent();
intent.setClass(mContext, FinClipPayActivity.class);
String jsonString = param.toString();
intent.putExtra("jsonString", jsonString);
callback.startActivityForResult(intent, 100);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data, ICallback callback) {
if (requestCode == 100) {
if (resultCode == RESULT_OK && data != null) {
String jsonString = data.getStringExtra(EXTRA_PAY_RESULT);
try {
JSONObject jsonObject = new JSONObject(jsonString);
callback.onSuccess(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
callback.onFail();
}
} else {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("errMsg", "Payment failed");
callback.onFail(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
callback.onFail();
}
}
}
}
}
Then register the custom API.
FinAppClient.INSTANCE.getExtensionApiManager().registerApi(new CustomApi(this));
Create FinClipConf.js in the root directory of the Mini-Program, with content as follows:
module.exports = {
extApi:[
{ // Payment API
name: 'finclipPay', // Extended API name, must be implemented by the Native side
sync: false, // Whether it is a synchronous API
params: { // Parameter format for the extended API, only list required properties
name: '',
price:'',
}
}
]
}
Call the custom API within the Mini-Program.
ft.finclipPay({
name:'Ultraman Zero',
price:26.2,
success: function (res) {
console.log("Calling payment success");
console.log(res);
},
fail: function (res) {
console.log("Calling payment fail");
console.log(res);
}
});
# 1.2 Register Custom Mini-Program Synchronous API
Supported App Types
Mini-Program✅ Mini-Game✅ H5 Application✅
A synchronous API is a custom API that can return results synchronously upon invocation.
Note: Custom synchronous APIs need to inherit
SyncApiand override the synchronousinvokemethod. Synchronous APIs must be registered in the Mini-Program process to take effect.
- Implement the custom synchronous API.
public class CustomApi extends SyncApi {
public CustomApi(Context context) {
super(context);
}
@Override
public String[] apis() {
return new String[]{"customApi"};
}
@Nullable
@Override
public String invoke(String event, JSONObject param) {
// {"errMsg": "customApi:ok" , "data": "1"} // The returned data format is fixed, must be JSON format and include the segment `"errMsg": "customApi:ok"`
return getSuccessRes(event).put("data","1").toString(); // Can use the SDK-provided API to assemble the data
// return getFailureRes(event,"token miss").toString()
}
}
- Register the synchronous API in the Mini-Program process.
For custom synchronous APIs in the Mini-Program process, there are two ways to obtain the Mini-Program Activity:
- Passed from outside, via the constructor of the custom API class;
- Directly obtained, via
FinAppProcessClient.appletProcessActivityto get the Activity corresponding to the current Mini-Program process.
- Declare the custom API in the Mini-Program configuration file.
Create FinClipConf.js in the Mini-Program root directory and configure the corresponding custom API, or pass the configuration parameters via loadExtApi.
For more configuration information on the Mini-Program side, refer to ft.loadExtApi.
module.exports = {
extApi:[
{ // General Interaction API
name: 'finclipLogin', // Extended API name, must be implemented by the Native side
sync: false, // Whether it is a synchronous API
params: { // Parameter format for the extended API, only list required properties
url: ''
}
},
{
name: 'finclipTestSync',
sync: true, // Whether it is a synchronous API
params: {
name:'',
title:''
}
}
]
}
- Call within the Mini-Program.
const res = ft.finclipTestSync({'name':'Zhang San', 'title':'Finclip'});
console.log(res.title);
# 1.3 Register Custom API (with Custom Scope Permissions)
Supported App Types
Mini-Program✅ Mini-Game✅ H5 Application🚫
For details, see Custom Mini-Program (Scope) Permissions.
# 1.4 Get All Registered Custom Mini-Program APIs
# API
/**
* Get all registered Mini-Program APIs
*/
fun getRegisteredApis(): Map<String, IApi>
# Call Example
# 2. Custom WebView Component API
Supported App Types
Mini-Program✅ Mini-Game🚫 H5 Application🚫
If H5 pages loaded within a Mini-Program also want to call a capability of the Host-App API, you can use this method to register an API. Currently, only asynchronous APIs are supported.
There are three steps to register and use a custom WebView API:
- Implement the custom API
- Register the custom API.
- Call the custom API within H5.
# 2.1 Register WebView Component API
- Implement the custom API.
# Custom API Example
public class WebApi extends BaseApi {
public WebApi(Context context) {
super(context);
}
@Override
public String[] apis() {
return new String[]{"webApiName"}; // API name
}
@Override
public void invoke(String event, JSONObject param, ICallback callback) {
// Native operations corresponding to the method call
}
}
- Register it with the
extensionWebApiManager, supporting individual and batch registration.
Register a Single Custom API
Register Custom APIs in Batch
- Call the custom API within H5.
Reference our bridge JSSDK file within H5, then you can call the registered methods.
Example of calling the registered method in HTML:
window.ft.miniProgram.callNativeAPI('js2AppFunction', {name:'getLocation'}, (result) => {
console.log(result)
});
# 2.2 Unregister WebView Component API
Supports individual and batch unregistration.
Unregister a Single WebView Component API
# Call Example
Unregister WebView Component APIs in Batch
# 2.3 Get All Registered Mini-Program WebView APIs
Supported App Types
Mini-Program✅ Mini-Game🚫 H5 Application🚫
# API
/**
* Get all registered native APIs called by web pages
*/
fun getRegisteredApis(): Map<String, IApi>
# Call Example
# 3. Register APIs in the Mini-Program Process
Supported App Types
Mini-Program✅ Mini-Game✅ H5 Application✅
Normally, APIs registered for the Mini-Program are executed in the main process. When there is a need for APIs to be executed in the Mini-Program process, you need to call a different interface to register them.
# 4. Native Calls to JS API
Supported App Types
Mini-Program✅ Mini-Game🚫 H5 Application🚫
# API
/**
* Native calls JS function
*
* @param appId Mini-Program id
* @param funcName JS function name
* @param funcParams JS function parameters
* @param webViewId WebView id
* @param callback Callback
*/
fun callJS(appId: String, funcName: String?, funcParams: String?, webViewId: Int, callback: FinCallback<String?>)
# Call Example
First, reference our bridge JSSDK file within H5.
Then, register the method in HTML, for example, name the method app2jsFunction.
window.ft.onNativeAPIHandler('app2jsFunction', function(res) {
// app2jsFunction callback
})
# 5. Register Native Components
Supported App Types
Mini-Program✅ Mini-Game🚫 H5 Application🚫
Due to limited resources, the implementation of native components like livePusher and livePlayer may require external third-party controls. In such cases, you can register native components. The native components we currently support for registration are three: Camera, LivePlayer, LivePusher.
# 5.1 Implement Custom Native Component
Implement the INativeView interface
# Example
class TestNativeView : INativeView {
lateinit var eventChannel: INativeView.EventChannel
/**
* Create native view
* @param params Parameters passed from the Mini-Program
* @param eventChannel Used to send events to the Mini-Program component
* @return The created view, which will be placed at the position declared by the component in the Mini-Program
*/
override fun onCreateView(
context: Context,
params: ShowNativeViewParams,
eventChannel: INativeView.EventChannel
): View {
Log.d(TAG, "onCreateView:${params.nativeViewId}")
this.eventChannel = eventChannel
return TextView(context).apply {
gravity = Gravity.CENTER
setTextColor(Color.RED)
text = params.params.toString()
setBackgroundColor(Color.GREEN)
setOnClickListener {
eventChannel.send(
"test",
mapOf("time" to System.currentTimeMillis())
)
}
}
}
/**
* Update native view
* @param params Parameters passed from the Mini-Program
* @param view Previously created view
*/
override fun onUpdateView(context: Context, params: ShowNativeViewParams, view: View) {
Log.d(TAG, "onUpdateView:${params.nativeViewId}")
params.params?.let { (view as TextView).text = it.toString() }
}
/**
* Destroy native view
* @param params Parameters passed from the Mini-Program
* @param view Previously created view
*/
override fun onDestroyView(context: Context, nativeViewId: String, view: View) {
Log.d(TAG, "onDestroyView:$nativeViewId")
}
}
# 5.2 Register Native Component
# API
/**
* Register native component
*
* @param type Component type
* @param cls Component implementation class, must implement the INativeView interface
*/
fun registerNativeView(type: String, cls: Class<out INativeView>)
# Call Example
# Kotlin
FinAppClient.nativeViewManager.registerNativeView("native-view", TestNativeView::class.java)
Finally, use the custom component within the Mini-Program.
<native-view type="native-view" style="left: 0px; top: 0px; width: 100px; height: 100px;">123</native-view>