How mobile web App can share multi-platform function _javascript skills

Source: Internet
Author: User
Tags datetime http request readline sha1 sha1 encryption time limit ticket browser cache

In other words, app has a common access to the social platform, Web page sharing has a very good framework, but with the continuous development of HTML5, mobile Web pages more and more into our lives, then how to complete the sharing on our mobile phone? said that the major sharing platform for Android, iOS SDK, as developers, we only need to integrate the SDK in our project, through the provision of external interface, we can easily complete the sharing of the function; web pages, there are many excellent sharing framework on the Internet, For example: Bshare sharing, jiathis sharing, we can easily integrate into our project, but the mobile Web page to achieve the sharing of the need for us to do a little bit, thinking that this time, we can invoke the user to install the client to share, here need to specifically mention the micro-letter sharing, When we share the Web page, usually pop up a shared two-dimensional code, we use the micro-mail app scan and then share, mobile phone we can not operate this way, we need to when the user selected micro-letter sharing, open the app directly to share, here will spit the micro-letter sharing JS SDK, When I first touched this stuff, also thought that as long as the completion of the operation can be customized to share, with a variety of pits, and finally found that the micro-letter JS SDK is only a temporary cache of our custom content, when we need to share, or through the micro-letter in the upper right corner of the button to complete the operation. Okay, no more nonsense, into today's theme, Next I will follow through the hyperlink to complete Sina, QQ, QQ space, Tencent Micro Bo share, and then for everyone based on the C # Platform of micro-letter JS SDK sharing components of the signature logic, and finally lead everyone to complete the mobile Web side to share.

  Enter 1th: Complete the sharing via hyperlinks

For common social platforms we can basically share content through hyperlinks, except for micro-letters that don't support this kind of sharing, which can be easily customized and easy to use.

function Sharesina () {//share to Sina Weibo var sharesinastring = ' http://service.weibo.com/share/share.php?title= ' + $ ("#title").
Val () + ' &url= ' + $ ("#url"). Val ();
Window.location.href = sharesinastring;
function Shareqqzone () {var p = {url:location.href, Showcount: ' 0 ',/* whether to display the total share, display: ' 1 ', does not show: ' 0 '/desc: ',/* default sharing reason (optional) * *
Summary: ", * * Share summary (optional) */title: ' ', * * share title (optional)/site: ' Full art net ', * * share sources such as: Tencent Network (optional)/pics: ', * * share the path of the picture (optional) */style: ' 203 ',
Width:98, height:22}; Share to QQ space var sharesinastring = ' http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?title= ' + $ ("#title").
Val () + ' &url= ' + $ ("#url"). Val () + ' &site= ' full art net ';
Window.location.href = sharesinastring; function shareqq () {var p = {url:location.href,/* Get URL, can be added from the share to the QQ logo, convenient statistics/desc: ', * * share the reason (style should simulate user dialogue), support multiple sharing language random display (use | separate)/title: ',/* share title (optional)/summary: ', * * Share summary (optional) * * PICS: ', * share picture (optional) * * * Flash: ',/* video address (optional)/site: ' Full art net ', * share to
Source (optional) such as: QQ share */style: ' 201 ', width:32, height:32}; Share to QQ var sharesinastring = ' HTtp://connect.qq.com/widget/shareqq/index.html?title= ' + $ ("#title"). Val () + ' &summary= ' + $ ("#url"). Val () + '
&url= ' + $ ("#url"). Val () + ' &site= ' full art net ';
Window.location.href = sharesinastring; function Shareqqweibo () {var p = {url:location.href,/* Get URL, can be added from the share to the QQ logo, convenient statistics/title: ", * * share the title (optional) * * * Pic:", *
Enjoy the picture (optional)/site: ' Full art net '/* sharing source (optional) such as: QQ sharing * *; Share to Tencent Weibo var sharesinastring = ' http://v.t.qq.com/share/share.php?title= ' + $ ("#title"). Val () + ' &url= ' + $ ("#url")
. val () + ' &site= ' full art net ';
Window.location.href = sharesinastring; }

The above is to share Sina Weibo, QQ, QQ space, Tencent micro-blog JS Code, we only need to share the page in the location of the call can be. Of course there are many platforms, like the support of this form of sharing content, the small partners themselves to explore it, here we no longer one by one repeat.

Here are some micro-credit sharing:

At first we said that the micro-mail built-in browser has a sharing function in the upper right corner, this also leads to our own web page can not directly share the micro-trust of the circle of friends, and micro-letter for us to provide a micro-letter customization to share the JS SDK, the small partner has not been able to resist their own passion, Let's start with a simple look at this JS SDK for what? Micro-credit official documents to the time is very detailed, but want to develop the JS SDK we first need a micro-letter public number, and then we click on "interface Permissions" To see the permissions we have, as follows:

For the above basic things do not say, below we focus on how to obtain jsapi_ticket, how to sign. The official documentation prompts the steps to get the Access_token first, then get the jsapi_ticket through the Access_token, and finally sign through Jsapi_ticket. Let's go through the above work step-by-step. Note: The official provided the PHP, Java, Python, nodejs instance program, here I will take C # as an example for everyone to end how to complete the above operation.

First step, get Access_token

The official document says: Access_token is the public number's globally unique interface invocation credential, and the public number calls each interface with a access_token. Developers need to be properly saved. Access_token storage should be reserved for at least 512 character spaces. The validity period of the Access_token is currently 2 hours and needs to be refreshed periodically, and repeated acquisition will cause the last acquired access_token to fail.

  Step two to get Jsapi_ticket

The official document says: Jsapi_ticket is a temporary ticket that the public number uses to invoke the micro-letter JS interface. Normally, the Jsapi_ticket is valid for 7,200 seconds and is obtained by Access_token. Because the number of API calls to get Jsapi_ticket is very limited, frequent refresh Jsapi_ticket can cause API calls to be limited and affect its own business, and developers must cache Jsapi_ticket in their own services globally.

1. Refer to the following documents to obtain Access_token (valid 7,200 seconds, the developer must be in their own service global cache Access_token):. /15/54ce45d8d30b6bf6758f68d2e95bc627.html

2. Use the first step to obtain the Access_token using the HTTP GET method request obtains the Jsapi_ticket (valid 7,200 seconds, the developer must in own service global cache Jsapi_ticket): https:// Api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=access_token&type=jsapi

After you get the Jsapi_ticket, you can generate the signature of the JS-SDK permission verification.

 Step three to generate a signature for JS-SDK permission validation

The signature generation rules are as follows: The fields participating in the signature include NONCESTR (random string), valid jsapi_ticket, timestamp (timestamp), url (the URL of the current Web page, not including # and its back section). Use the format of the URL key value pair (that is, key1=value1&key2=value2 ...) for all pending signature parameters, sorted by the ASCII code of the field name from small to large (dictionary order). ) stitching into string string1. Note here that all parameter names are lowercase characters. For string1 as SHA1 encryption, the field name and field values are all in the original value, and no URL escapes are used.

Attention matters

1. The noncestr and timestamp of the signature must be the same as NONCESTR and timestamp in the wx.config;

2. The URL of the signature must be the full URL of the call to the JS interface page;

3. For security reasons, the developer must implement the logic of the signature on the server side.

The above is the micro-letter JS SDK Signature Logic part, below the specific code implementation:

Using System;
Using System.Net;
Using SYSTEM.WEB.MVC;
Using System.IO;
Using System.Text;
Using System.Web.Script.Serialization;
Using Manyiabywap.models; <summary>///Micro-credit acquisition Jsapi_ticket///</summary> namespace Manyiabywap.controllers {public class Wxmessagec Ontroller:controller {private static string APPID = "APPID provided by micro-letter"; private static string secrect = "Secrect provided by micro-letter"; Publi c static Wxinfo Accesstoken = null;//Global object, updated every 7,200 seconds, micro-letter to obtain daily token number of requests and limitations of the time limit public static DateTime overtime = datetime.no w;//token for expiration validation public actionresult gettoken (string url) {if (Accesstoken!= null) {TimeSpan span = Convert.todatetime ( Overtime).
Subtract (Convert.todatetime (DateTime.Now)); if (span.
Totalhours > 2) {accesstoken = Getwinxintoken (); overtime = DateTime.Now;}} else {Accesstoken = Getwinxintoken (); overtime = DateTime.Now;}//Generate signature timestamp TimeSpan ts = datetime.utcnow-new DateTime (
1970, 1, 1, 0, 0, 0, 0); Accesstoken.timestamp = Convert.toint64 (ts. totalseconds). ToString ();
Get random string accesstoken.noncestr = Createnoncestr (16); String str = "jsapi_ticket=" + accesstoken. ticket+ "&noncestr=" + accesstoken.noncestr + "&timestamp=" +
Accesstoken.timestamp + "&url=" + url; Accesstoken.signature = SHA1 (str).
ToLower ();
Accesstoken.appid = APPID;
Return Json (Accesstoken, jsonrequestbehavior.allowget); //Generate random string private string createnoncestr (int length =) {string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZ0123456789 ";
Random r = new Random (); string result = String.
Empty; Generates a 8-bit long random character, specific lengths can be changed for themselves (int i = 0; i < length; i++) {int m = r.next (0, 62);//Here is the lower bound 0, the random number can be taken, the upper bound should be 62, because the random number is not upper bound, That is, the maximum of 62, matches our string s = str.
Substring (M, 1);
result = = S;
return result;  }//hash algorithm private static string SHA1 (string text) {byte[] cleanbytes = Encoding.Default.GetBytes (text); byte[] Hashedbytes = System.Security.Cryptography.SHA1.Create ().
ComputeHash (cleanbytes); Return bitconverter.tostring (hashedbytes).
Replace ("-", "");}
Get token by getting requestprivate static Wxinfo Getwinxintoken () {//get access_token HttpWebResponse response = Creategethttpresponse ("https://
Api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= "+ AppID +" &secret= "+ SECRECT, 5000); StreamReader reader = new StreamReader (response.
GetResponseStream ());
String Line;
StringBuilder sb = new StringBuilder (); while (line = reader. ReadLine ())!= null) {sb. Append (line.
ToString ());
} JavaScriptSerializer js = new JavaScriptSerializer (); Wxinfo Accesstoken = js. Deserialize<wxinfo> (sb.)
ToString ()); Get jsapi_ticket response = Creategethttpresponse ("Https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_
Token= "+ Accesstoken.access_token +" &type=jsapi ", 5000); reader = new StreamReader (response.
GetResponseStream ());
SB = new StringBuilder (); while (line = reader. ReadLine ())!= null) {sb. Append (line.
ToString ()); } Accesstoken = js. Deserialize<wxinfo> (sb.)
ToString ());
return accesstoken; }///<summary>///http request to create get mode 
</summary>///<param name= "url" > Requested url</param>///<param "name=" > Request Timeout timeout am>///<param name= "useragent" > requested client browser information, which can be null </param>///<param name= "cookies" > Cookie information sent with the HTTP request, if authentication is not required, can be null </param>///<returns></returns> public static HttpWebResponse Creategethttpresponse (string url, int? timeout, string useragent=null, Cookiecollection cookies=null) {if (string).
IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url");}
HttpWebRequest request = webrequest.create (URL) as HttpWebRequest; Request.
method = ' Get '; if (!string. IsNullOrEmpty (useragent)) {request.
useragent = useragent; } if (timeout. HasValue) {request. Timeout = Timeout.
Value; } if (cookies!= null) {request.
Cookiecontainer = new Cookiecontainer (); Request.
Cookiecontainer.add (cookies); Return request.
GetResponse () as HttpWebResponse; }
}
}

A global object for storing token information WXInfo.cs

Namespace Manyiabywap.models
{
///<summary>
///micro-letter Fetch token return parameter class
///</summary>
public class Wxinfo
{public
string APPID {get; set;}
public string Access_token {get; set;} Access_token public
string expires_in {get; set;} Token expiration time, valid public
string ticket {get; set} in 7,200 seconds Jsapi_ticket public
string ErrMsg {get; set;}
public int Errcode {get; set;}
public string Noncestr {get; set;} Generate signed random string
timestamp {get; set;} Generate signature Timestamp public
string Signature {get; set;} Signature return value
}
}

The JS code for initializing the Web end:

Micro-letter JS SDK request status var requeststatus = 0; function Sharewx () {if (RequestStatus!= 1) {requeststatus = 1;//is requesting var Ajaxpara = "Url=" + encodeuricomponent (window.
Location.href.split (' # ') [0]); $.ajax ({url: '/wxmessage/gettoken ', DataType: ' json ', Data:ajaxpara, Success:function (JSON) {if (Undefined!= json &A
mp;& json!== "") {var jsonobjs = eval (JSON);
Wx.config ({debug:false,//Open debug mode, the return value of all invoked APIs will be on the client alert, to view incoming parameters, can be opened on the PC side, the parameter information will be typed through the log, only on the PC side will print.) AppId:jsonObjs.APPID,//must fill, public number unique identification Timestamp:jsonObjs.timestamp,//required, generate signature timestamp nonceStr:jsonObjs.noncestr,//required, generate Signed random string signature:jsonobjs.signature,//must be filled in, signed, see Appendix 1 jsapilist: [' Checkjsapi ', ' onmenusharetimeline ', '
Onmenushareappmessage ', ' onmenushareqq ', ' Onmenushareweibo ', ' onmenushareqzone ']//required, need to use the JS interface list, all JS interface list see appendix 2}); Wx.ready (function () {//alert ("Successful micro-Authentication");//config information is validated after the Ready method is executed, and all interface calls must be made after the Config interface obtains the result, config is a client-side asynchronous operation. So if you need to call the relevant interface when the page loads, then you must place the relevant interface in the ready function to make sure it executes correctly. For an interface that is invoked when a user triggers it, it can be invoked directly without the need to place the ready functionIn Wx.checkjsapi ({jsapilist: [' Checkjsapi ', ' onmenusharetimeline ', ' onmenushareappmessage ', ' onmenushareqq ', ' Onmenushareweibo ', ' onmenushareqzone '],//need to detect the JS interface list, all JS interface list See Appendix 2, Success:function (res) {//return in the form of a key value pair, the available API value TRUE
, cannot be used as false//such as: {"Checkresult": {"Chooseimage": true}, "ErrMsg": "Checkjsapi:ok"}}); Wx.onmenushareweibo ({title: ' Full Art network sharing test ',//share title desc: ' Full art Web Sharing description test ',//Share description Link: ' http://www.manyiaby.com ',//Share link Imgurl : ' Http://www.manyiaby.com/img/logo_2.jpg ',//Share icon Success:function () {//The callback function alert ("sharing success") executed after the user confirms the share;}, Cancel:fun
Ction () {//callback function alert ("Share cancellation") after user cancels sharing;});
});
Wx.error (function (res) {//alert ("micro-authentication failed res:" +res); Config information is validated after the Ready method is executed, all interface calls must be the result of the Config interface, config is a client's asynchronous operation, so if you need to call the relevant interface when the page is loaded, The relevant interfaces must be called in the ready function to ensure proper execution.
For interfaces that are invoked when a user fires, they can be called directly and do not need to be placed in the ready function.
}); 
RequestStatus = 2;//Request Complete}, Complete:function () {window.settimeout (function () {requeststatus = 2;//request Complete}, 300);
}); }

Here about the use of micro-letter sharing JS SDK for everyone to introduce finished, we can combine their own needs for reference. In the beginning has been introduced, the micro-letter to provide a share of the JS SDK is just a micro-letter internal browser cache processing, the real share or need we click on the top right corner of the share button.

These are not too perfect mobile web sharing solutions, and finally to introduce some sosh social sharing components, when I see this component, I know this is what I need, concise interface, the whole good can make our site look elegant and comfortable. Well, nonsense not much to say, into the subject:

The above is a small set to introduce the mobile phone web app how to realize the sharing of multi-platform functions, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.