WeChat authorization and sharing with friends

Author: Wang Jiaojiao

Date: 2016.9.25

Thinking about it now, wechat is really a thing that people love and hate. When I first came into contact with it, I had no clue. However, with the cooperation of the background, now I can finally obtain user information and share the circle of friends through WeChat. The two pieces are more thorough, and when they are empty, I quickly write down these things, I am afraid that one day I will forget them again, hahaha.

1. Public account.

If you want to do something like WeChat, you must first have a public account (you can apply for registration on the WeChat public platform), mainly fill in the following JS interface security domain name in "Official Account Settings" -> "Function Settings" (Note: log in Afterwards, you can view the corresponding interface permissions in the "Developer Center". For example, only the enterprise account has the function of sharing the circle of friends, and the subscription account does not have this permission).

 

2. Make reasonable use of "developer documentation".

Since there are these functions, the documentation provided by WeChat should not be underestimated. The most important thing for our developers is naturally the "developer documentation", and the most important developer documentation belongs to "WeChat Web Development", "WeChat Web Development" The core of "WeChat web page authorization", "WeChat JS-SDK documentation" and "WeChat web developer tools".

 

(1) WeChat webpage authorization

In fact, this piece only needs to be understood, because this part is something that belongs to background research. We only need to know that there are two types of web page authorization: manual authorization (scope is snsapi_userinfo) and silent authorization (scope is snsapi_base). Whether manual authorization or silent authorization is required, it is enough to discuss with the background.

 

(2) WeChat JS-SDK documentation

This piece is naturally what we need to see on the front end. There is a lot to say, because WeChat is really detailed, and the interfaces used are listed one by one, but we only need to use whichever one is copied. . Then let's start to talk about the steps of using JSSDK in detail.

 

Step 1: Import JS files.

Introduce the following JS file to the page that needs to call the JS interface:

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

 

Step 2: Obtain WeChat authorization.

There is a very big premise that you must know, the link opened in WeChat is not our ordinary link, but a link with many prefixes and suffixes, for example, your link is: http://jojojojo.duapp.com/index .html?id=3

Note: id=3 is the parameter I want to use (because my personal project needs it, so I added an id), everyone depends on the specific situation, but it must be noted that only one parameter can be added later, no matter how many you write, at the end Leave only the first one. If there are more than one, you can combine the two into one in the form of json, for example: param={id:3,scope:snsapi_userinfo}.

 

If you want your link to be authorized by WeChat, it must be written as follows:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxef51b342984c9a03&redirect_uri=http%3a%2f%2fjojojojo.duapp.com%2findex.html%3fid%3d3&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect

Note: appid is the appid of your WeChat official account, and url is the encoded url.

Encoding URL: http://tool.chinaz.com/tools/urlencode.aspx .

 

After opening this link in the developer tools, you will get another link:

http://jojojojo.duapp.com/index.html?id=3&code=021v0NLa1mmCcr0g7IJa1bURLa1v0NLK&state=1

This link is the link you really want to operate. For example, I want to call the interface written in the background to obtain WeChat authorization through ajax (for example: "../share"). When calling the ajax, I need to pass 2 fields to the background: code and url. Both of these fields are required, because the backend needs to exchange the code for the access_token authorized by the web page. url is the full url of the page, where the url is:

http://jojojojo.duapp.com/index.html?id=3&code=021v0NLa1mmCcr0g7IJa1bURLa1v0NLK&state=1

 

This link should be dynamically obtained with location.href.split('#')[0] , and it is best to use the encodeURIComponent() function to encode it (I didn't encode it here), because once the page is shared, the WeChat client will show you Add other parameters at the end of the link. If the current link is not dynamically obtained, it will cause the page signature after sharing to fail. If you need other parameters, you can add them.

 

Taking my own link as an example, the code is as follows:

(location.href in the code below is the url above)

var code=location.href.split("?")[1].split("&")[1].split("=")[1],   //code
    url=location.href.split('#')[0],                               //url
    id=location.href.split("?")[1].split("&")[0].split("=")[1],   //id,我自己的参数,你们据自己情况而定
    appId,nonceStr,timestamp,signature;

$.ajax({
	type:"post",
	url:"../share",
	async:true,
	dataType:"json",
	data:{
		code:code, 
		url:url   
	},
	success:function(data){
		console.log(data);
        var sp = data.signPackage,
        appId = sp.appId,
        nonceStr = sp.nonceStr,
        timestamp = sp.timestamp,
        signature = sp.signature;
	}),
	error:function(){
		console.log("fail");
	})
})

After calling, you can get the information you want (such as appId, etc.), that is, the log data, as shown in the following figure:

Note: The four fields of appId, nonceStr, signature and timestamp are required for WeChat sharing. Not to mention the information in userInfo, you can do a lot of small games with the avatar and username.

 

Step 3: Share to Moments or Share to Friends

The four fields of appId, nonceStr, signature and timestamp mentioned above can be used immediately here. I encapsulated this piece into a function myself, so I can call it directly when I want to use it:

function weixin(tit,des){
	var redirect_uri="http://jojojojo.duapp.com/index.html?"+id;
	wx.config({
		debug: true, 
        // 开启调试模式,调用的所有api的返回值会在客户端alert出来,在pc端时会打印出来,不需要的话可以将true改成false。
		appId: appId,  // 必填,公众号的唯一标识
		timestamp: timestamp,  // 必填,生成签名的时间戳
		nonceStr: nonceStr,  // 必填,生成签名的随机串
		signature: signature,  // 必填,签名
		jsApiList: [
            // 必填,需要使用的JS接口列表
			"onMenuShareTimeline",
			"onMenuShareAppMessage"
		]
	});
    //分享到朋友圈
	wx.ready(function () {
	    wx.onMenuShareTimeline({
		    title: tit,   // 分享时的标题
		    link: "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect",     // 分享时的链接
		    imgUrl: 'http://jojojojo.duapp.com/homepage/images/qr.png',    // 分享时的图标
		    success: function () {
			    console.log("分享成功");
		    },
		    cancel: function () {
			    console.log("取消分享");
		    }
	    });
        //分享给朋友
	    wx.onMenuShareAppMessage({
		    title: tit,
		    desc: des, 
		    link: "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect",
		    imgUrl: 'http://jojojojo.duapp.com/homepage/images/qr.png',
		    type: '',
		    dataUrl: '', 
		    success: function () {
			    console.log("分享成功");
		    },
		    cancel: function () {
			    console.log("取消分享");
		    }
	    });
    })
}

The call is as follows:

var tit="Share",des='La La La';

weixin(tit,des);

 

(3) WeChat web developer tools

Come on, I have to recommend this tool. It simulates the performance of the WeChat client to make it easier for developers to develop and debug on the computer. Download the experience now

Specific operations: log in to the management background with the official account, enable the developer center, and send a binding invitation to the developer's WeChat account on the developer tools - web developer tools page.

If not, you can go to the WeChat public platform to find the steps, even~

Finally, if there is any problem, please feel free to spray, but welcome to point out and communicate with you (*^__^*)!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326078652&siteId=291194637