自定義API
invokeNativePlugin
小程序sdk提供接口,可實現一些開放平臺API可以直接透傳給宿主用戶端來實現,如登入、獲取用戶資訊等; 一些宿主用戶端可以擴展,以保持UI和功能的一致性,如掃碼,分享等; 也可以擴展自定義API,進行透傳宿主用戶端來。
小程序端使用方式
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); // InvocationMethods
| 方法 | 說明 |
|---|---|
| View onCreateLoadingView() | 創建加載視圖,允許宿主用戶端呈現小程序/小遊戲品牌和自定義顯示樣式,如返回空,則展示默認加載視圖。 |
| View onCreateCapsuleView() | 創建膠囊按鈕,允許宿主自定義膠囊按鈕樣式,如返回空,則展示默認膠囊按鈕。 |
| boolean onShowMenu() | 按一下'…'更多按鈕時觸發,如果onCreateCapsuleView返回空且onShowMenu返回false,則顯示默認選單。 |
| void onExit() | 按一下'〇'退出按鈕時觸發,如果onCreateCapsuleView返回空且onExit返回false,則執行默認操作。 |
| boolean onAuthorize(JSONObject params, Value Callback callback) | wx.authorize接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onOpenSetting(JSONObject params, ValueCallback callback) | wx.openSetting接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onGetSetting(JSONObject params, ValueCallback callback) | wx.getSetting接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onLogin(JSONObject params, ValueCallback callback) | wx.login接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onRefreshSession(JSONObject params, ValueCallback callback) | wx.checkSession接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onRequestPayment(JSONObject params, ValueCallback callback) | wx.requestPayment接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onGetUserInfo(JSONObject params, ValueCallback callback) | wx.getUserInfo接口實現,如返回false,則直接通知wx api調用失敗,詳情請參見onGetUserInfo |
| boolean onShareAppMessage(JSONObject params, ValueCallback callback) | wx.shareAppMessage接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onNavigateToMiniProgram(JSONObject params, ValueCallback callback) | wx.navigateToMiniProgram接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onScanCode(JSONObject params, ValueCallback callback) | wx.scanCode接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onOpenDocument(JSONObject params, ValueCallback callback) | wx.openDocument接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onOpenLocation(JSONObject params, ValueCallback callback) | wx.openLocation接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onChooseLocation(JSONObject params, ValueCallback callback) | wx.chooseLocation接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onPreviewImage(JSONObject params, ValueCallback callback) | wx.rviewImage接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onChooseImage(JSONObject params, ValueCallback callback) | wx.chooseImage接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onChooseVideo(JSONObject params, ValueCallback callback) | wx.chooseVideo接口實現,如返回false,則直接通知wx api調用失敗。 |
| boolean onShowToast(JSONObject params, ValueCallback callback) | wx.showToast和wx.showLoading接口實現,如返回false,則使用默認樣式展示。 |
| boolean onHideToast(JSONObject params, ValueCallback callback) | wx.hideToast和wx.hideLoading接口實現,如返回false,則使用默認樣式展示。 |
| boolean onShowModal(JSONObject params, ValueCallback callback) | wx.showModal接口實現,如返回false,則使用默認樣式展示。 |
| boolean onInvokeWebAPI(String event, JSONObject params, ValueCallback callback) | 實現自定義wx api,如返回false,則直接通知wx api調用失敗,詳情請參見onInvokeWebAPI |
| boolean onReportEvent(String event, Map params) | 詳情請參見 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.通用接口
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);注意: VS Code可以用可以使用wx或者使用以下代碼:
js
declare global {
var wx: any
}
// To avoid error prompts小程序&小遊戲取得luffa ID,頭像,暱稱,錢包地址 呼叫DAPP方式
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);
}
}支付功能
1.合約付款呼叫DAPP方式
1.1 加密參數合成16位字串_V1.0 (不支援陣列參數)
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 加密參數合成16位字串_V2.0 (支援陣列參數)
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.錢包支付
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);
}
}小程序&小遊戲呼叫DAPP驗證功能
1.簽章驗證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.簽章驗證API【服務端】
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.多簽驗證 (暫不支援)
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);分享功能
1.主動分享
参数在wx.onshow的监听接口下通过wx.getEnterOptionsSync().extendData 来获取「带参数的分享」
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.分享按钮
2.1.小遊戲模式下,在啟動的時候加入
js
wx.showShareMenu({
withShareTicket: true,
});
wx.onShareAppMessage(() => {
//Call the above active sharing method
});2.2.小程序模式下,在onLaunch裡加入
wx.showShareMenu({
withShareTicket: true
});2.3頁面上添加方法
onShareAppMessage(() => {
//Call the above active sharing method
})聊天功能
1.加好友 或 好友聊天
js
curUrl= https://callup.luffa.im/p/{uid*}2.群聊天 或 加入群
js
curUrl= https://callup.luffa.im/g/{group id*}3.添加频道
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);獲取Luffa設定的語言
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);小程序合集
js
let opts = {
api_name: "luffaWebRequest",
data: {
methodName: "navigateToMiniProgram",
url: "tcmppn3u4by5l18://applet/?appId=*****(required parameter)+[¶ms=*****(optional parameter)]"", //Mini Program Link
},
success: (res) => {},
fail: (res) => {
console.log(res);
},
};
wx.invokeNativePlugin(opts);