By the way, apps usually have entrances to share on social platforms, and there is also a good framework for sharing web pages. However, with the continuous development of HTML5, mobile web pages are becoming more and more popular in our lives. So how to complete sharing on our mobile phones? Speaking of which, major sharing platforms have SDKs for Android and Ios. As developers, we only need to integrate the SDK into our project. Through the external interface provided, we can easily complete the sharing function; as for web pages, there are many excellent sharing frameworks on the Internet, such as: bShare sharing and JiaThis sharing; we can easily integrate into our project; but we need to put some effort into implementing sharing on mobile web pages. I think that at this time, we can share by calling the client installed by the user. What needs to be mentioned here is WeChat sharing. When we share on the web page, a sharing QR code usually pops up. We use WeChat App to scan and share. We cannot operate on the mobile phone. We need to open the App directly to share when the user selects WeChat sharing. Here we will complain about WeChat sharing JS SDK. When I first came into contact with this thing, I thought that as long as I completed the operation, I could realize custom sharing. With all kinds of pitfalls, I finally found that the WeChat JS SDK only temporarily caches our custom content. When we need to share, we still need to complete the operation through the button in the upper right corner of WeChat. OK, I won’t talk nonsense anymore. Let’s enter today’s topic. Next, I will complete the sharing of Sina, QQ, QQ Space, and Tencent Weibo through hyperlinks, and then provide you with the signature logic of the WeChat JS SDK sharing component based on the C# platform, and finally lead you to complete the sharing of the mobile web.
Enter the first point: Complete sharing through the hyperlink
For commonly used social platforms, we can basically share content through hyperlinks, except for WeChat, which does not support this sharing method. This sharing method can facilitate us to customize sharing and is very convenient 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 the total number of shares is displayed, display: '1', not display: '0' */desc:'',/*Default sharing reason (optional)*/summary:'',/*Share summary (optional)*/title:'',/*Share title (optional)*/site:'Manyi.com',/*Share source such as: Tencent (optional)*/pics:'', /*Path to share pictures (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="Manyi.com"';window.location.href = sharesinastring;}function shareQQ() {var p = {url: location.href, /*Get URL, you can add from sharing to QQ logo for convenient statistics*/desc: '', /*Share reason (the style should simulate user conversation), supports random display of multiple sharing languages (using|separation)*/title: '', /*Share title (optional)*/summary: '', /*Share summary (optional)*/pics: '', /*Share picture (optional)*/flash: '', /*Video address (optional)*/site: 'Manyi.com', /*Share source (optional) For example: QQ sharing*/style: '201',width: 32,height: 32};//Share to QQvar sharesinastring = 'http://connect.qq.com/widget/shareqq/index.html?title=' + $("#title").val() + '&summary=' + $("#url").val() + '&url=' + $("#url").val() + '&site="Manyi.com"';window.location.href = sharesinastring;}function shareQQweibo() {var p = {url: location.href, /*Get the URL, and add the shared QQ logo from the QQ to facilitate statistics*/title: '', /*Share title (optional)*/pic: '', /*Share picture (optional)*/site: 'Manyi.com' /*Share source (optional) For example: QQ sharing*/};//Share to Tencent Weibo var sharesinastring = 'http://vtqq.com/share/share.php?title=' + $("#title").val() + '&url=' + $("#url").val() + '&site="Manyi.com"';window.location.href = sharesinastring;}The above is the JS codes for sharing Sina Weibo, QQ, QQ Space, and Tencent Weibo. We only need to call them at the location where the page needs to be shared. Of course, there are many platforms that also support this form of sharing content. Please explore it yourself. We will not elaborate on it one by one here.
Here are some WeChat shares:
At the beginning, we said that the built-in browser of WeChat has a sharing function in the upper right corner, which also makes it impossible for us to share directly on our web pages to WeChat’s circle of friends. WeChat provides us with a JS SDK for custom sharing of WeChat. Are you unable to hold back your passion? Let’s take a brief look at what this JS SDK is? The documents provided by WeChat are quite detailed at that time, but if you want to develop the JS SDK, we first need a WeChat official account, and then we click "Interface Permissions" to view the permissions we have, as follows:
I won’t talk about the basic things above. Let’s focus on how to obtain jsapi_ticket and how to sign. The steps prompted by the official documentation are to first obtain access_token, then obtain jsapi_ticket through access_token, and finally sign through jsapi_ticket. Let’s complete the above work step by step. Note: The official provides example programs for php, java, python, and nodejs. Here I will use C# as an example to end the above operations for you.
Step 1: Get access_token
The official document says this: access_token is the globally unique interface calling credential of the official account. Access_token is required when calling each interface by the official account. Developers need to save it properly. The storage of access_token must retain at least 512 character space. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the access_token you obtained last time to be invalid.
Step 2 to get jsapi_ticket
The official document says this: jsapi_ticket is a temporary ticket used by the official account to call the WeChat JS interface. Under normal circumstances, the validity period of jsapi_ticket is 7200 seconds, which is obtained through access_token. Since the number of API calls to obtain jsapi_ticket is very limited, frequent refresh of jsapi_ticket will cause API calls to be limited and affect their own business. Developers must cache jsapi_ticket globally in their services.
1. Refer to the following document to obtain access_token (valid for 7200 seconds, developers must cache access_token globally in their service): ../15/54ce45d8d30b6bf6758f68d2e95bc627.html
2. Use the access_token obtained in the first step to request the jsapi_ticket (valid for 7200 seconds, the developer must cache jsapi_ticket globally in his service): https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
After obtaining jsapi_ticket, you can generate a signature for JS-SDK permission verification.
The third step is to generate the signature for JS-SDK permission verification
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 subsequent parts). After sorting all parameters to be signed from small to large (dictionary order) according to the ASCII code of the field name, the format of the URL key-value pair (that is, key1=value1&key2=value2…) is used to splice into a string string1. It should be noted here that all parameter names are lowercase characters. String1 is encrypted, and the field name and field value are both original values and no URL escape is performed.
Things to note
1. The noncestr and timestamp used for signature must be the same as the nonceStr and timestamp in wx.config;
2. The url used for signature must be the complete URL of the page calling the JS interface;
3. For security reasons, developers must implement signature logic on the server side.
The above is the signature logic part of the WeChat JS SDK, and the following is 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>//// Get jsapi_ticket//// </summary>namespace ManYiAbyWAP.Controllers{public class WXMessageController: Controller{private static string APPID = "appid provided by WeChat";private static string SECRECT = "secret provided by WeChat";public static WXInfo accessToken = null;//Global object, updated every 7200 seconds, WeChat has requests and time limits for daily token acquisition public static DateTime overTime = DateTime.Now;//Updated verification of token 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 the signature timestamp TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);accessToken.timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();//Get the random string accessToken.noncestr = createNonceStr(16);string str = "jsapi_ticket="+ accessToken .ticket+ "&noncestr="+ accessToken.noncestr + "×tamp="+ accessToken.timestamp + "&url="+ url;accessToken.signature = SHA1(str).ToLower();accessToken.APPID = APPID;return Json(accessToken, JsonRequestBehavior.AllowGet);}// Generate a random string private string createNonceStr(int length = 16){string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";Random r = new Random();string result = string.Empty;// Generate an 8-bit long random character. The specific length can be changed by itself for (int i = 0; i < length; i++){int m = r.Next(0, 62);// Here the lower bound is 0, the random number can be obtained, and the upper bound should be 62, because the random number cannot be retrieved, that is, the maximum is 62, which is in line with our question 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 Tokenprivate static WXInfo GETWinXinToken() {// Get access_tokenHttpWebResponse 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_ticketresponse = 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> /// Create a GET HTTP request/// </summary> /// <param name="url">Requested URL</param> /// <param name="timeout">Requested timeout</param> /// <param name="userAgent">The requested client browser information can be empty</param> /// <param name="cookies">Cookie information sent with HTTP request, it can be empty</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;}}}WXInfo.cs global object for storing Token information
namespace ManYiAbyWAP.Models{/// <summary>/// WeChat to get Token return parameter class/// </summary>public class WXInfo{public string APPID { get; set; }public string access_token { get; set; }//access_tokenpublic string expires_in { get; set; }//Token expiration time, valid within 7200 seconds public string ticket { get; set; }//jsapi_ticketpublic string errmsg { get; set; }public int errcode { get; set; }public string noncestr { get; set; }//Generate a random string of signature public string timestamp { get; set; }//Generate a timestamp of signature public string signature { get; set; }//Signature return value}}JS code for initialization on the web page:
//WeChat JS SDK request status var requestStatus = 0;function shareWX() {if (requestStatus != 1) {requestStatus = 1;//Requesting var ajaxPara = "url=" + encodeURIComponent(window.location.href.split('#')[0]);$.ajax({url: '/WXMessage/GetToken',dataType: 'json',data: ajaxPara,success: function (json) {if (undefined != json && json !== "") {var jsonObjs = eval(json);wx.config({debug: false, // Turn on debug mode, the return values of all APIs called will be alerted on the client. To view the passed parameters, you can open them on the PC side. The parameter information will be printed through the log and will only be printed on the PC side. appId: jsonObjs.APPID, // Required, the unique identifier of the official account timestamp: jsonObjs.timestamp, // Required, generate the signature timestamp nonceStr: jsonObjs.noncestr, // Required, generate the signature random string signature signature: jsonObjs.signature, // Required, see Appendix 1jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // Required, the list of JS interfaces that need to be used, see Appendix 2});wx.ready(function () {//alert("WeChat verification is successful");// After config information verification, the ready method will be executed. All interface calls must be obtained after the config interface obtains the result. config is an asynchronous operation of a client. Therefore, if you need to call the relevant interface when the page is loaded, the relevant interface must be called in the ready function to ensure correct execution. For interfaces that are called only when the user triggers, they can be called directly, and do not need to be placed in the ready function. wx.checkJsApi({jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'], // List of JS interfaces that need to be detected. See Appendix 2 for all JS interface lists, success: function (res) {// Return as key-value pairs, the available api value is true, not available as false// For example: {"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}}});wx.onMenuShareWeibo({title: 'Manyi.com share test', // share title desc: 'Manyi.com share 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("Shared successfully");},cancel: function () {// The callback function alert("Shared Cancel");}});});wx.error(function (res) {//alert("WeChat verification failed res:"+res);// After config information verification, the ready method will be executed. All interface calls must be obtained after the config interface obtains the result. config is an asynchronous operation of a client, so if you need to call the relevant interface when the page is loaded, the relevant interface must be placed in the ready function to ensure correct execution. For interfaces that are called only when the user triggers, they can be called directly, and do not need to be placed in the ready function. });requestStatus = 2;//Request completion}},complete: function () {window.setTimeout(function () {requestStatus = 2;//Request completed}, 300);}});}Here, I will introduce the use of the WeChat sharing JS SDK. You can refer to it based on your own needs. I have introduced it to you at the beginning that the sharing JS SDK provided by WeChat is just a cache processing for the internal browser of WeChat. The real sharing still requires us to click the sharing button in the upper right corner.
The above are not perfect mobile web sharing solutions. Finally, I will introduce some Sosh social sharing components to you. When I see this component, I know that this is what I need, a simple interface, and it can make our website look elegant and comfortable. OK, without further ado, enter the topic:
The above is the editor’s introduction to how to share multi-platform functions on mobile Web APP. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!