您的位置:首页 > 移动开发 > 微信开发

Android微信第三方登录接入

2015-03-30 20:07 369 查看
微信开放平台地址:https://open.weixin.qq.com/

一、首先注册微信开放平台账户,并创建应用,目前支持三种:Android、IOS、WP8

       创建完应用后需要审核,审核通过后会得到AppID和AppSecret。

       设置android app包名(如:com.test.partylogin)和应用签名。

时序图如下:



二、创建一个新工程

1、复制并导入包:   

          


2、新建包:com.test.partylogin.wxapi,并在其中新建一个WXEntryActivity,这个必须要建立在wxapi下,用于微信的回调:

代码如下:

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
// IWXAPI 是第三方app和微信通信的openapi接口
private IWXAPI api;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry);

// 通过WXAPIFactory工厂,获取IWXAPI的实例
api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
// 将该app注册到微信
api.registerApp(Constants.APP_ID);
}

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);

setIntent(intent);
api.handleIntent(intent, this);
}

// 微信发送请求到第三方应用时,会回调到该方法
@Override
public void onReq(BaseReq req) {
switch (req.getType()) {
case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
goToGetMsg();
break;
case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
goToShowMsg((ShowMessageFromWX.Req) req);
break;
default:
break;
}
}

// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
@Override
public void onResp(BaseResp resp) {
int result = 0;

switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
result = R.string.errcode_success;
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();
}
}
3、调用需要的地方注册并调用微信api:(这里调用的api将会在onResp方法中处理回调结果)



此处将获取到code授权临时票据

4、通过Https get请求获取到access_token:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 网络请求方法如下:

package info.cd120.tools;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
* Created by John Lee on 03-30.
*/
public class HttpUtils {

private static final int CONNECTION_TIMEOUT = 10000;

public static String doHttpGet(String serverURL) throws Exception {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(serverURL);
get.addHeader("Content-Type", "text/xml");
get.setParams(httpParameters);
HttpResponse response = null;
try {
response = hc.execute(get);
} catch (UnknownHostException e) {
throw new Exception("Unable to access " + e.getLocalizedMessage());
} catch (SocketException e) {
throw new Exception(e.getLocalizedMessage());
}
int sCode = response.getStatusLine().getStatusCode();
if (sCode == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else
throw new Exception("StatusCode is " + sCode);
}

public static String doHttpsGet(String serverURL) throws Exception {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpClient hc = initHttpClient(httpParameters);
HttpGet get = new HttpGet(serverURL);
get.addHeader("Content-Type", "text/xml");
get.setParams(httpParameters);
HttpResponse response = null;
try {
response = hc.execute(get);
} catch (UnknownHostException e) {
throw new Exception("Unable to access " + e.getLocalizedMessage());
} catch (SocketException e) {
throw new Exception(e.getLocalizedMessage());
}
int sCode = response.getStatusLine().getStatusCode();
if (sCode == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else
throw new Exception("StatusCode is " + sCode);
}

public static String doHttpPost(String serverURL, String xmlString) throws Exception {
Log.d("doHttpPost", "serverURL=" + serverURL);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost(serverURL);
post.addHeader("Content-Type", "text/xml");
post.setEntity(new StringEntity(xmlString, "UTF-8"));
post.setParams(httpParameters);
HttpResponse response = null;
try {
response = hc.execute(post);
} catch (UnknownHostException e) {
throw new Exception("Unable to access " + e.getLocalizedMessage());
} catch (SocketException e) {
throw new Exception(e.getLocalizedMessage());
}

b7aa
int sCode = response.getStatusLine().getStatusCode();
Log.d("response code ", "sCode="+sCode);
if (sCode == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else
throw new Exception("StatusCode is " + sCode);
}

public static String doHttpsPost(String serverURL, String xmlString) throws Exception {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpClient hc = initHttpClient(httpParameters);
HttpPost post = new HttpPost(serverURL);
post.addHeader("Content-Type", "text/xml");
post.setEntity(new StringEntity(xmlString, "UTF-8"));
post.setParams(httpParameters);
HttpResponse response = null;
try {
response = hc.execute(post);
} catch (UnknownHostException e) {
throw new Exception("Unable to access " + e.getLocalizedMessage());
} catch (SocketException e) {
throw new Exception(e.getLocalizedMessage());
}
int sCode = response.getStatusLine().getStatusCode();
if (sCode == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else
throw new Exception("StatusCode is " + sCode);
}

public static HttpClient initHttpClient(HttpParams params) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient(params);
}
}

public static class SSLSocketFactoryImp extends SSLSocketFactory {
final SSLContext sslContext = SSLContext.getInstance("TLS");

public SSLSocketFactoryImp(KeyStore truststore) throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws java.security.cert.CertificateException {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws java.security.cert.CertificateException {
}
};
sslContext.init(null, new TrustManager[] {
tm
}, null);
}

@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
}

最终获取到如下内容:

参数说明
access_token接口调用凭证
expires_inaccess_token接口调用凭证超时时间,单位(秒)
refresh_token用户刷新access_token
openid授权用户唯一标识
scope用户授权的作用域,使用逗号(,)分隔
  unionid只有在用户将公众号绑定到微信开放平台帐号后,才会出现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息