android开发实现微信三方登录
版权声明:本文为博主原创文章,未经博主允许不得转载。
需要了解的知识:OATH2的简单机制。http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html这篇文章写得很清晰(谢谢作者)。
基本流程(从微信官方文档截图):(说的很详细)
自己理解:首先使用appId在手机客户端向微信开放平台发起请求---->返回code零时票据,让后客户端请求自己的服务器端(code作为参数)---->服务器使用code加上app ID河appSecret(不能放在客户端,容易泄露)向微信开放平台发起请求---->返回access_token。然后服务器端就可以根据access_token获取到授权用户的一些信息。
下面是我的代码实现:
第一部分:(客户端)
第一个页面:
/**
* 发起请求的页面,只有一个按钮
* @author ylh
*
*/
public class YlhActivity extends Activity {
String APP_ID = "******";//改成你自己的APP_ID
private IWXAPI api;
private Button btn_sanfangLogin_activity_main;
public static String uuid = null;
@Override
protected void onCreate(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(new OnClickListener() {
@Override
public void onClick(View v) {
if (!api.isWXAppInstalled()) {
Toast.makeText(YlhActivity.this, "未安装微信客户端,请先下载",
Toast.LENGTH_LONG).show();
return;
}
uuid = UUID.randomUUID().toString();
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = uuid;
System.out.println("state: " + uuid);
boolean b = api.sendReq(req);
System.out.println(b);
}
});
}
}
第二个页面:
/**
* 授权后,微信客户端调用的页面( Android:exported="true")
* @author ylh
*
*/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
String APP_ID = "*****";//改成你自己的APP_ID
private IWXAPI api;
@Override
protected void onCreate(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
public void onReq(BaseReq arg0) {
System.out.println("onRep");
}
@Override
public void onResp(BaseResp resp) {
System.out.println("onResp");
switch (resp.errCode) {
case BaseResp.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;
case BaseResp.ErrCode.ERR_USER_CANCEL:
System.out.println("quxiao");
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
System.out.println("jujue");
break;
default:
break;
}
}
}
第二部分:(服务器端,使用httpClient向微信开放平台发起请求,使用json-lib-2.4-jdk15.jar解析返回的结果)
/**
* 发起get请求的方法
* @param urlAddress
* @return
*/
public static String doGet(String urlAddress) {
String getUrl = urlAddress;
HttpGet httpGet = new HttpGet(getUrl);
HttpParams hp = httpGet.getParams();
hp.getParameter("true");
// hp.
// httpGet.setp
HttpClient hc = HttpClients.createDefault();
try {
HttpResponse ht = hc.execute(httpGet);
if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity he = ht.getEntity();
InputStream is = he.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
// response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
// String str = EntityUtils.toString(he);
System.out.println(response);
return response;
} else {
return "error";
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
} catch (IOException e) {
// TODO Auto-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向微信开放平台发起请求,获得用户信息
String resp = doGet("https://api.weixin.qq.com/sns/userinfo?access_token=**********&openid=***********");
JSONObject jObject = JSONObject.fromObject(resp);
String openid = jObject.get("openid").toString();
String nickname = jObject.get("nickname").toString();
String sex = jObject.get("sex").toString();
String language = jObject.get("language").toString();
String city = jObject.get("city").toString();
String province = jObject.get("province").toString();
String country = jObject.get("country").toString();
String headimgurl = jObject.get("headimgurl").toString();
String privilege = jObject.get("privilege").toString();
String unionid = 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