獲取微信OpenId
- 先獲取code 
- 再通過code獲取authtoken,從authtoken中取出openid給前臺 
- 微信端一定不要忘記設定網頁賬號中的授權回調頁面域名 
流程圖如下

主要代碼
頁面js代碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /* 寫cookie 
*/functionsetCookie(name, value) {  varDays = 30;  varexp = newDate();  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 
1000);  document.cookie = name + "="+ escape(value) + 
";expires="+ 
exp.toGMTString() + ";path=/";}/* 讀cookie 
*/functiongetCookie(name) {  vararr = 
document.cookie.match(newRegExp("(^| )"+ name + "=([^;]*)(;|$)"));  if(arr != null) {    returnunescape(arr[2]);  }  returnnull;}/* 獲取URL參數 
*/functiongetUrlParams(name) {  varreg = newRegExp("(^|&)"+ name + 
"=([^&]*)(&|$)", "i");  varr = 
window.location.search.substr(1).match(reg);  if(r != null) {    returnunescape(r[2]);  }  returnnull;}/* 獲取openid 
*/functiongetOpenId(url) {  varopenid = 
getCookie("usropenid");  if(openid == null) {    openid = getUrlParams('openid');    alert("openid="+openid);    if(openid == null) {      window.location.href = 
"wxcode?url="+ 
url;    } else{      setCookie("usropenid", 
openid);    }  }} | 
WxCodeServlet代碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | //訪問微信獲取code@Overrideprotected void 
doPost(HttpServletRequest req, HttpServletResponse resp)    throws ServletException, IOException {  String state = req.getParameter("url");  //WxOpenIdServlet的地址  redirect = URLEncoder.encode(redirect, "utf-8");      .append(Configure.APP_ID).append("&redirect_uri=").append(redirect)      .append("&response_type=code&scope=snsapi_base&state=").append(state).append("#wechat_redirect");  resp.sendRedirect(url.toString());} | 
WxOpenIdServlet代碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //訪問微信獲取openid@Overrideprotected void 
doPost(HttpServletRequest req, HttpServletResponse resp)    throws ServletException, IOException {  String code = req.getParameter("code");  String state = req.getParameter("state");  Result ret = newResult();  AuthToken token = WXUtil.getAuthToken(code);  if(null!= 
token.getOpenid()){    ret.setCode(0);    log.info("====openid=="+token.getOpenid());    Map<String,String> map = newHashMap<String,String>();    map.put("openid", token.getOpenid());    map.put("state", state);    ret.setData(map);  }else{    ret.setCode(-1);    ret.setMsg("登錄錯誤");  }  String redUrl = state+"?openid="+token.getOpenid();  resp.sendRedirect(redUrl);} | 
獲取AuthToken(WXUtil.getAuthToken(code))代碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static 
AuthToken getAuthToken(String code){  AuthToken vo = null;  try{    StringBuffer url = newStringBuffer(uri);    url.append("appid=").append(Configure.APP_ID);    url.append("&secret=").append(Configure.APP_SECRET);    url.append("&code=").append(code);    url.append("&grant_type=").append("authorization_code");    HttpURLConnection conn = 
HttpClientUtil.CreatePostHttpConnection(url.toString());    InputStream input = null;    if(conn.getResponseCode() == 
200) {      input = 
conn.getInputStream();    } else{      input = 
conn.getErrorStream();    }    vo = JSON.parseObject(newString(HttpClientUtil.readInputStream(input),"utf-8"),AuthToken.class);  } catch(Exception e) {    log.error("getAuthToken 
error", e);  }  returnvo;} | 
HttpClientUtil類
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | package 
com.huatek.shebao.util;import 
java.io.ByteArrayOutputStream;import 
java.io.DataOutputStream;import 
java.io.IOException;import 
java.io.InputStream;import 
java.net.HttpURLConnection;import 
java.net.MalformedURLException;import 
java.net.ProtocolException;import 
java.net.URL;public class 
HttpClientUtil {  // 設置body體  public static void setBodyParameter(String sb, 
HttpURLConnection conn)      throws IOException 
{    DataOutputStream out = newDataOutputStream(conn.getOutputStream());    out.writeBytes(sb);    out.flush();    out.close();  }  // 添加簽名header  public static HttpURLConnection CreatePostHttpConnection(String 
uri) throws MalformedURLException,      IOException, 
ProtocolException {    URL url = newURL(uri);    HttpURLConnection conn = (HttpURLConnection) 
url.openConnection();    conn.setUseCaches(false);    conn.setDoInput(true);    conn.setDoOutput(true);    conn.setRequestMethod("POST");    conn.setInstanceFollowRedirects(true);    conn.setConnectTimeout(30000);    conn.setReadTimeout(30000);    conn.setRequestProperty("Content-Type","application/json");    conn.setRequestProperty("Accept-Charset", "utf-8");    conn.setRequestProperty("contentType", "utf-8");    returnconn;  }  public static byte[] readInputStream(InputStream inStream) 
throws Exception {    ByteArrayOutputStream outStream = newByteArrayOutputStream();    byte[] buffer = newbyte[1024];    int len = 0;    while((len = 
inStream.read(buffer)) != -1) {      outStream.write(buffer, 0, 
len);    }    byte[] data = outStream.toByteArray();    outStream.close();    inStream.close();    returndata;  }} | 
封裝AuthToken的VO類
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package 
com.huatek.shebao.wxpay;public class 
AuthToken {  private String access_token;  private Long expires_in;  private String refresh_token;  private String openid;  private String scope;  private String unionid;  private Long errcode;  private String errmsg;  public String getAccess_token() {    returnaccess_token;  }  public void setAccess_token(String access_token) {    this.access_token = 
access_token;  }  public Long getExpires_in() {    returnexpires_in;  }  public void setExpires_in(Long expires_in) {    this.expires_in = 
expires_in;  }  public String getRefresh_token() {    returnrefresh_token;  }  public void setRefresh_token(String refresh_token) 
{    this.refresh_token = 
refresh_token;  }  public String getOpenid() {    returnopenid;  }  public void setOpenid(String openid) {    this.openid = 
openid;  }  public String getScope() {    returnscope;  }  public void setScope(String scope) {    this.scope = 
scope;  }  public String getUnionid() {    returnunionid;  }  public void setUnionid(String unionid) {    this.unionid = 
unionid;  }  public Long getErrcode() {    returnerrcode;  }  public void setErrcode(Long errcode) {    this.errcode = 
errcode;  }  public String getErrmsg() {    returnerrmsg;  }  public void setErrmsg(String errmsg) {    this.errmsg = 
errmsg;  }} | 
