Table of Contents
1. Preparation, set the js interface security domain name
2. Front-end configuration
3. Generate signature
1.access_token
2. Get jsapi_ticket
3.Signature
4. Summary
Home WeChat Applet WeChat Development Development of WeChat sharing function

Development of WeChat sharing function

Mar 16, 2018 pm 02:28 PM
share Function develop

This time I will bring you the development of the WeChat sharing function. What are the precautions for the development of the WeChat sharing function. The following is a practical case, let's take a look.

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.

In this file is 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: '@Model.appId', // 必填,公众号的唯一标识
        timestamp: '@Model.timestamp', // 必填,生成签名的时间戳
        nonceStr: '@Model.nonceStr', // 必填,生成签名的随机串
        signature: '@Model.signature',// 必填,签名,见附录1
        jsApiList: ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2    });
    wx.ready(function () {
        document.querySelector('#checkJsApi').onclick = function () {
            wx.checkJsApi({
                jsApiList: [            'getNetworkType',            'previewImage'
                ],
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };
    //朋友圈        wx.onMenuShareTimeline({
            title: '暖木科技', // 分享标题
            link: 'http://www.warmwood.com/home/lampindex', // 分享链接
            imgUrl: 'http://www.warmwood.com/images/s1.jpg',
            success: function (res) {
                alert('已分享');
            },
            cancel: function (res) {
                alert('已取消');
            },
            fail: function (res) {
                alert(JSON.stringify(res));
            }
        });        //朋友        wx.onMenuShareAppMessage({
            title: '暖木科技', // 分享标题
            desc: '宝宝的睡眠很重要,你的睡眠也很重要', // 分享描述
            link: 'http://www.warmwood.com/home/lampindex', // 分享链接
            imgUrl: 'http://www.warmwood.com/images/s1.jpg', // 分享图标
            type: '', // 分享类型,music、video或link,不填默认为link
            dataUrl: '', // 如果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 consistent across 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 you get to this point, and then you see a scene in the document that disappoints you :

Is there any 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 https://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).

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Usage of webpack automatic refresh and parsing

Usage of H5 cache Manifest

The above is the detailed content of Development of WeChat sharing function. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

See all articles