android微信第三方登陸怎麼經過code獲取openid?

     方法1:html

1.登陸公衆帳號設置OAuth2.0
2.設置菜單按鈕URL爲OAuth連接
3.頁面後臺獲取:java

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


     方法2:json

//重寫onresume()方法api

@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() {app

        @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);
        }
    });
}
相關文章
相關標籤/搜索