需求:接入微信支付,需要獲取 OpenID。
微信開放平臺上面對大多數步驟都有詳細的介紹。但是……,還是自己梳理一下吧。
1.申請AppID。
(微信支付或微信登錄等功能需要進行開發者資質認證,準備好300大洋)
2.下載最新SDK。
3.導入jar包,並配置權限。
4.代碼實現
① 註冊到微信
// 通過WXAPIFactory工廠,獲取IWXAPI的實例
api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
api.handleIntent(getIntent(), this);
// 將該app註冊到微信
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) {
// APP_ID和APP_Secret在微信開發平臺添加應用的時候會生成,grant_type 用默認的"authorization_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.configCurrentHttpCacheExpiry(1000 * 10);
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 OpenID
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就害的我很慘。
2.調試時的應用簽名和正式版的應用簽名是不一致的,應該區別對待,分別獲取。簽名生成工具鏈接。
3.網絡訪問HttpUtils用的是xUtils.jar包裏面的類,不要誤會了。