PS: sendAuthRequest拿到code,經過code拿到access_token和openId,access_token能夠拿到用戶的信息java
http://blog.csdn.net/haovip123/article/details/50503176json
需求:接入微信支付,須要獲取 OpenID。
微信開放平臺上面對大多數步驟都有詳細的介紹。可是……,仍是本身梳理一下吧。
1.申請AppID。
(微信支付或微信登陸等功能須要進行開發者資質認證,準備好300大洋)
2.下載最新SDK。
3.導入jar包,並配置權限。
4.代碼實現
① 註冊到微信
- api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
- api.handleIntent(getIntent(), this);
- api.registerApp(Constants.APP_ID);
② 發送請求
- final SendAuth.Req req = new SendAuth.Req();
- req.scope = "snsapi_userinfo";
- req.state = "wechat_sdk_demo_test";
- api.sendReq(req);
③ 接受微信請求(獲取code值)
- @Override
- public void onResp(BaseResp resp) {
- int result = 0;
- SendAuth.Resp re = ((SendAuth.Resp) resp);
- String code = re.code;
-
- switch (resp.errCode) {
- case BaseResp.ErrCode.ERR_OK:
- result = R.string.errcode_success;
- getOpenID(code);
-
- break;
- case BaseResp.ErrCode.ERR_USER_CANCEL:
- result = R.string.errcode_cancel;
- break;
- case BaseResp.ErrCode.ERR_AUTH_DENIED:
- result = R.string.errcode_deny;
- break;
- default:
- result = R.string.errcode_unknown;
- break;
- }
-
- Toast.makeText(this, result, Toast.LENGTH_LONG).show();
- Toast.makeText(this, code, Toast.LENGTH_LONG).show();
- }
④ 經過code獲取access_token,code等數據
- private void getOpenID(String code) {
-
- String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.APP_ID+"&secret="+Constants.APP_Secret+
- "&code="+code+"&grant_type=authorization_code";
-
- HttpUtils http = new HttpUtils();
-
-
- http.send(HttpRequest.HttpMethod.GET, urlStr, null,
- new RequestCallBack<String>() {
-
- @Override
- public void onSuccess(ResponseInfo<String> info) {
- System.out.println("返回的json字符串:" + info.result);
- Toast.makeText(getApplicationContext(), info.result, Toast.LENGTH_SHORT).show();
-
- JSONObject obj = null;
- try {
- obj = new JSONObject(info.result);
-
- Toast.makeText(getApplicationContext(), obj.getString("openid"), Toast.LENGTH_LONG).show();
-
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {
-
- }
- });
- }
1.下載的SDK必定要是最新的,舊一點的SDK裏面在獲取code的時候沒有 .code屬性,好比官方demo中萬年不變的sdk就害的我很慘。
簽名生成工具連接。