Light application H5 new version JS
H5 version light application component call
H5 version light application component refers to the light application mobile version (embedded in Weibo client Center) A JavaScript function package that evokes the native functions of Weibo provided for accessing applications.
Allow light applications to achieve functions such as obtaining the current network status, obtaining positioning information, triggering client QR code scanning, viewing large pictures, etc. It also provides some components for the access party to call, such as shared addresses Book component.
Conditions of use
Weibo Android and iPhone official client version 5.3.0 or above built-in browser.
Set a secure domain name
- Click My Apps at the top and open the light app that needs to be configured
- Select "Application Information" in the left navigation ”
- Edit the basic information of the application, fill in the secure domain name and save it
Note: The subdomain name configured with the secure domain name will also obtain the calling permission of JSBridge
Introduce JS files
To use the H5 version of the JS API, you need to introduce a JS file first.
This JS file will use the global namespace WeiboJS, which provides three JS methods:
- • WeiboJS.init() Purpose: Initialize before calling Bridge
- • WeiboJS.invoke() Purpose: Call Bridge's Action or component
- • WeiboJS.on( ) Purpose: Monitor Bridge events
The following are explained one by one:
WeiboJS.init()
Pass Initialize using the `init` method of `window.WeiboJS`.
- Parameter list:
- `appkey`: Required, appkey for light application
- `debug`: Optional, debugging switch
- `timestamp`: Required, the timestamp used in the signature
- `noncestr`: Required, the random string used in the signature
- `signature`: Required, the calculated signature, See the end of the document for the signature method.
- `scope`: Required, the API list that the light application needs to call is a string array
- `callback`: Required, after the initialization is successful or failed Callback functions, WeiboJS.invoke() or WeiboJS.on() need to wait until the callback is successful before executing
For example:
WeiboJS.invoke()
Call the bridge action through the `invoke` method of `window.WeiboJS`.
For example:
document.write('The network status is' params.network_type);
} else {
if (code == WeiboJS.STATUS_CODE.NO_RESULT) {
// do something.
The first parameter is the action to be called, the second is the parameter list, and the third is the callback function.
Action list
getNetworkType Get network status
-Parameter list: None
-Return value : `{"network_type": "wwan"}`, `wwan` represents 2G or 3G, `wifi` represents WIFI, `fail` represents no network
getBrowserInfo Get basic browser information
- Parameter list: None
- Return value: `{"clientVersion": "5.3.0", "isWeiboClient": true, " browserType": "normal"}` Among them, `clientVersion` represents the client version number, `isWeiboClient` represents whether the current Weibo client is, `browserType` represents the browser type: normal=normal browser, topnav=bottomless browser, infopage=object text page browsing Device
checkAvailability Check API availability
- Parameter list: api_list String array, indicating the api list that needs to be checked, for example: ["getNetworkType", "setBrowserTitle"]
- Return value: `{"getNetworkType": true, "setBrowserTitle": true}` where true means there is permission to call, false means there is no permission to call
setBrowserTitle Set the top navigation title
- Parameter list:
- `title`: New title, required
- Return value: None
- Note: The title set by this method has the highest priority
- Error code:
- `MISSING_PARAMS`: The `title` parameter was not passed
openMenu Open the menu in the upper right corner of the browser
-Parameter list :None
- Return value: `{"selected_code": 1001, "selected_title": Share to Weibo}` where selected_code represents the code corresponding to the button selected by the user. The unknown button is 0. See the general button Appendix 2, selected_title represents the copy of the menu selected by the user
setMenuItems sets the menu in the upper right corner of the browser [Share, add follow]
- menus: ["shareToWeibo", "follow"], the name of the menu, up to 5 items
- content: default copy
- Return value: None
- Note: follow focuses on the owner of the appkey
For example:
if (success) {
document.write('网络状态是' params.network_type);
} else {
if (code == WeiboJS.STATUS_CODE.NO_RESULT) {
// do something.
}
}
});
setSharingContent Set sharing content
- Parameter list: {"icon": "", "title": "", "desc": ""} where icon represents the image URL, title represents the title, desc represents the copy
- Return value: None
- Note: What is set here is the default copy
## set for sharing to the third-party platform #openImage View large image
- Parameter list:- `url`: currently selected image src; `urls`: in the current page All pictures src, used to support horizontal sliding viewing
- `MISSING_PARAMS`: `url ` and `urls` need to pass at least one
scanQRCode Scan the QR code
-Parameter list: None- Return value: `{"result": "http://weibo.com"}`- Error code:- `USER_CANCELLED`: User Scan canceled`SERVICE_FORBIDDEN`: The device does not have a camera or the user is not allowed to use the camera
pickImage Get photos
- Parameter list:- `source`: `camera` is to take pictures, others are to select from the album
- `USER_CANCELLED`: The user canceled the image selection`SERVICE_FORBIDDEN`: The device does not have The camera or user is not allowed to select pictures
pickContact Select contact
-Parameter list:- `count`: 1, indicating the maximum number of people selected
"}]`
- Error code:- `USER_CANCELLED`: The user canceled the selection`SERVICE_FORBIDDEN`: The service is unavailable
getLocation Location
- Parameter list: None- Return value: `{"lat": 100, "long": 100 }`- Error code:- `SERVICE_FORBIDDEN`: Location service is not available`NO_RESULT`: Failed to obtain location
login evokes the login function
- Parameter list:- `redirect_uri`: The address of the callback after login, required . And the URL must start with http://apps.weibo.com, URLs from any other domain names are not accepted
"redirect_uri" : encodeURIComponent("http://apps.weibo.com/test/1406758883/2I8KtA/demo/game/yangtuo")
}, function (params, success, code) {});
#menuItemAvailableGet available menu items
##WeiboJS.on("audioMetersChange", function(params){
Client supported version: 5.4.5
cashier Weibo payment
Parameter list :
sign_type: Signature type, currently only supports RSA
sign: Signature type
appkey: Merchant’s Appkey, distinguishing different businesses of the merchant
seller_id : Merchant Weibo id
out_pay_id: Merchant order number, merchant website unique number, 6-64 digits
notify_url: Asynchronous notification address
return_url: Callback after payment is completed Page address
subject: Product name
total_amount: Total price of the product in cents
body: Product description
Return value: None
Invocation example:
sign : "",
appkey: "",
seller_id: ,
out_pay_id: "",
notify_url:"",
return_url:"",
subject:" ",
body:""
total_amount:,
}, function(params){
safeAlert(JSON.stringify(params));
});
Status Code list
The status code will be provided in the action callbackILLEGAL_ACCESS: The illegal call
INTERNAL_ERROR: The client internal processing error
ACTION_NOT_FOUND: The client does not implement this action
NO_RESULT: The client did not obtain the result
USER_CANCELLED: The user canceled the operation
SERVICE_FORBIDDEN: The relevant services are not enabled or prohibited (such as location services, photo album permissions)
The webpage is processed by comparing the callback code value with the above value
WeiboJS.on()
Sometimes native will send some event notifications to the web page, and the web page can selectively receive them.
document.write('The network status has changed to:' params.network_type);
});
Event list
networkTypeChanged Network status change
-Return result:
- `network_type`: changed state, `wwan` or `wifi` or `fail`
##menuItemSelected Select a browser menu item
- Return result:- `selected_code`: The code corresponding to the button selected by the user. The unknown button is 0. For general buttons, see Appendix 2 `selected_title: The button title selected by the user
orientationChange screen rotation event
-Usage conditions: None- Return result:
- `orientation`: The status of the screen orientation, that is, the value of window.orientation
Shared address book component [need to apply for whitelist]
The shared address book component is used by the access party to obtain the Weibo delivery address of the current Weibo user. It is currently in the internal trial stage and is not open to all access parties. The components come in two forms: PC version: H5 version:The first step is to use the shared address book component. Application is required. Please send the appkey to wanglei25@staff.weibo.com to apply for permission to use this component.
The second step is code development. The shared address book component provides two Actions for calling:
PC version calling method: (You can also click here)
1. Get the default delivery address
App.trigger('deliverAddress:default', function(addr){ /* callback function*/ });
2. Select other delivery addresses (addresses can be added, deleted, or modified )
App.trigger('deliverAddress:change', function(addr){ /* callback function*/ });
Complete Web version calling example:
<head>
<meta charset="utf-8" />
<title>Shared Address Book Component Web Version</title>
</head>
<body>
<div id="address">Read shipping address Hit...</div>
<script src="http://tjs.sjs.sinajs.cn/open/thirdpart/js/frame/appclient.js" charset="utf-8"></script>
<script>
function $(o){
return document.getElementById(o);
}
// 显示地址组件返回的地址
function showAddress(addr){
var address = $("address");
if(addr == null){
address.innerHTML = "No default shipping address";
} else {
address.innerHTML = addr.name " " addr.mobile " " addr.address;
showAddress);
//Bind a click event to the address area. Click the area to invoke the address component selection interface
('deliverAddress:change', showAddress);
#
H5 version calling method:
1. Get the default delivery address
WeiboJS.invoke("deliverAddress:default", {}, function(addr) { /* Callback function */ });
2. Select another delivery address (you can add, delete, or modify the address)
WeiboJS.invoke("deliverAddress:change ", {}, function(addr){ /* callback function*/ });
Complete H5 version calling example:
<html>
<head>
; <meta charset="utf-8" />
; <title>Shared Address Book Component H5 Version</title>
</head>
<body>
<div id="address">Reading shipping address...</div>
<script src="http://tjs.sjs.sinajs.cn/open/thirdpart/js/pageapp/mobile/jsapi.js" charset="utf-8"></script>
<script>
{
var address = $("address");
if(addr == null){
address.innerHTML = "No default shipping address";
} else {
address .innerHTML = addr.name " " addr.mobile " " " addr.address;
}
}
// Get the default delivery address of the currently logged in user
WeiboJS.invoke("deliverAddress:default ", {}, showAddress);
Bind click events to the address area, click this area, evoke the address component selection interface
## WeiboJS.invoke("deliverAddress:change", {}, showAddress);
Light application H5 bottom guide [need to apply for whitelist]
Light application in Weibo client is now displayed in the built-in browser of the object text page (there is a link at the bottom Like button), it has certain flaws, such as:
- does not support sharing of internal pages. For example, if there is an object in your application, click the link in the object, and the iframe will jump to a non-object URL. At this time, if you click forward, you will still share the information of the object that just came in.
- Does not support customized sharing copywriting. For the publisher evoked by clicking forward, the copy is fixed and you cannot modify it.
- Poor customizability
Currently, Light App provides an H5 bottom navigation component, which is implemented with HTML JavaScript and is almost the same as the current object text page bottom navigation UI. But it can support sharing of internal pages, and the copy can be customized as you like. It is currently in the internal trial stage and is not open to all access parties.
Access method:
The first step is to use the light application H5 bottom guide. Application is required. Please send the appkey to wanglei25@staff .weibo.com applies for permission to use this component.
The second step is to introduce the JS of the mobile version of the light application component into the pages that need to support internal page sharing.
At this time, you can see the component directly.
The third step is to modify the default sharing copy.
"title" : "My sharing copy, write whatever you like, haha "
}, function(){});
Complete example:
<head>
<meta charset="utf-8" />
<title>Light application H5 bottom guide</title>
</head>
<body>
<script src= "http://tjs.sjs.sinajs.cn/open/thirdpart/js/pageapp/mobile/jsapi.js" charset="utf-8"></script>
<script>
WeiboJS.invoke('bottomNavigation:info', {
"title": "My sharing copy, write whatever you like, haha"
}, function(){});
;/script>
</body>
</html>
Full calling example:
Complete calling example:
alert(params.msg);
}
});
Light Application H5 Component Demo
Please use Weibo client to scan the QR code below to view the demo Demo:
For details of the interfaces involved in the Demo, please refer to the following documents:
Weibo Payment Application Access Guide: http://open.weibo.com/wiki/Weibo Payment Application Access Guide
Weibo API interface document: http://open.weibo.com/wiki/Weibo API
Appendix 1. Signature method
Note: In order to ensure the security of appsecret and ticket, the following steps need to be completed on the server side
Call the open platform interface, pass in appkey and appsecret to generate ticket:
POST https://api.weibo.com/oauth2/js_ticket/generate?client_id=APPKEY&client_secret=APPSECRET
返回值: { "result":true, "appkey":"", "js_ticket":"", // 获取到的 ticket "expire_time":7199 // ticket 的有效时间(秒) }
Note:
Calling this interface again within the validity period will cause the ticket to be refreshed, and the old one will be invalid directly. Therefore, the third party should cache the ticket on the server and only request to change the interface again when it is about to expire.
Generate signature string:
签名字符串 = "jsapi_ticket=[TICKET]&noncestr=[NONCESTR]×tamp=[TIMESTAMP]&url=[URL]"
Note: Please update the URL parameters in real time according to the actual address loaded by the current webview
Among them:
[TICKET]: the ticket obtained in the previous step [NONCESTR]: random string, needs to be consistent with the value in config [TIMESTAMP]: The current UNIX timestamp needs to be consistent with the value in config [URL]: The complete URL of the current page (without url encoding, without # and fragment)
Use sha1 algorithm to generate signature
签名 = sha1(签名字符串)
Appendix 2, menu encoding
Weibo: 1001
Friend circle: 1002
Private message: 1003
WeChat friends: 1004
Friend circle: 1005
Micro Friends: 1006
Micro Circle: 1007
Friends: 1008
News: 1009
QQ: 1010
Qzone: 1011
SMS: 1101
Email: 1102
System browser: 2001
Copy link: 2002
Font size setting: 2003