微信小程序Login后JAVA获取session_key和openid

//js的数据 
 globalData:{
    userInfo:null,
    codetest:'',
    sessionId:'',
    loginCode:''
  }

const APPId = "写自己的ID";
const app_Secret = "开小程序开发设置里生成过来即可";
//JS的代码
 login: function (cb) {
    var that = this
    wx.login({
      success: function (res) {
        console.log('login')
        //获取login的CODE
        console.log(res)
        that.globalData.loginCode =res.code;
        //发起网络请求,这里是利用res.code与APPID+APPSecret向微信服务器
//(https://api.weixin.qq.com/sns/jscode2session)
//发起request请求获取sessionKey和openid,仅用于测试,实际中需要通过服务器取获取
        //application/x-www-form-urlencoded
        //application/json
        console.log(that.globalData.loginCode)
        wx.request({
          method: 'POST',
          // url: 'https://api.weixin.qq.com/sns/jscode2session?
//appid=' + APPId + '&secret=' + app_Secret + '&js_code=' + res.code + '&grant_type=authorization_code',
          url: 'http://localhost:8080/WebTest2/CheckWxDataServlet',
          data: {
            js_code: that.globalData.loginCode,
            appId:APPId,
            appSecret:app_Secret
          },
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: function (res) {
            console.log('request开始写服务器端获取数据app');
            console.log(res.data);
            //登录成功,开始写入3rdsession_key数据
            wx.setStorage({
              key: '3rdsession_key',
              data: res.data.session_key,
            })
            console.log('request success')
            wx.getUserInfo({
              success: function (res) {
                console.log('登录成功!')
                console.log(res.userInfo)
                that.globalData.userInfo == res.userInfo
                typeof cb == "function" && cb(that.globalData.userInfo)
              }
            })
          }, fail: function (res) {
            console.log('request error1' + res.data)
          },
          fail: res => {
            console.log('request error2')
          }
        })
      }, fail: function (res) {
        console.log('log fail' + res.data)
      }
    })
  },


//wxml的数据 
<button bindtap="login" type="submit" class="button_submit">登录</button>

以上为微信小程序端代码

 

小程序代码与java--Servlet 关联请求微信服务获取session_key 与opendid

 


/**
 * Servlet implementation class CheckWxDataServlet
 */
@WebServlet("/CheckWxDataServlet")
public class CheckWxDataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckWxDataServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String appid = request.getParameter("appId").toString();
		String js_code = request.getParameter("js_code").toString();
		String secret = request.getParameter("appSecret").toString();		
		String params ="appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type=authorization_code";
		System.out.println(params);	
//此处为拷贝res.code过来执行测试是否可行,一开始因为拼凑的等号前面多了一个控制
//导致的错误,才这样测试
		String params2 ="appid=wxae6ffe97d0fee46f&secret=925e344466e932fb7577e154077b1781
//&js_code=071wRPwb0upIEx1Yp9yb0bsSwb0wRPwA&grant_type=authorization_code";

	String sr =us.getopenid("http://localhost:8080/WebTest2/returnInfoServlet?",params2);		
		UserDBO us = new UserDBO();
		String sr =us.getOpenid("https://api.weixin.qq.com/sns/jscode2session?",params);
		JSONObject job = JSONObject.fromObject(sr);
		PrintWriter pw2 = response.getWriter();
		pw2.write(job.toString());
		System.out.println(job.toString()+"  sessionKey:"+job.get("session_key"));
//至此已经结束,至于写自己的session在传到小程序端这里不做介绍,自由发挥吧
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	

}

参数与等号之间不能有空格

官方参考文档

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

  
    public String getOpenid(String urlParam, String param) {  
        BufferedReader in = null;  
        //appid和secret是开发者分别是小程序ID和小程序密钥,开发者通过微信公众平台-》设置-》开发设置就可以直接获取,
        String url=urlParam+param;
        try {  
		URL Url = new URL(url); 
            // 打开和URL之间的连接  
            URLConnection connection = Url.openConnection();  
            // 设置通用的请求属性  
            connection.setConnectTimeout(5000);  
            connection.setReadTimeout(5000);  
            // 建立实际的连接  
            connection.connect();  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
            StringBuffer sb = new StringBuffer();  
            String line;  
            while ((line = in.readLine()) != null) {  
                sb.append(line);  
            }  
            return sb.toString();  
        } catch (Exception e1) {  
        	throw new RuntimeException(e1);
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
    }  

小程序端返回如下:

至此完成红色框部分内容

紫色框部分自己看情况做吧

此文章为从各大博客汇总写的可以实现的部分,这里没有坑,欢迎有问题留言咨询

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页