需要了解的知识:OATH2的简单机制。http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html这篇文章写得很清晰(谢谢作者)。
基本流程(从微信官方文档截图):(说的很详细)
自己理解:首先使用appId在手机客户端向微信开放平台发起请求---->返回code零时票据,让后客户端请求自己的服务器端(code作为参数)---->服务器使用code加上app ID河appSecret(不能放在客户端,容易泄露)向微信开放平台发起请求---->返回access_token。然后服务器端就可以根据access_token获取到授权用户的一些信息。
下面是我的代码实现:
第一部分:(客户端)
第一个页面:
/**
* 发起请求的页面,只有一个按钮
*@authorylh
*
*/
publicclassYlhActivityextendsActivity {
StringAPP_ID="******";//改成你自己的APP_ID
privateIWXAPIapi;
privateButtonbtn_sanfangLogin_activity_main;
publicstaticStringuuid=null;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_sanfangLogin_activity_main= (Button) findViewById(R.id.btn_sanfangLogin_activity_main);
api= WXAPIFactory.createWXAPI(this,APP_ID);
api.registerApp(APP_ID);
btn_sanfangLogin_activity_main
.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
if(!api.isWXAppInstalled()) {
Toast.makeText(YlhActivity.this,"未安装微信客户端,请先下载",
Toast.LENGTH_LONG).show();
return;
}
uuid= UUID.randomUUID().toString();
finalSendAuth.Req req =newSendAuth.Req();
req.scope="snsapi_userinfo";
req.state=uuid;
System.out.println("state: "+uuid);
booleanb =api.sendReq(req);
System.out.println(b);
}
});
}
}
第二个页面:
/**
* 授权后,微信客户端调用的页面(Android:exported="true")
*@authorylh
*
*/
publicclassWXEntryActivityextendsActivityimplementsIWXAPIEventHandler {
StringAPP_ID="*****";//改成你自己的APP_ID
privateIWXAPIapi;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
api= WXAPIFactory.createWXAPI(this,APP_ID);
api.registerApp(APP_ID);
api.handleIntent(getIntent(),this);
}
@Override
publicvoidonReq(BaseReq arg0) {
System.out.println("onRep");
}
@Override
publicvoidonResp(BaseResp resp) {
System.out.println("onResp");
switch(resp.errCode) {
caseBaseResp.ErrCode.ERR_OK:
System.out.println("成功");
SendAuth.Resp response = (SendAuth.Resp) resp;
System.out.println(response.state);
if(response.state==null
|| !response.state.equals(YlhActivity.uuid))
return;// 判断请求是否是我的应用的请求
System.out.println(response.code);
System.out.println(response.country);
break;
caseBaseResp.ErrCode.ERR_USER_CANCEL:
System.out.println("quxiao");
break;
caseBaseResp.ErrCode.ERR_AUTH_DENIED:
System.out.println("jujue");
break;
default:
break;
}
}
}
第二部分:(服务器端,使用httpClient向微信开放平台发起请求,使用json-lib-2.4-jdk15.jar解析返回的结果)
/**
* 发起get请求的方法
*@paramurlAddress
*@return
*/
publicstaticString doGet(StringurlAddress) {
StringgetUrl=urlAddress;
HttpGethttpGet=newHttpGet(getUrl);
HttpParamshp=httpGet.getParams();
hp.getParameter("true");
//hp.
// httpGet.setp
HttpClienthc= HttpClients.createDefault();
try{
HttpResponseht=hc.execute(httpGet);
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntityhe=ht.getEntity();
InputStreamis=he.getContent();
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
Stringresponse="";
StringreadLine=null;
while((readLine=br.readLine()) !=null) {
// response = br.readLine();
response=response+readLine;
}
is.close();
br.close();
// Stringstr= EntityUtils.toString(he);
System.out.println(response);
returnresponse;
}else{
return"error";
}
}catch(ClientProtocolExceptione) {
//TODOAuto-generated catch block
e.printStackTrace();
return"exception";
}catch(IOExceptione) {
//TODOAuto-generated catch block
e.printStackTrace();
return"exception";
}
}
下面就调用:
1. 使用客户端传来的code,加上app ID河appSecret(不能放在客户端,容易泄露)向微信开放平台发起请求
doGet("https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&appid=***********&secret=***********&code=***********");(***********的地方替换相应的参数)返回access_token和openid
2. 使用上一步获得的access_token和openid向微信开放平台发起请求,获得用户信息
Stringresp= doGet("https://api.weixin.qq.com/sns/userinfo?access_token=**********&openid=***********");
JSONObjectjObject= JSONObject.fromObject(resp);
Stringopenid=jObject.get("openid").toString();
Stringnickname=jObject.get("nickname").toString();
Stringsex=jObject.get("sex").toString();
Stringlanguage=jObject.get("language").toString();
Stringcity=jObject.get("city").toString();
Stringprovince=jObject.get("province").toString();
Stringcountry=jObject.get("country").toString();
Stringheadimgurl=jObject.get("headimgurl").toString();
Stringprivilege=jObject.get("privilege").toString();
Stringunionid=jObject.get("unionid").toString();
System.out.println(openid);
System.out.println(nickname);
System.out.println(sex);
System.out.println(language);
System.out.println(city);
System.out.println(province);
System.out.println(country);
System.out.println(headimgurl);
System.out.println(privilege);
System.out.println(unionid);
注:JSONObject使用的是json-lib-2.4-jdk15.jar解析,依赖的jar包有
commons-beanuitls-1.7.0.jar、commons-collections-3.2.jar、commons-lang-2.4.jar、commons-logging-1.2.jar、ezmorph-1.0.4.jar、json-lib-2.4-jdk15.jar
微信技术交流群号:ffffff888886666