微信小程序使用spring boot获取用户唯一标识openId

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013934408/article/details/83541284

1.app.js里面调用wx.login(OBJECT) 获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)等。

//app.js
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    wx.login({
      success: function(res) {
        if (res.code) {
          wx.getUserInfo({
            success: function(userRes) {
              var name, url;
              console.log("name:" + userRes.userInfo.nickName + " url:" + userRes.userInfo.avatarUrl + " code:" + res.code);
              wx.request({
                url: 'https://www.test.com/wx/toLogin',//调用第三方服务器换取openid
                // header: {
                //   "Content-Type": "application/x-www-form-urlencoded"//默认是application/json
                // },
                method: "GET",
                data: {
                  code: res.code,
                  name: userRes.userInfo.nickName,
                  url: userRes.userInfo.avatarUrl
                },
                success: function() {
                  console.log("success")
                },
                fail: function() {
                  console.log("fail")
                }
              })

            }
          })
        }
        console.log("userinfo" + res);
        typeof cb == "function" && cb(that.globalData.userInfo)
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

2.后端接收code并请求微信服务器获取openid,涉及到小程序的appid以及secret

@RestController
@RequestMapping("/wx")
public class WxController {
    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/toLogin")
    public Map<String, Object> doLogin(HttpServletResponse resp, HttpServletRequest req){
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("text/html;charset=UTF-8");
        String code = req.getParameter("code");
        String nickName = req.getParameter("name");
        String avatarUrl = req.getParameter("url");
        
        System.out.println("code:" + code + " nickName:" + nickName + " url:" + avatarUrl);

        String url = AppUtil.wxLoginUrl;
        String param = "appid=" + AppUtil.appId_run + "&secret=" + AppUtil.secret_run + "&js_code=" + code + "&grant_type=authorization_code";

        Map<String, Object> result = new HashMap<String, Object>();
        int error = 0;

        try {
            String ret = WebUtil.sendGet(url, param);
            System.out.println(ret);
            JSONObject obj = JSONObject.parseObject(ret);
            String openid = obj.getString("openid");
            String session_key = obj.getString("session_key");
            result.put("openid", openid);
            System.out.println("session_key:" + session_key);
            User user = new User(openid, nickName, avatarUrl, 0);
            userRepository.save(user);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            error = -1;
        }
        result.put("code", error);
        return result;
    }
}

AppUtil.java里面appId以及secret填写自己小程序的就行,可在微信平台登录查看

public class AppUtil {
    public static final String appId = "";
    public static final String secret = "";
    public static final String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
}

展开阅读全文

没有更多推荐了,返回首页