android 微信第三方登录怎么通过code获取openid?

阅读 21.9k
4 个回答

1.登录公众账号设置OAuth2.0
2.设置菜单按钮URL为OAuth链接
3.页面后台获取:

public String getopenId() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/html");
    String code = request.getParameter("code");
    String urlstr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=<appId>&secret=<secret>&code=" + code + "&grant_type=authorization_code";
    JSONObject json;
    try {
        json = JSONObject.fromObject(HTTPTools.postToGetJson(urlstr));
        openId = json.getString("openid");
    } catch (Exception e) {
        // e.printStackTrace();
        return "";
    }
    return openId;
}
新手上路,请多包涵

楼主,跪求你是怎么获取code的?求具体的代码啊。我这个根本无法获取code,反编译之后代码里也没有code这个属性

//重写onresume()方法

@Override
protected void onResume() {
if (type != null && type.equals("mwx")) {
SharedPreferences settings = getSharedPreferences("setting", 0);
String code = settings.getString("code", null);
if (code != null && !code.equals("")) {
showProgress(true);
getOpenid(code);
}
settings.edit().clear();
settings.edit().commit();
}
super.onResume();
}

// 获取微信用户的openid和access token
public void getOpenid(String code) {
final AsyncHttpClient httpClient = Gl.sharedAsyncClient();
RequestParams params = new RequestParams();
params.put("appid", Constants.wxAPP_ID);
params.put("secret", Constants.wxAppSecret);
params.put("code", code);
params.put("grant_type", "authorization_code");
String httpurl = "https://api.weixin.qq.com/sns/oauth2/access_token";
httpClient.get(httpurl, params, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                JSONObject response) {
            try {
                String opendid = response.getString("openid");
                if (opendid != null && !opendid.equals("")) {
                    openid = response.getString("openid");
                    otherLogin("mwx", opendid);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onSuccess(statusCode, headers, response);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题