Home > WeChat Applet > WeChat Development > Detailed explanation of the process of implementing WeChat sharing function using Asp.net MVC

Detailed explanation of the process of implementing WeChat sharing function using Asp.net MVC

Y2J
Release: 2017-04-27 14:07:49
Original
2788 people have browsed it

Web pages embedded in WeChat will have a default sharing function in the upper right corner. As shown in the figure below, the first one is the customized effect, and the second one is the default effect. Will implementing customized sharing links make people more eager to click? The development process is explained below.

1. Preparation, set the js interface security domain name

This requires using WeChat’s jssdk, and first needs to be set in the WeChat official account background: Official account settings -->Function Settings-->JS interface security domain name. After opening this page you will see the following prompt. You need to download this file first and upload it to the root directory of the specified domain name.

#This file contains a string, which from the name is used for verification. You must upload this file first before you can save it successfully. This way you can use jssdk.

2. Front-end configuration

The first thing to note is that the sharing function is a configuration function, and it has no effect if it is bound to the click event of a button. In other words, only clicking Share in the upper right corner will have an effect (I don’t know how to share some text content). The official js has four steps. The first is to introduce jssdk:

<script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
Copy after login

According to the official configuration parameters, we can define a WXShareModel object:

   public class WXShareModel
    {        public string appId { get; set; }        public string nonceStr { get; set; }        public long timestamp { get; set; }        public string signature { get; set; }        public string ticket { get; set; }        public string url { get; set; }        public void MakeSign()
        {             var string1Builder = new StringBuilder();
             string1Builder.Append("jsapi_ticket=").Append(ticket).Append("&")
                          .Append("noncestr=").Append(nonceStr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);            var string1 = string1Builder.ToString();
            signature = Util.Sha1(string1, Encoding.Default);
        }
    }
Copy after login

and then configure it:

wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: &#39;@Model.appId&#39;, // 必填,公众号的唯一标识
        timestamp: &#39;@Model.timestamp&#39;, // 必填,生成签名的时间戳
        nonceStr: &#39;@Model.nonceStr&#39;, // 必填,生成签名的随机串
        signature: &#39;@Model.signature&#39;,// 必填,签名,见附录1
        jsApiList: ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2    });

    wx.ready(function () {
        document.querySelector(&#39;#checkJsApi&#39;).onclick = function () {
            wx.checkJsApi({
                jsApiList: [            &#39;getNetworkType&#39;,            &#39;previewImage&#39;
                ],
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };
    //朋友圈        wx.onMenuShareTimeline({
            title: &#39;暖木科技&#39;, // 分享标题
            link: &#39;http://www.warmwood.com/home/lampindex&#39;, // 分享链接
            imgUrl: &#39;http://www.warmwood.com/images/s1.jpg&#39;,
            success: function (res) {
                alert(&#39;已分享&#39;);
            },
            cancel: function (res) {
                alert(&#39;已取消&#39;);
            },
            fail: function (res) {
                alert(JSON.stringify(res));
            }
        });        //朋友        wx.onMenuShareAppMessage({
            title: &#39;暖木科技&#39;, // 分享标题
            desc: &#39;宝宝的睡眠很重要,你的睡眠也很重要&#39;, // 分享描述
            link: &#39;http://www.warmwood.com/home/lampindex&#39;, // 分享链接
            imgUrl: &#39;http://www.warmwood.com/images/s1.jpg&#39;, // 分享图标
            type: &#39;&#39;, // 分享类型,music、video或link,不填默认为link
            dataUrl: &#39;&#39;, // 如果type是music或video,则要提供数据链接,默认为空
            success: function () {                // 用户确认分享后执行的回调函数
                alert("分享");
            },
            cancel: function () {                // 用户取消分享后执行的回调函数
                alert("取消分享");
            }
        });
    });
Copy after login

Then the rest is the backend. The key to the backend is getting the access_token and jsapi_ticket and generating the correct signature. In addition, if you want to count the number of shares, it is best to count them in the success method.

3. Generate signature

1.access_token

The method of obtaining access_token is the same across all platforms.

public const string AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
Copy after login
 public TokenResult GetAccessToken()
        {            var url = string.Format(WxDeviceConfig.AccessTokenUrl, WxDeviceConfig.AppId, WxDeviceConfig.APPSECRET);            var res = SendHelp.Send<TokenResult>(null, url, null, CommonJsonSendType.GET);            return res;
        }
Copy after login

The timeout of access_token is 7200 seconds, so it can be cached first. You can download it at the end of the SendHelp article

2. Get jsapi_ticket

The purpose of access_token is to get jsapi_ticket. Use get method to obtain, url: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi, the returned JSON object is as follows.

{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}
Copy after login

So you can define a model:

public class jsapiTicketModel
    {        public string errcode { get; set; }        public string errmsg { get; set; }        public string ticket { get; set; }        public string expires_in { get; set; }
    }
Copy after login

Then complete the method of obtaining the ticket:

 public jsapiTicketModel GetJsApiTicket(string accessToken)
        {            var url = string.Format(WxPayConfig.Jsapi_ticketUrl, accessToken);            return SendHelp.Send<jsapiTicketModel>(accessToken, url, "", CommonJsonSendType.GET);
        }
Copy after login

The ticket expiration time is also 7200 seconds, and frequent requests cannot be made, so it is also needed Then cache it on the server side.

 private void setCacheTicket(string cache)
        {
            _cacheManager.Set(tokenKey, cache, 7200);
        }
Copy after login

MemoryCacheManager:

View Code

3. Signature

Finally this step is reached, and then you I saw a scene in the document that will disappoint you:

Is there a C# demo? The payment side provides it. Why is jssdk not provided? Well, let’s not complain now. . The official also explained the rules for signing. At the beginning, I used the signature in github.com/night-king/weixinSDK:

 public static string Sha1(string orgStr, string encode = "UTF-8")
        {            var sha1 = new SHA1Managed();            var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);            byte[] resultHash = sha1.ComputeHash(sha1bytes);            string sha1String = BitConverter.ToString(resultHash).ToLower();
            sha1String = sha1String.Replace("-", "");            return sha1String;
        }//错误示例
Copy after login

The result obtained was inconsistent with the official verification, and it kept prompting a signature error.

The correct way to write it is:

public static string Sha1(string orgStr, Encoding encode)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();            byte[] bytes_in = encode.GetBytes(orgStr);            byte[] bytes_out = sha1.ComputeHash(bytes_in);
            sha1.Dispose();            string result = BitConverter.ToString(bytes_out);
            result = result.Replace("-", "");            return result;  
        }
Copy after login

Once it matches the official verification result, it will be ok (ignoring the case). Another thing to pay attention to is the url in the signature. If the page has parameters, the url in the model also needs to have parameters, and the ones after the # sign are not required. Otherwise, a signature error will be reported.

 public ActionResult H5Share()
        {            var model = new WXShareModel();
            model.appId = WxPayConfig.APPID;
            model.nonceStr = WxPayApi.GenerateNonceStr();
            model.timestamp = Util.CreateTimestamp();
            model.ticket = GetTicket();
            model.url = "http://www.warmwood.com/AuthWeiXin/share";// domain + Request.Url.PathAndQuery;            model.MakeSign();
            Logger.Debug("获取到ticket:" + model.ticket);
            Logger.Debug("获取到签名:" + model.signature);            return View(model);
        }
Copy after login

4. Summary

If debug in wx.config is true, various operation results will be alerted. After the parameters are correct, the interface will prompt:

At this point, the sharing function is ok. This also opens the door to calling other jssdk. In addition, the SendHelp object in this article uses the dll of Senparc (based on .net4.5).

The above is the detailed content of Detailed explanation of the process of implementing WeChat sharing function using Asp.net MVC. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template