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();
}
}
}
最终获取到如下内容:
一、首先注册微信开放平台账户,并创建应用,目前支持三种: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_in | access_token接口调用凭证超时时间,单位(秒) |
refresh_token | 用户刷新access_token |
openid | 授权用户唯一标识 |
scope | 用户授权的作用域,使用逗号(,)分隔 |
unionid | 只有在用户将公众号绑定到微信开放平台帐号后,才会出现 |
相关文章推荐
- android接入原生第三方登录(微信登录、QQ登录、新浪微博登录)
- android接入原生第三方登录(微信登录、QQ登录、新浪微博登录)
- android接入原生第三方登录(微信登录、QQ登录、新浪微博登录)
- android接入原生第三方登录(微信登录、QQ登录、新浪微博登录)
- Android开发接入第三方原生SDK实现微信登录
- android接入原生第三方登录(微信登录、QQ登录、新浪微博登录)
- Android 第三方应用接入微信平台(1)
- Android 使用shareSDK进行第三方登录失败解决方法(微信,微博,qq)
- android第三方登录之微信登录详情
- 微信第三方登录Android实现
- 微信授权登陆接入第三方App(步骤总结)Android
- 微信授权登陆接入第三方App(Android)
- Android 第三方应用接入微信平台(2)
- 微信第三方接入遇到的科恩(坑)——登录、分享
- Android 第三方应用接入微信平台研究情况分享
- Android 微信第三方App登录
- Android 第三方应用接入微信平台研究情况分享
- Android 第三方应用接入微信平台研究情况分享(一) 详细出处参考:http://www.jb51.net/article/33048.htm
- Android 第三方应用接入微信平台(1)
- Android 第三方应用接入微信平台(1)