tencent cloud

Feedback

Customize JSAPI

Last updated: 2024-03-04 22:47:57
    Creating API
    Example:
    @JsPlugin(secondary = true)
    public class CustomPlugin extends BaseJsPlugin {
    @JsEvent("customAsyncEvent")
    public void custom(final RequestEvent req) {
    //Get parameters
    //req.jsonParams
    //Asynchronously return data
    //req.fail();
    //req.ok();
    JSONObject jsonObject = new JSONObject();
    try {
    jsonObject.put("key", "test");
    } catch (JSONException e) {
    e.printStackTrace();
    }
    req.ok(jsonObject);
    }
    
    @JsEvent("customSyncEvent")
    public String custom1(final RequestEvent req) {
    //Get parameters
    //req.jsonParams
    //Synchronously Return Data
    JSONObject jsonObject = new JSONObject();
    try {
    jsonObject.put("key", "value");
    } catch (JSONException e) {
    throw new RuntimeException(e);
    }
    return req.okSync(jsonObject);
    }
    
    /**
    * Testing Coverage System API
    * @param req
    */
    @JsEvent("getAppBaseInfo")
    public void getAppBaseInfo(final RequestEvent req) {
    //Get parameters
    //req.jsonParams
    //Asynchronously return data
    //req.fail();
    //req.ok();
    JSONObject jsonObject = new JSONObject();
    try {
    jsonObject.put("key", "test");
    } catch (JSONException e) {
    e.printStackTrace();
    }
    req.ok(jsonObject);
    }
    @JsEvent("testState") public void testState(final RequestEvent req) { try { //Callback intermediate status req.sendState(req, new JSONObject().put("progress", 1)); req.sendState(req, new JSONObject().put("progress", 30)); req.sendState(req, new JSONObject().put("progress", 60)); req.sendState(req, new JSONObject().put("progress", 100)); } catch (JSONException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "test"); req.ok(jsonObject); } catch (JSONException e) { throw new RuntimeException(e); } }
    }
    Note:
    Inherit BaseJsPlugin and define with annotation @JsPlugin(secondary = true)
    Define a method that takes only one parameter of type RequestEvent.
    Then, define the annotation @JsEvent("event name") on the method. When the Mini Program js calls the "event name", it will call the corresponding method decorated with @JsEvent.
    @JsEvent supports the definition of multiple event names.
    Supports synchronous or asynchronous data return (only one method can be selected for the same event).
    You can call sendState to return the intermediate status to the Mini Program end for multiple times. After the sendState call ends, you must call "OK" or "fail" to indicate the end of the entire process.
    Define API Configuration
    {
    "extApi": [
    {
    //Event name, consistent with the event defined in @JsEvent in the "Create API" example
    "name": "customSyncEvent",
    //Whether to call synchronously to keep consistent with the data return method in the "Create API" example
    "sync": true,
    //Define Parameters
    //a.json format can be nested
    //b. Set the string parameter value to ""
    //c. Set the numerical parameter value to 0
    "params": {
    "name": "",
    "age": 0,
    "object": {
    "key": "",
    }
    }
    }
    ],
    //true: When the custom API event name overlaps with the built-in method name of the mini program SDK, it will override the latter.
    //API, the final call will call the developer's custom API
    "overwriteWxApi": false
    }
    
    
    
    Store the defined API configuration file in the project's assets directory (the file name and path can be defined by the developer), then set the API configuration file path as follows.
    @ProxyService(proxy = MiniAppProxy.class)
    public class MiniAppProxyImpl extends BaseMiniAppProxyImpl {
    @Override
    public MiniConfigData configData(Context context, int configType, JSONObject params) {
    if(configType == MiniConfigData.TYPE_CUSTOM_JSAPI) {
    //Custom JsApi configuration
    MiniConfigData.CustomJsApiConfig customJsApiConfig = new MiniConfigData.CustomJsApiConfig();
    customJsApiConfig.jsApiConfigPath = "tcmpp/custom-config.json";
    
    return new MiniConfigData
    .Builder()
    .customJsApiConfig(customJsApiConfig)
    .build();
    }
    return null;
    }
    The mini program system's built-in APIs can all be found under wx., as shown below:
    
    
    
    Json API Configuration Reference Example
    {
    "extApi": [
    {
    "name": "customSyncEvent",
    "sync": true,
    "params": {
    "name": "",
    "age": ""
    }
    },
    {
    "name": "customAsyncEvent",
    "sync": false,
    "params": {
    "name": "",
    "age": ""
    }
    },
    {
    "name": "getAppBaseInfo",
    "sync": false,
    "params": {
    }
    }
    "overwriteWxApi": true
    }
    Call code at the mini program end
    The code in the above example is called in the mini program as follows:
    wx.customAsyncEvent({"name":"123","age":"18"})
    wx.getAppBaseInfo()//This will override the system API, and then call into the custom API
    Troubleshooting Custom JSAPI Errors
    Reason 1: Check whether the following class XxxJsPluginScope has been generated.
    
    Reason 2: Verify whether the event names defined by the client and the method names called by the mini program are consistent. Event names are case-sensitive.

    Start Activity in Plugin

    Start a new Activity in the plugin and get the data returned by the Get Activity.
    @JsPlugin(secondary = true)
    public class CustomPlugin extends BaseJsPlugin {
    @JsEvent("testStartActivityForResult")
    public void testStartActivityForResult(final RequestEvent req) {
    Activity activity = req.activityRef.get();
    TmfMiniSDK.addActivityResultListener(new IActivityResultListener() {
    @Override
    public boolean doOnActivityResult(int requestCode, int resultCode, Intent data) {
    TmfMiniSDK.removeActivityResultListener(this);
    Log.i(ModuleApplet.TAG, data.getStringExtra("key"));
    req.ok();
    return true;
    }
    });
    //Note: requestCode must be>=1000000, otherwise it may conflict with internal requestCode, causing unknown problems.
    activity.startActivityForResult(new Intent(activity, TransActivity.class), 1000000);
    }
    }
    Add Activity to return to listen and remove listening after listening processing is complete:
    TmfMiniSDK.addActivityResultListener()
    TmfMiniSDK.removeActivityResultListener()
    Start a new Activity
    //Note: requestCode must>=1000000, otherwise it may conflict with internal requestCode, causing unknown problems
    activity.startActivityForResult(new Intent(activity, Xxxx.class), 1000000);

    Call third-party apps in plugins

    When other third-party apps (sharing, payment, login) are called in the plugin, Mini programs can be returned directly instead of App when these operations are completed.
    First developers create transparent helper activities
    The following example TransActivity is a transparent auxiliary activity defined (transparent activity developers configure themselves, because the theme settings are related to the system Activity inherited by the application Activity)
    <activity android:name=".activity.TransActivity"
    android:exported="false"
    android:screenOrientation="portrait"
    android:theme="@style/TransparentTheme"/>
    Then invoke the business logic in TransActivity.
    public class TransActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable
    Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.applet_activity_tran);
    
    /** ***********************
    business development
    *************************/
    
    //Return data and call finish after completion of business development
    Intent intent = new Intent();
    intent.putExtra("key", "value");
    setResult(RESULT_OK, intent);
    finish();
    }
    }
    
    
    Plugins start activities and listen for data to return.
    @JsPlugin(secondary = true)
    public class CustomPlugin extends BaseJsPlugin {
    @JsEvent("testStartActivityForResult")
    public void testStartActivityForResult(final RequestEvent req) {
    Activity activity = req.activityRef.get();
    TmfMiniSDK.addActivityResultListener(new IActivityResultListener() {
    @Override
    public boolean doOnActivityResult(int requestCode,
    int resultCode, Intent data) {
    TmfMiniSDK.removeActivityResultListener(this);
    
    Log.i(ModuleApplet.TAG, data.getStringExtra("key"));
    req.ok();
    
    return true;
    }
    });
    
    //Note: requestCode must be>=1000000, otherwise it may conflict with internal requestCode, causing unknown problems.
    activity.startActivityForResult(new Intent(activity, TransActivity.class),
    1000000);
    }
    }
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support