[Micro] springboot letter applet Get the user's background openid

openid can identify a user, session_key become, so to get it openid.

openid micro-channel can not be directly acquired in the applet, the background need to send a request to the interface of the micro-channel, micro-channel and returns a string json format to the background after the background processing, and then returns to the micro-channel applet.

Published applet requires https domain name, test time can use http.

App.js applet, modify the content () in the login:

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          wx.request({
            url: 'http://localhost:84/user/login',
            method: 'POST',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
              console.log("openid:"+res.data.openid);
              if(! res.data.openid = "" || res.data.openid =! null ) {
                 // successful login 
                wx.setStorageSync ( "openid", res.data.openid); // user id saved to the cache 
                wx.setStorageSync ( "session_key", res.data.session_key); // save the cache session_key 
              } the else {
                 // login failure 
                // the TODO jump to the error page, asks the user to retry 


                return  to false ; 
              } 
            } 
          }) 
        } the else { 
          the console.log ( 'Get user login state fails!' + res.errMsg) 
        } 
      } 
    })

Here request http: // localhost: 84 / user / login

Background processing class:

package com.ft.feathertrade.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.feathertrade.entity.OpenIdJson;
import com.ft.feathertrade.utils.HttpUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class LoginHandler {

    private String appID = "";
    private String appSecret = "";

    @PostMapping("/ User / Login" )
     public String the userLogin (@RequestParam ( "code") String code) throws IOException { 
        String Result = "" ;
         the try { // request WeChat server, in exchange for a code openid. HttpUtil are tools, will be given later realized, the Configure class is the configuration applet, the code will be given later 
            Result = HttpUtil.doGet (
                     "https://api.weixin.qq.com/sns/jscode2session?appid=" 
                            + the this .appID + "Secret = &" 
                            + the this .appSecret + "& js_code =" 
                            + code
                             + "null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);
        System.out.println(result.toString());
        System.out.println(openIdJson.getOpenid());
        return result;
    }

}

HttpUtil tools:

Package com.ft.feathertrade.utils; 


Import java.io.BufferedReader;
 Import the java.io.InputStreamReader;
 Import java.net.HttpURLConnection The;
 Import the java.net.URL;
 Import java.net.URLEncoder;
 Import the java.util.HashMap ;
 Import java.util.Map.Entry;
 Import java.util.Set;
 Import org.apache.commons.httpclient.HttpStatus; // such dependency or to add maven jar package 

/ ** this dependency added to pom.xml in 
 <dependency> 
 <the groupId> Commons-HttpClient </ the groupId> 
 <the artifactId> Commons-HttpClient </ the artifactId> 
 <Version> 3.1 </ Version> 
 </dependency>
 **/

public class HttpUtil {

    public static String doGet(String urlPath, HashMap<String, Object> params)
            throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");

            Set<Entry<String, Object>> set = params.entrySet();
            for (Entry<String, Object> entry : set) { // 遍历map里面的参数
                String key = entry.getKey();
                String value = "";
                if (null != entry.getValue()) {
                    value = entry.getValue().toString();
                    // 转码
                    value = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(key).append("=").append(value).append("&");
            }

            sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
        }
        // System.out.println(sb.toString());
        URL url = new URL(sb.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000); // 5s超时
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == HttpStatus.SC_OK) {// HttpStatus.SC_OK ==
            // 200
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            return sbs.toString();
        }

        return null;
    }
}

OpenIdJson entity classes:

package com.ft.feathertrade.entity;

public class OpenIdJson {
    private String openid;
    private String session_key;

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public String getSession_key() {
        return session_key;
    }

    public void setSession_key(String session_key) {
        this.session_key = session_key;
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/to-red/p/11563854.html