Skip to content

Custom Api

invokeNativePlugin

Mini program sdk provides an interface that can realize some open platform APIs that can be directly passed to the host client for implementation, such as logging in, obtaining user information, etc.; some host clients can be extended to maintain the consistency of UI and functions, such as scanning codes, sharing, etc.; custom APIs can also be extended to pass through the host client.

How to use the mini program

js
 var opts = {
   api_name: '', // Name of the API
   success: function(res) {},
   fail: function(res) {},
   complete: function(res) {},
   data: { // Input Parameters
      name : 'kka',
      age : 22,
      data: {...}
   }
 }
 wx.invokeNativePlugin(opts); // Invocation

Methods

MethodDescription
View onCreateLoadingView()Create a loading view, allowing the host client to present the mini program/mini game brand and custom display style. If it returns empty, the default loading view will be displayed.
View onCreateCapsuleView()Create a pill button, allowing the host to customize the pill button style. If it returns empty, the default pill button will be displayed.
boolean onShowMenu()Fired when the '...' more button is clicked, if onCreateCapsuleView returns null and onShowMenu returns false, the default menu is shown.
void onExit()Triggered when the '〇' exit button is clicked. If onCreateCapsuleView returns empty and onExit returns false, the default action is performed.
boolean onAuthorize(JSONObject params, Value Callback callback)wx.authorize interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onOpenSetting(JSONObject params, ValueCallback callback)wx.openSetting interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onGetSetting(JSONObject params, ValueCallback callback)wx.getSetting interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onLogin(JSONObject params, ValueCallback callback)wx.login interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onRefreshSession(JSONObject params, ValueCallback callback)wx.checkSession interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onRequestPayment(JSONObject params, ValueCallback callback)wx.requestPayment interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onGetUserInfo(JSONObject params, ValueCallback callback)wx.getUserInfo interface implementation, if it returns false, it directly notifies wx api call failure, for details, please refer toonGetUserInfo
boolean onShareAppMessage(JSONObject params, ValueCallback callback)wx.shareAppMessage interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onNavigateToMiniProgram(JSONObject params, ValueCallback callback)wx.navigateToMiniProgram interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onScanCode(JSONObject params, ValueCallback callback)wx.scanCode interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onOpenDocument(JSONObject params, ValueCallback callback)wx.openDocument interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onOpenLocation(JSONObject params, ValueCallback callback)wx.openLocation interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onChooseLocation(JSONObject params, ValueCallback callback)wx.chooseLocation interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onPreviewImage(JSONObject params, ValueCallback callback)wx.rviewImage interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onChooseImage(JSONObject params, ValueCallback callback)wx.chooseImage interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onChooseVideo(JSONObject params, ValueCallback callback)wx.chooseVideo interface implementation, if it returns false, it directly notifies wx api call failure.
boolean onShowToast(JSONObject params, ValueCallback callback)wx.showToast and wx.showLoading interface implementation, if it returns false, it uses the default style display.
boolean onHideToast(JSONObject params, ValueCallback callback)wx.hideToast and wx.hideLoading interface implementation, if it returns false, it uses the default style display.
boolean onShowModal(JSONObject params, ValueCallback callback)wx.showModal interface implementation. If false is returned, the default style will be used for display.
boolean onInvokeWebAPI(String event, JSONObject params, ValueCallback callback)Implement custom wx api. If false is returned, directly notify wx api that the call failed. For details, please refer toonInvokeWebAPI
boolean onReportEvent(String event, Map params)For details, please refer to onReportEvent

boolean onGetUserInfo(JSONObject params, ValueCallback callback)

js
-(void)onGetUserInfoWithParams:(NSDictionary *)params inApp:(NSString *)appId callbackHandler:(WebAPICallbackHandler)handler {
    //TODO
        NSDictionary* userInfo = @{
                                   @"nickname" : @"morven",
                                   @"headimgurl" : @"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKav1ib8qG43xy0resTpgfeCqH00vRpHicEdk0kKMxqTMMUG1WmBuAdgB2tmCf6joGVKlGbsicelhluw/0",
                                   @"sex" : @(1),
                                   @"province" : @"Guangdong",
                                   @"city" : @"Shenzhen",
                                   @"country" : @"China"
                                   };
        NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:1];
        NSMutableDictionary* userInfoDic = [NSMutableDictionary dictionaryWithCapacity:6];
        NSMutableDictionary* resultDataDic = [NSMutableDictionary dictionaryWithCapacity:1];
        [userInfoDic setValue:userInfo[@"nickname"] forKey:@"nickName"];
        [userInfoDic setValue:userInfo[@"headimgurl"] forKey:@"avatarUrl"];
        [userInfoDic setValue:userInfo[@"sex"] forKey:@"gender"];
        [userInfoDic setValue:userInfo[@"province"] forKey:@"province"];
        [userInfoDic setValue:userInfo[@"city"] forKey:@"city"];
        [userInfoDic setValue:userInfo[@"country"] forKey:@"country"];

        NSData *data=[NSJSONSerialization dataWithJSONObject:userInfoDic options:NSJSONWritingPrettyPrinted error:nil];

        [resultDataDic setValue:[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] forKey:@"data"];
        [result setValue:resultDataDic forKey:@"data"];
        [result setValue:@"getUserInfo:ok" forKey:@"errMsg"];

    if (handler) {
        //success
        handler(result, nil);
    }
}

onInvokeWebAPI

boolean onInvokeWebAPI(String event, JSONObject params, ValueCallback callback)

js
- (BOOL)onInvokeWebAPIWithEvent:(NSString*)event params:(NSDictionary*)params callbackHandler:(WebAPICallbackHandler _Nullable)handler {
    NSLog(@"onInvokeWebAPIWithEvent, event:%@, params:%@", event, params);
    if (handler) {
        handler(@{@"errMsg" : @"onInvokeWebAPIWithEvent"}, nil);
    }
    return YES;
}

onReportEvent

boolean onReportEvent(String event, Map<String, String> params)

js
Event reporting. The events are as follows:
 1. Launch the mini program, event: MS_EVENT_LAUNCH, keys for params: pagePath, d;
 2. Duration of mini program usage, event: MS_EVENT_USE_TIME, keys for params: useTime, startId, appId; the unit of useTime is milliseconds;
 3. Successful launch of the mini program, event: MS_EVENT_LAUNCH_SUCCESS, keys for params: appId.
 4. Opening a page within the mini program, event: MS_EVENT_OPEN_PAGE, keys for params: pagePath, appId.
 5. Failure to launch the mini program, event: MS_EVENT_LAUNCH_FAIL, keys for params: pagePath, reason, appId.

General Interface

js
let opts = {
  api_name: "luffaWebRequest",
  data: {
    methodName: "Operation", // Assuming "Operation" means Operation
  },
  success: (res) => {
    console.log(res);
  },
  fail: (res) => {
    console.log(res);
  },
};
wx.invokeNativePlugin(opts);

Note: VS Code can use wx or the following code:

js
declare global {
    var wx: any
}
// To avoid error prompts

Mini Program & Mini Game DAPP Call Method: Obtaining Luffa ID, Avatar, Nickname, and Wallet Address

js
//Randomly generate a string of length 16. You can also implement this method yourself.
public create16String() {
        var len = 16
        let strVals = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        let maxLen = strVals.length;
        let randomStr = '';
        for (var i = 0; i < len; i++) {
            randomStr += strVals.charAt(Math.floor(Math.random() * maxLen));
        }
        return randomStr;
}


getUserInfo() {
    var cur = this
        let opts = {
            api_name: 'luffaWebRequest',
            data: {
                uuid: this.create16String(), //Randomly generate a string of length 16
                methodName: "connect",
                initData: {
                    network: "endless",   //endless is the main network chain, and the test network needs to change to the corresponding value
                },
		// To display your own icon in the pop-up authorization connection UI, you need to add the metadata attribute
		metadata:{
		  superBox:true,
		  url:"https://********",//URL cache identification, the same URL, connect again without popping up the UI
		  icon:"*****" //The address of the icon url [temporary, to be removed later]
		}
                from: "",
                data: {},
            },
            success: (res) => {
                console.log(res)
                var address = res.data.address //address
                var hashHead = res.data.avatar //hash avatar base64
                var cid = res.data.cid  //luffa CID Avatar
		var name=res.data.nickname //luffa cid avatar
		var uid=res.data.uid   //luffa ID
		// res.data.avatar_frame  is the range where the CID avatar is captured and displayed.
            },
            fail: (err) => {
                console.log(err)
            }
        }
        if ( wx) {
             wx.invokeNativePlugin(opts);
        }
}

Payment Function

1.Contract Payment DAPP Call Method

1.1 Encrypted Parameter Synthesis into a 16-bit String_V1.3 (Array parameters are not supported)

js
////////Game Contract DATA  ////////

module: "Hm3g4xXM4JHt5EwFUcvVZ8RthR4KWUnR51fKHCbnKkiZ",//The default contract address is EDS. If you want to use other currencies, you must specify the currency in the contract.

moduleName: "poker_b",//Module Name
functionName: "deposit",//Method Name
data: JSON.stringify({
//The following parameters are required by the contract. The parameters required by each game may be different and will be determined according to the contract.
 "1_u64_roomId": "32847238974289",//1 Represents the first parameter u64 represents the parameter typeroomId 自己的參數名
 "2_u128_amount": String(10 * 100000000),  //2 Represents the second parameter u128 represents the parameter type amount its own parameter name
  }),
argsData: [] //Keep


////////DATA corresponding to the transfer ////////

module: "0x1",//[Fixed]
moduleName: "endless_account",//[Fixed]
functionName: "transfer",//[Fixed]
data: JSON.stringify({
       "1_address_address": "*********",// The other party's wallet address
       "2_u128_amount": String(n* 100000000),  // n is endless amount
}),
argsData: []
////////////////

 packageTransaction() {
        var cur = this
        let opts = {
            api_name: 'luffaWebRequest',
            data: {
                uuid: this.create16String(),//Randomly generate a string of length 16
                from: *****,//Your own wallet address
                methodName: "packageTransaction",
                initData: {
                    network: "endless",
                },
                data:DATA,//See definition above
            },
            success: (res) => {
                console.log(res.data.rawData)//Obtain an encrypted 16-bit string for later payment
            },
            fail: (err) => {
                console.log(err)
            }
        }
        if (wx) {
             wx.invokeNativePlugin(opts);
        }

    }

1.2 Encrypt Parameters to Combine 16-bit String_V2.3 (Supports Array Parameters)

js
let opts = {
    api_name: 'luffaWebRequest',
    data: {
        uuid: this.create16String(),
        from:  ****,// Your wallet address
        methodName: "packageTransactionV2",
        initData: {
              network: "endless", // "endless" is mainnet, "ends" is testnet
        },
        data: {
            data: JSON.stringify({
                "payload": {// payload remains fixed
                    "function": ContractAddress::ModuleName::FunctionName,// e.g., "31c86388c45acec19a57fe844faa0c553cbded8ced01fc5fab48904cd84777c1::turntable::play_free_turntable_sponsored"
                    "functionArguments": [],// e.g., ["HAXAM8Q6RGJnfKc4MpMQKWTQmSRYNQkkWzy8Qjudn8ss","aaabbbb","123","123"]
                    "typeArguments": [],// e.g., ["address","String","u64","u128"]
                    "typeEnum": []
                },
                "secondarySignerAddresses": [
                    "9CiQTrLPDht1g7YhsDcV4LsjCrmQWEdFaxnHM8UDTydV"
                ],// Multi-signature address collection. Not needed for single sig.
                "feePayer": "" // Gas fee payer
            })
        },
    },
    success: (res) => {
        console.log(res) // RawData2 = res.data.rawData

    },
    fail: (err) => {
        console.log(err)
    }
}
console.log(opts)
if (wx) {
    wx.invokeNativePlugin(opts);
}

2.Wallet Payment

js
 sendTransaction() {
        var cur = this
        let opts = {
            api_name: 'luffaWebRequest',
            data: {
                uuid: this.create16String(),//Randomly generate a string of length 16
                from: ****,//Your own wallet address
                methodName: "signAndSubmitTransaction",
                initData: {
                    network: "endless",
                },
                data:{
                    serializedTransaction: {
                        data:*****,//Encrypt parameters into 16-bit string
                    },
                },
            },
            success: (res) => {
                console.log(res.data.hash) //The returned hash
            },
            fail: (err) => {
                console.log(err)
            }
        }
         if ( wx) {
             wx.invokeNativePlugin(opts);
        }

    }

Mini-program & Mini-game Call DAPP Verification Function

1.Signature Verification API

js
let opts = {
    api_name: 'luffaWebRequest',
    data: {
        uuid: this.create16String(),
        methodName: "signMessageV2",
        initData: {
            network: "eds", // Assuming "eds" is the network identifier
        },
        from: "",
        data: {
            message:"Hello dapp", // The signature text seen by the user, also included in `fullMessage`
            nonce:1 // DApp must generate a nonce to prevent replay attacks
address:false, // Optional parameter, default false. Whether to include wallet address in the signed message (affects `fullMessage`)
application:false, // Optional parameter, default false. Whether to include current page origin in the signed message (affects `fullMessage`)
chainId: false, // Optional parameter, default false. Whether to include chain ID for multi-chain verification (affects `fullMessage`)
        }
    },
    success: (res) => {
        console.log(res)
        // res.data.publicKey  Public Key
        // res.data.signature  Signature Result
        // res.data.fullMessage *The full content that was signed (multi-line string)
    },
    fail: (err) => {
        console.log(err)
    }
}
wx.invokeNativePlugin(opts);

2.Signature Verification API [Server-side]

API-URL(post): https://16585928939296.endlesshub.link/verify/endless/verify

js
//Parameters returned by the corresponding mini program SDK

{
    "key":"publickey",
    "sign":"signature",
    "msg":"fullmessage"
}
// return:
{
    "msg": "Operation succeeded",
    "code": 200,
    "data": true // "true" indicates whether the verification has been passed, while "false" indicates it has not
}

3.Multi-signature Verification (Not currently supported)

js
 let opts = {
      api_name: 'luffaWebRequest',
      data: {
          uuid: this.create16String(),
          from:  ****,// Your wallet address
          methodName: "signBuildTransaction",
          initData: {
              network: "endless", // "endless" is mainnet, "ends" is testnet
          },
          data: {
              transactionData:RawData2, // Raw transaction data from packageTransactionV2
          },
      },
      success: (res) => {
          console.log(res)
      },
      fail: (err) => {
          console.log(err)
      }
  }
  wx.invokeNativePlugin(opts);

Sharing Function

1.Active Sharing

Parameters are obtained through wx.getEnterOptionsSync().extendData in the wx.onshow listener interface. Get "Share with Parameters"

js
share(params) {
    var tab = {
        title: "Title",
        detail: "Content",
        imageUrl: "",//The URL of the large image in the middle. The image size should meet the ratio of 2:1. The larger the pixel, the clearer it is. The main content is best placed in the middle. For example, https://ertlnx.site/src/findingTreasure.jpg
        methodName: "share"
    }

    if (params) {
        tab["params"] = params
    }
    let opts = {
        api_name: 'luffaWebRequest', // Custom API name
        data: tab,
        success: (res) => {
        },
        fail: (err) => {
        }
    }
    wx.invokeNativePlugin(opts); // Calling custom API
}

2.Share Button

2.1.In mini-game mode, add it upon launch

js
wx.showShareMenu({
  withShareTicket: true,
});

wx.onShareAppMessage(() => {
  //Call the above active sharing method
});

2.2.In mini-program mode, add it in onLaunch

wx.showShareMenu({
        withShareTicket: true
    });

2.3Add method on page

onShareAppMessage(() => {
 //Call the above active sharing method
})

Chat Function

1.Add Friend or Chat with Friend

js
curUrl= https://callup.luffa.im/p/{uid*}

2.Group Chat or Join Group

js
curUrl= https://callup.luffa.im/g/{group id*}

3.Add Channel

js
curUrl= https://callup.luffa.im/c/{channel id*}
js
var curUrl;
let opts = {
  api_name: "luffaWebRequest",
  data: {
    methodName: "openUrl",
    url: curUrl,
  },
  success: (res) => {
    console.log(res);
  },
  fail: (res) => {
    console.log(res);
  },
};
wx.invokeNativePlugin(opts);

Get Luffa's Language Settings

js
let opts = {
  api_name: "luffaWebRequest",
  data: {
    methodName: "language",
  },
  success: (res) => {
    console.log(res);
    // res.result is the current luffa language
  },
  fail: (res) => {
    console.log(res);
  },
};
wx.invokeNativePlugin(opts);

Mini Program Collection

js
let opts = {
  api_name: "luffaWebRequest",
  data: {
    methodName: "navigateToMiniProgram",
    url: "tcmppn3u4by5l18://applet/?appId=*****(required parameter)+[&params=*****(optional parameter)]"", //Mini Program Link
  },
  success: (res) => {},
  fail: (res) => {
    console.log(res);
  },
};
wx.invokeNativePlugin(opts);