微信公众平台开发[5]-开发模式-高级功能-获取access_token

access_token 是微信公众平台的一大亮点,有了这个值,在权限允许的情况下你可以做
1、自定义菜单管理;
2、主动发消息;
3、获取关注用户的信息;
4、通过图片、视频、音频ID获取内容;
5、将图片、视频、音频I内容上传到微信服务器并发送给用户;


接下来文章我只会讲解“自定义菜单管理”,其余的几个接口,我这里虽然有文档,但考虑到微信官方没有公布相应的接口,故我在这里只先做预留,不暴露,请谅解。
本篇主要讲解如何获取access_token。
access_token是微信提供的一串很长的字符串,是通过appid、appsecret去微信服务器获取。

appid、appsecret这两个值微信官方文档中也有说明:

1、成为开发者;(能接入到“开发模式”必定已经是开发者了)
2、成功申请自定义菜单;(目前只支持“服务号”)
如果满足此两点在如下图所示的地方会有appid、appsecret的ID:
微信公众平台开发[5]-开发模式-高级功能-获取access_token
文章图片




使用appid、appsecret获取access_token的方法有两种:
1、浏览器直接打开:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}

替换地址中的${appid}、${appsecret}
在浏览器中浏览器直接打开即可。



2、通过程序获取:

package weixin; import java.io.IOException; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import MySecureProtocolSocketFactory; public class AccessTokenGet { private final static String appid = "${appid}"; private final static String secretid = ${secretid}; public static void main(String[] args) { HttpClient httpclient; String url; GetMethod method; ProtocolSocketFactory fcty; url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; url += "&appid=" + appid; url += "&secret="+secretid; //https 证书 fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); httpclient = new HttpClient(); url = new GetMethod(url); // get调用 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println(statusCode + ": " + method.getStatusLine()); } else { System.out.println(new String(method.getResponseBody(), "UTF-8")); } } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } } }


因链接是https的故需要以下两个类来支持:
MySecureProtocolSocketFactory.java


package weixin; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClientError; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory { private SSLContext sslContext = null; /** * Constructor for MySecureProtocolSocketFactory. */ public MySecureProtocolSocketFactory() { } /** * * @return */ private static SSLContext createEasySSLContext() { try { SSLContext context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] { new MyX509TrustManager() }, null); return context; } catch (Exception e) { throw new HttpClientError(e.toString()); } } /** * * @return */ private SSLContext getSSLContext() { if (this.sslContext == null) { this.sslContext = createEasySSLContext(); } return this.sslContext; } /* * (non-Javadoc) * * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String, *int, java.net.InetAddress, int) */ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } /* * (non-Javadoc) * * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String, *int, java.net.InetAddress, int, *org.apache.commons.httpclient.params.HttpConnectionParams) */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); } } /* * (non-Javadoc) * * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port); } /* * (non-Javadoc) * * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }


MyX509TrustManager.java


package weixin; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class MyX509TrustManager implements X509TrustManager { /* * (non-Javadoc) * * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], *java.lang.String) */ public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } /* * (non-Javadoc) * * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], *java.lang.String) */ public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } /* * (non-Javadoc) * * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { return null; } }


代码中用到了apache的开源包
下载地址:http://download.csdn.net/detail/yuyang2013/5959699
也可从apache官网下载。



正确情况下会返回:
{"access_token":"${access_token}","expires_in":7200}

${access_token} 就是你的access_token,这个access_token的有效时间为2个小时。

获取此access_token需要注意以下几点:
1、每天最大获取次数为200次;
2、一旦从新获取,上一次获取的access_token就不能用了;
3、妥善保管好此access_token。
提供两种方式的原因是,有些用户需要程序自动去获取,程序管理即可,而有些用户或许只需要用一次。
【微信公众平台开发[5]-开发模式-高级功能-获取access_token】






    推荐阅读