tencent cloud

Feedback

TCMPP Flutter Plugin

Last updated: 2024-06-12 09:28:22
    TCMPP Flutter Plugin is a Flutter plugin to provide access for TCMPP SDK in Flutter. For details of TCMPP, see:https://www.tencentcloud.com/products/tcmpp.

    Add TCMPP Flutter Plugin

    Add TCMPP core plugin from Pub.dev

    1. Add dependencyTo add plugin from pub.dev, open the pubspec.yaml file located inside the app folder, and add tcmpp_flutter: ${version} under dependencies.
    
    2. Install dependency
    From the terminal: Run flutter pub get.
    From VS Code: Click Get Packages located in right side of the action ribbon at the top of pubspec.yaml indicated by the Download icon.
    From Android Studio/IntelliJ: Click Pub get in the action ribbon at the top of pubspec.yaml.
    For details how to add Flutter plugins or packages, see Use packages & plugins.

    Add TCMPP extra plugins

    Some TCMPP mini-program APIs may require additional privacy and permissions. To use these APIs, additional Flutter plugin dependencies are needed.
    APIs
    Plugin name
    Permissions needed
    LBS related APIs (Location & POI search)
    Access location
    MDNS APIs
    Access locale network
    TCP/UDP APIs
    Access internet
    Meida APIs (Photos & Videos)
    Access photo library
    Wifi APIs, Bluetooth APIs, Calendar APIs, Contact APIs, Clipboard APIs, Biometric authentication APIs
    Access wifi state, Access bluetooth, Access Calendar, Access contact, Access clipboard, Access fingerprint & face id
    Map APIs
    Access location
    These plugins must be used together with tcmpp_flutter plugin. Map API support is only needed by Android platform, iOS include these APIs by default.
    
    [Notice] iOS needs to add corresponding permission descriptions in the plist file:
    
    iOS plugin name and corresponding permission key:
    Plugin name
    Permission key
    tcmpp_flutter_lbs
    NSLocationAlwaysUsageDescription NSLocationWhenInUseUsageDescription
    NSLocationAlwaysAndWhenInUseUsageDescription
    NSLocationUsageDescription
    NSMotionUsageDescription
    tcmpp_flutter_mdns
    NSBonjourServices
    tcmpp_flutter_network
    NSAppTransportSecurity
    tcmpp_flutter_media
    NSPhotoLibraryUsageDescription
    NSCameraUsageDescription
    tcmpp_flutter_device
    NSCalendarsUsageDescription
    NSRemindersUsageDescription NSContactsUsageDescription
    NSFaceIDUsageDescription
    NSBluetoothAlwaysUsageDescription
    NSBluetoothPeripheralUsageDescription

    Add assets for TCMPP configuration files

    Get TCMPP configuration file from your TCMPP web console

    1. Get application ID / bundle ID of your Android / IOS application.
    For Android, in your Flutter project, open android > app > build.gradle, application id can be found in android > defaultConfig section.
    
    For IOS, in your Flutter project, open ios > Runner.xcodeproj > project.pbxproj, search for PRODUCT_BUNDLE_IDENTIFIER.
    
    2. Create Flutter Application on TCMPP web console.
    2.1 Login the Tencent Cloud Mini Program Platform Console and click 'Overview' in the left-hand navigation bar.
    2.2 On the Overview page, click Access Application.
    2.3 In the pop-up window for creating an application, fill in informations for your application.
    2.4 For Intergration platform section, check both IOS platfrom & Android Platform. Then fill application ID / bundle ID you got in the package name field.
    
    2.5 Click next, download Android / IOS configuration file in the new page.
    

    Add configuration file

    1. Put TCMPP configuration file someware in your flutter project.
    2. Add a file named "tcmpp-plugin-settings.json" in your project's root.
    3. Edit pubspec.yaml file and add flutter assets for files mentioned above.
    
    4. Specify the path to TCMPP configuration file in "tcmpp-plugin-settings.json".
    

    SDK settings

    In the tcmpp-plugin-settings.json file, you can choose to configure settings of your SDK.
    For Android:
    Field name
    Type
    Description
    configAssetsName
    string
    TCMPP android configuration file path
    debug
    bool
    enable SDK debugging & log
    enableX5Core
    bool
    Whether to use TBS service(X5 core) as mini-program runtime
    x5LicenseKey
    string
    License for TBS service if runtime enabled
    X5DocLicenseKey
    string
    License for TBS document service if runtime enabled
    x5Core32Url
    string
    Download url for 32-bit TBS runtime
    x5Core64Url
    string
    Download url for 64-bit TBS runtime
    For iOS:
    Field name
    Type
    Description
    configAssetsName
    string
    TCMPP iOS configuration file path
    debug
    bool
    enable SDK debug
    logEnable
    bool
    enable SDK log
    inspectableEnabled
    bool
    Enable inspectable after iOS 16.4, you can debug mini-program through safari
    For common:
    Field name
    Type
    Description
    appName
    string
    Host app name, mainly used for copyright prompts in mini-program
    appVersion
    string
    Host app version, mainly used for copyright prompts in mini-program

    Platform specific

    For Android platform

    1. Open android > app directory, edit build.gradle file.
    2. In android > defaultConfig section, change minSdkVersion to no less than 21.
    
    minSdkVersion 21
    3. In android > defaultConfig section, add ndk filter for armeabi, armeabi-v7a, arm64-v8a.
    
    ndk { abiFilters "armeabi", "armeabi-v7a", "arm64-v8a" }
    4. In android > defaultConfig section, add packagingOptions.
    
    packagingOptions {
    pickFirst 'lib/arm64-v8a/libc++_shared.so'
    pickFirst 'lib/armeabi/libc++_shared.so'
    pickFirst 'lib/armeabi-v7a/libc++_shared.so'
    pickFirst 'lib/arm64-v8a/libmarsxlog.so'
    pickFirst 'lib/armeabi/libmarsxlog.so'
    pickFirst 'lib/armeabi-v7a/libmarsxlog.so'
    pickFirst 'lib/arm64-v8a/libv8jni.so'
    }

    For iOS platform

    Add source

    In the Podfile file in the ios directory, add source:
    source 'https://e.coding.net/tcmpp-work/tcmpp/tcmpp-repo.git'

    Execute pod install

    cd to ios directory,execute pod install:
    pod install
    

    TCMPP Flutter APIs

    Usage

    1. To use TCMPP APIs, import 'package:tcmpp_flutter/tcmpp_flutter.dart'.
    
    2. Then create a TcmppFlutter object and use it to call TCMPP APIs.
    

    Implement Open APIs

    Some mini-program APIs need to interact with host app or third-party library, such as get account information or request a payment action. For these APIs to work properly, developer should implement and register a OpenApiHandler before mini-program is launched. For details about these APIs, see OpenApiHandler in Classes section.
    example code:
    class MyAppletHandler extends OpenApiHandler {
    @override
    Future<Map<String, dynamic>> getUserProfile(
    AppInfo appInfo, Map<Object?, Object?> params) async {
    print("getUserProfile:$appInfo params:$params");
    Map<String, dynamic> result = {
    "userInfo": {
    "nickName": "xcode",
    "avatarUrl":
    "https://staticintl.cloudcachetci.com/cms/backend-cms/8WGP653_%E5%BC%80%E5%8F%91%E8%80%85%E5%B7%A5%E5%85%B7%E9%80%9A%E7%94%A8.png",
    "gender": 1,
    "country": "China",
    "province": "ChongQing",
    "city": "ChongQing",
    }
    };
    return result;
    }
    
    @override
    Future<Map<String, dynamic>> login(
    AppInfo appInfo, Map<Object?, Object?> params) async {
    /// return current login certification or do login if not logged in
    ...
    }
    
    @override
    Future<Map<String, dynamic>> checkSession(
    AppInfo appInfo, Map<Object?, Object?> params) async {
    /// throw any error if this api call is failed
    throw NotLoggedInError();
    }
    
    /// other api implementation
    ...
    }
    The parameter of these API calls are provided by corresponding mini-program API, converted from JSON object into Dart Map object. Also return value of your implementation will be converted into JSON object and delivered to corresponding mini-program API. You can check out these APIs in TCMPP's mini-program API document.
    To register your OpenApiHandler instance, use registerOpenApiHandler in TcmppFlutter object.
    final _tcmppFlutterPlugin = TcmppFlutter();
    
    ...
    
    @override
    void initState() {
    super.initState();
    
    ...
    
    /// Must registered before mini-program is launched
    _tcmppFlutterPlugin.registerOpenApiHandler(MyAppletHandler());
    }

    Implement Custom API

    The TCMPP SDK engine provides an extension mechanism that allows the host app to customize APIs for mini-programs to call.
    example code: /// Mini Program Call
    var opts = {
    api_name: 'myApiName',
    success: function(res) {
    log(res);
    },
    fail: function(res) {
    log(res);
    },
    complete: function(res) {
    log(res);
    },
    data: {
    name : 'kka',
    age : 22
    }
    }
    wx.invokeNativePlugin(opts);
    void initState() {
    super.initState();
    getRecentMini();
    /// Register custom JSAPI names and functions
    _tcmppFlutterPlugin.registerMiniAppApi("myApiName",myApiHandler);
    }
    /// Custom API
    Future<Map<String, dynamic>?> myApiHandler(MiniApiCall call) async {
    print("API : ${call.apiName}");
    print("AppInfo: ${call.appInfo}");
    print("WebView ID: ${call.webViewId}");
    print("params: ${call.params}");
    return {"result": "success","method":"myApiHandler"};
    }

    Implementing platform event handler

    Some platform events will be delivered to Flutter, you can register a handler to subscribe and response to those events.
    example code:
    class MyPlatformHandler extends TcmppPlatformEventHandler {
    @override
    Future<void> onMiniProgramStateChange(
    String appId, MiniProgramState state) async {
    print("app state change: appid=$appId, state=$state");
    }
    /// other event handler implementation
    ...
    }
    final _tcmppFlutterPlugin = TcmppFlutter();
    
    ...
    
    @override
    void initState() {
    super.initState();
    ...
    /// Must registered before mini-program is launched
    _tcmppFlutterPlugin.registerPlatformEventHandler(MyPlatformHandler());
    }

    Implementing a custom menu

    Developer can customize buttons in mini-program's action panel. Those include share buttons and other function buttons. Currently, action panel is called out by clicking the more button on top right side of mini-program.
    example code:
    @override
    Future<List<CustomMenu>> getCustomMenus() async {
    /// The menu includes menuId, picture (supports local path and network picture), menu name, and whether it is a custom sharing type.
    CustomMenu menu1 = CustomMenu(
    '100', 'res/images/mini_app_wechat_friend.png', 'Share To', true,
    shareKey: 'twitter');
    CustomMenu menu2 = CustomMenu(
    '101', 'https://staticintl.cloudcachetci.com/cms/backend-cms/8WGP653_%E5%BC%80%E5%8F%91%E8%80%85%E5%B7%A5%E5%85%B7%E9%80%9A%E7%94%A8.png', 'Custom', false);
    return [
    menu1,
    menu2,
    ];
    }
    @override
    Future<void> customMenuClick(String menuId, ShareData? shareMenu) async {
    /// callback for menu button click
    print("click menuId:$menuId shareMenu:$shareMenu");
    throw UnimplementedError();
    }

    Mini-program state change event

    When mini-program start, go foreground, go background and closed, host Flutter app can be notified by overriding onMiniProgramStateChange method.
    example code:
    @override
    Future<void> onMiniProgramStateChange(
    String appId, MiniProgramState state) async {
    print("app state change: appid=$appId, state=$state");
    }

    Log event

    If important log message appears, it will also be delivered to host app. Override log method to record these messages.
    example code:
    @override
    Future<void> log(String message) async {
    print(message);
    }

    Analysis event

    You can capture and record analysis events by implementing reportEvent method. These events including mini-program user interaction activities and crashes.
    example code:
    @override
    Future<bool> reportEvent(int eventId, String eventName, AppInfo appInfo,
    Map<Object?, Object?> params) async {
    print("reportEvent:$eventName appinfo:$appInfo params:$params");
    // TODO: implement reportEvent
    return Future.value(false);
    }

    APIs

    Future<void> startMiniAppWithId(String appId, MiniStartOptions? options)
    Start a mini program with given appId
    appId: The app id of mini program.
    options: Start options of this mini program.
    Future<void> startMiniAppWithLink(String link, MiniStartOptions? options)
    Start a mini program with given link
    link: The uri link to start.
    options: Start options of this mini program.
    Future<ScanResult?> scan()
    Start a new page to scan for QR codes, returns a ScanResult if found one.
    Future<List<AppInfo>?> getRecentList()
    Get a list of recent opened mini programs
    Future<List<AppInfo>?> searchMiniApp(String keyword,
    {int pageIndex = 0, int pageSize = 0})
    Search for online mini programs with given keyword
    keyWord: Keyword of mini program to search.
    pageIndex: Page to return if pageSize has a none-zero value, which means paging is enabled.
    pageSize: The max size of a page returned by server. When set to 0, paging will be disabled.
    Future<void> stopMiniApp(String appId)
    Stop mini program with given app ID
    appId: The app id of mini program.
    Future<void> stopAllMiniApp()
    Stop all running mini programs
    Future<void> deleteMiniAppCache(String appId,
    {int appVerType = 0, String? ver
    Remove all local data of mini program with given ID
    appId: the app id of mini program
    appVerType: type of mini program
    version: version of mini program to remove
    Future<AppInfo?> currentMiniApp()
    Return information for current foreground running mini program
    Future<void> preDownloadMiniApp(List<String> appIdList,
    {bool isDownload = false})
    Preload information for online mini programs
    appIdList: a list of app IDs for mini programs to load.
    isDownload: if set to true, mini program package will be downloaded after preload, default to false.
    void registerOpenApiHandler(OpenApiHandler handler)
    Register handler for sdk to send open api event to your flutter code. These events are triggered when mini-program require third-party information or action, such as, account login, request payment or get user information.
    handler: method ref to handle open api event.
    void registerPlatformEventHandler(TcmppPlatformEventHandler handler)
    Register handler for sdk to send platform-related event to your flutter code.These events may query information about your flutter application or notify flutter when user interact with mini program container.
    handler: method ref to handle platform event
    void registerMiniAppApi(String apiName, TcmppMiniAppApiHandler apiHandler)
    Define customised mini program api and associate api handler.apiName: name of your customised api, mini program can use this api by calling wx.(apiNme).
    apiHandler: function to handle this api call
    void setAccount(AccountInfo? info)
    Set account information of current logged in user for data isolation and user information display
    info: information of current logged in account, null if not logged in.
    Future<void> setLocale(String language,
    {String? region, String? variant})
    Set localization of mini-programs.must be set before mini-program launched.language: language of mini-programs. Should be an ISO 639 alpha-2 or alpha-3 language code.regin: region code of locale. Should be an ISO 3166 alpha-2 country code.variant: any arbitrary value used to indicate a variation of locale.
    Future<void> setTheme(MiniTheme theme)
    Set theme of mini-program container.must be set before mini-program launched.theme: light mode, dark mode or use system setting.

    Classes

    MiniStartOptions
    class MiniStartOptions {
    /// entry path of mini program
    String? entryPath;
    
    /// is always update mini program when start
    bool? isForceUpdate;
    
    /// string param passed to mini program when start
    String? params;
    }
    ScanResult
    class ScanResult {
    /// result string of qrcode or barcode contains
    String? result;
    
    /// the type of code
    String? scanType;
    
    /// charset of result string
    String? charset;
    }
    AppInfo
    class AppInfo {
    /// MiniProgram id
    String appId;
    
    /// MiniProgram package type (release, dev, etc.). See [AppVerType]
    int appVerType;
    
    /// MiniProgram version
    String version;
    
    /// MiniProgram name
    String? name;
    
    /// MiniProgram icon url
    String? iconUrl;
    
    /// MiniProgram description
    String? appIntro;
    
    /// Developer of MiniProgram
    String? appDeveloper;
    
    /// MiniProgram release time
    int time;
    }
    AppVerType
    /// Consts for MiniProgram package type. see[AppInfo]
    class AppVerType {
    static const int online = 0;
    static const int develop = 1;
    static const int preview = 2;
    static const int experience = 3;
    }
    AccountInfo
    class AccountInfo {
    /// Unique id of current account
    String? uid;
    /// Url of avatar image
    String? avatarUrl;
    /// Name of current account
    String? accountName;
    }
    OpenApiHandler
    abstract class OpenApiHandler {
    /// Called when mini-program invoke wx.requestPayment, requesting third-party payment action
    ///
    Future<Map<String, dynamic>> requestPayment(
    AppInfo appInfo, Map<Object?, Object?> params);
    
    /// Called when mini-program invoke wx.getUserProfile, requesting host app's user information
    ///
    Future<Map<String, dynamic>> getUserProfile(
    AppInfo appInfo, Map<Object?, Object?> params);
    
    /// Called when mini-program invoke wx.login, requesting host app's login certificate
    ///
    Future<Map<String, dynamic>> login(
    AppInfo appInfo, Map<Object?, Object?> params);
    
    /// Called when mini-program invoke wx.checkSession, requesting host app's login state
    /// check if login expired
    ///
    Future<Map<String, dynamic>> checkSession(
    AppInfo appInfo, Map<Object?, Object?> params);
    
    /// Called when mini-program invoke wx.getUserInfo, deprecated by wx.getUserProfile
    /// compatibility for earlier mini-program api
    ///
    Future<Map<String, dynamic>> getUserInfo(
    AppInfo appInfo, Map<Object?, Object?> params);
    
    /// Called when mini-program invoke wx.getPhoneNumber, get current user's phone number
    ///
    Future<Map<String, dynamic>> getPhoneNumber(
    AppInfo appInfo, Map<Object?, Object?> params);
    }
    TcmppPlatformEventHandler
    abstract class TcmppPlatformEventHandler {
    Future<String> getAppName() async {
    return "";
    }
    Future<String> getAppVersion() async {
    return "";
    }
    Future<void> log(String message) async {}
    Future<List<CustomMenu>> getCustomMenus() async {
    return [];
    }
    Future<void> customMenuClick(String menuId, ShareData? shareMenu) async {}
    Future<void> onMiniProgramStateChange(
    String appId, MiniProgramState state) async {}
    Future<bool> reportEvent(int eventId, String eventName, AppInfo appInfo,
    Map<Object?, Object?> params) async {
    return false;
    }
    }
    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