The WeChat applet obtains the user's official account OpenID through the authorization of the web-view page

Implement webpage authorization in the applet to obtain WeChat public account OpenID

1. Preparations

Step 1: Obtain the AppID and appsecret of the WeChat official account test account
through this address https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index (the test official account can be tested
Use, personal official account is not allowed. WeChat authentication service account can be used, WeChat authentication subscription account cannot be used).
Link to view interface privileges:
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Explanation_of_interface_privileges.htmlTest
public account Follow the prompts on WeChat in the interface for generating a test public account. Non-testing not only needs attention, but also needs to be set up by the developer in the WeChat public platform before the web-view can be used.

At the same time, you need to modify the webpage authorization interface
insert image description here

Because it is a test, just modify the local IPv4 address and add the port number of your backend. Note that 127.0.0.1 is not allowed.

insert image description here
The above is mine. The domain name is required in the formal environment, but not in the test environment.

Step 2:
You also need to get a test account for the WeChat Mini Program. Get the AppID and appsecrt in it. Note: The AppID of the Mini Program and the WeChat Official Account are not the same.

Step 3:
I use the WeiXin-JAVA development kit for the backend. Specifically, you can visit
https://github.com/Wechat-Group/WxJava through the link
, or you can implement it yourself according to your own ability.

2. Description of application scenarios

I don't know about other application scenarios. According to my actual situation (the current method can be used without using unionID)

3. Implementation steps

Step 1: Download WeChat development tools (otherwise how to test it)

Step 2: Use the AppId of the WeChat applet to create a WeChat applet project, and then you can use or not use the official simple demo. It's a very simple program, and it can be written in one go, so you don't need an official one.

Step 3: Write a button and click the button to obtain the WeChat public account OpenID

// index.wxml
<button bindtap="getGzhOpenId">获取公众号OpenId</button>

One button one click event.

The code in the click event is as follows:

// index.js
getGzhOpenId(){
    
    
    wx.navigateTo({
    
    
      url: '/pages/test/test',
    })
  }

Anyone who has written a small program knows that this is a page jump. But this jump is not a normal page, but an interface with web-view.

// test.wxml
<web-view src="{
     
     {src}}">
</web-view>

There are only two lines of code on the entire page, which is equivalent to a transfer station and does not need to be seen by users. src is an article that can open the associated official account. For other web pages, you need to log in to the applet management background to configure the business domain name.

// test.js
onLoad(){
    
    
	let redirect_url = 'http://测试公众号网页授权的地址/后台接口地址/appid';   
   this.data.src = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=测试号AppID&redirect_uri=' + escape(redirect_url) + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
   this.setData({
    
    
    src: this.data.src
   })
}

The above is the point. Reorganize:
load the applet into index.wxml -> click the button to jump to test.wxml -> come to test.wxml and execute the rendering method in js, which is onLoad(){} During rendering, we can start to get the public No. OpenID is up.

redirect_url: callback address

this.data.src: That is, assign an address to src in web-view, and web-view will open this address. After opening, you will get the code and then call back the redirect_url address and carry the WeChat official account code (the code is not the code of the applet wx.login()).

The parameters in the address can refer to the official document:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

Special attention needs to be paid to the scope parameter. He has two values ​​one is snsapi_base. The other is snsapi_userinfo. The former is to get openId. The latter is to obtain OpenId and user information, and it can be obtained without following the official account . The interface in WeiXin-Java-Demo is to obtain userInfo, so the scope needs to be changed, otherwise an error will be reported. If you only need to get OpenId. See the following example:

@RequestMapping({
    
    "/getOpenId"})
    public String getOpenId(@PathVariable String appid, @RequestParam String code, ModelMap map) {
    
    
        if (!this.wxService.switchover(appid)) {
    
    
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
        } else {
    
    
            try {
    
    
                WxOAuth2AccessToken accessToken = this.wxService.getOAuth2Service().getAccessToken(code);
                map.addAttribute("openId",accessToken.getOpenId());
            } catch (WxErrorException var6) {
    
    
                var6.printStackTrace();
            }
            return "xxx";   
        }
    }

In fact, the weixin toolkit encapsulates its methods, which are not used in the Demo, just copy the interface, just paste and modify it.

At this point, I got the OpenId, which can be debugged, but it is strange, why my applet is still on the white screen. Hahaha because the web-view interface I have to understand is the ifrname embedded page in html.

The next step is also the key point.
Looking at the above picture of the background interface, the return is xxx. xxx represents a page, which is the xxx.html interface. We need to return the view to the applet through springmvc, and the web-view of the applet opens the interface you wrote in the background.
So what is written in xxx.html? read on

xxx.html is opened in the applet, and then you want to display something? No! No! No! No need, but if you just need it, I won't say anything.

// xxx.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
    <TITLE> New Document </TITLE>
    <META NAME="Generator" CONTENT="EditPlus">
    <META NAME="Author" CONTENT="">
    <META NAME="Keywords" CONTENT="">
    <META NAME="Description" CONTENT="">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
</HEAD>
<BODY>
</BODY>
<SCRIPT LANGUAGE="JavaScript">
    function back()
    {
      
      
        wx.miniProgram.redirectTo({
      
      url: "/pages/index/index?mpOpenid=${openId}"})
        //wx.miniProgram.postMessage({data:"${openId}"})
    }

    back();
</SCRIPT>
</HTML>

After returning xxx.html to the applet, the view is loaded, and the view executes the back() method. Use redirectTo in the applet to return to the interface you want to go to. This interface must exist in the applet! Then be sure to introduce jweixin. Otherwise, the method of the applet cannot be used in the web page. To return, you can bring the openId of the WeChat official account on the url to return to the index interface of the applet.

onLoad(e){
    
    
console.log(e);
}

You can get the OpenID, and after getting it through the above methods, you can correspond to the applet OpenID obtained by wx.login.

The above method can also be extended to many situations. For example, when the applet is loaded for the first time, read the 10s attention notice first. You can also carry the small program OpenId when opening the web-view page, and get the official account OpenID at the back end in one go and then store it persistently. There is no need to go back.

epilogue

It is the first time I write CSDN, and it is also the first time I use markdown to write. I write less and have no vision of beautification. The point is to solve a problem at work. Use this as a record, in case the next time the interviewer asks me about the problems I encountered in the project (is it still called the problem I encountered?) . At the same time, this article also hopes that everyone can use it when encountering difficulties. If you don’t understand, you can communicate in the comment area or private message. Because it was the first time, I checked Baidu by myself and then slowly figured it out. Also read other similar articles. I found inspiration from their articles and I also attach it below, so you can read it at the same time, so that you can understand it more quickly.

https://blog.csdn.net/qq_41929578/article/details/121748935
https://blog.csdn.net/daengwei/article/details/124535274
https://blog.csdn.net/qq_21492635/article/details/119491131

Guess you like

Origin blog.csdn.net/weixin_43819028/article/details/129534126