微信小程序 springboot后台如何获取用户的openid

发布时间:2020-08-29 17:56:37 作者:SupermanH
来源:脚本之家 阅读:184

openid可以标识一个用户,session_key会变,所以来获取一下openid。

openid不能在微信小程序中直接获取,需要后台发送请求到微信的接口,然后微信返回一个json格式的字符串到后台,后台处理之后,再返回到微信小程序。

发布的小程序需要https的域名,而测试的时候可以使用http。

小程序在app.js中,修改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){
        // 登录成功
        wx.setStorageSync("openid", res.data.openid);//将用户id保存到缓存中
        wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
       }else{
        // 登录失败
        // TODO 跳转到错误页面,要求用户重试


        return false;
       }
      }
     })
    } else {
     console.log('获取用户登录态失败!' + res.errMsg)
    }
   }
  })

这里请求的http://localhost:84/user/login

后台的处理类:

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 userLogin(@RequestParam("code") String code) throws IOException {
    String result = "";
    try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
      result = HttpUtil.doGet(
          "https://api.weixin.qq.com/sns/jscode2session?appid="
              + this.appID + "&secret="
              + this.appSecret + "&js_code="
              + code
              + "&grant_type=authorization_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工具类:

package com.ft.feathertrade.utils;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包

/** 将此依赖添加到pom.xml中
 <dependency>
 <groupId>commons-httpclient</groupId>
 <artifactId>commons-httpclient</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的实体类:

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;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 小程序订阅消息推送(含源码)java实现小程序推送,springboot实现微信消息推送
  2. 微信小程序python用户认证的实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

小程序 spring

上一篇:Python读取分割压缩TXT文本文件实例

下一篇:利用require.js与angular搭建spa应用的方法实例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》