如何利用wx.login方法获取openid和sessionKey

1,

wx.login(Object object)

调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。

2,

  1. 调用 wx.login() 获取 临时登录凭证code (五分钟有效期),并回传到开发者服务器。
  2. 调用 auth.code2Session 接口,换取 用户唯一标识 OpenID会话密钥 session_key

3,登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。

请求地址

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_cod

4,后台获取openid和sessionkey代码
@RequestMapping(value="/getAppid",method = RequestMethod.GET)
    @ResponseBody
    public  String do_get(String JSCODE) throws ClientProtocolException, IOException {
        String body = "{}";
        String APPID = "wxbea50118b27deed2";
        String SECRET = "916e340c613a39a413076a03d5379692";
//        String JSCODE1 = "021Ktl4S1ognG510zT2S1f7w4S1Ktl4Q";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+JSCODE+"&grant_type=authorization_code");
//            String a = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+JSCODE+"&grant_type=authorization_code";
//            System.out.println(a);
//解决ssl证书问题
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); body = EntityUtils.toString(entity); System.out.println(body); } finally { httpclient.getConnectionManager().shutdown(); } return body; }
 
原文地址:https://www.cnblogs.com/wskb/p/11685818.html