App下載
話題 首頁 > 微信小程序開發(fā)文檔 > 微信小程序開發(fā)文檔話題列表 > 詳情

如何獲取微信小程序用戶openid?

精華
唐婷大小姐 2016-11-24 10:47:47 瀏覽(11028) 回復(fù)(7) 贊(1)
微信小程序要怎樣獲取微信OpenId?
微信小程序

回答(7)

李大寶兒 精華 2016-11-24

獲取微信OpenId


  1. 先獲取code
  2. 再通過code獲取authtoken,從authtoken中取出openid給前臺(tái)
  3. 微信端一定不要忘記設(shè)定網(wǎng)頁賬號(hào)中的授權(quán)回調(diào)頁面域名

流程圖如下

獲取微信OpenId流程圖

主要代碼


頁面js代碼

/* 寫cookie */
function setCookie(name, value) {
  var Days = 30;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}
/* 讀cookie */
function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) {
    return unescape(arr[2]);
  }
  return null;
}
/* 獲取URL參數(shù) */
function getUrlParams(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
/* 獲取openid */
function getOpenId(url) {
  var openid = 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代碼

//訪問微信獲取code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String state = req.getParameter("url");
  //WxOpenIdServlet的地址
  String redirect ="http://"+Configure.SITE+"/wxopenid";
  redirect = URLEncoder.encode(redirect, "utf-8");
  StringBuffer url = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?appid=")
      .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代碼

//訪問微信獲取openid
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String code = req.getParameter("code");
  String state = req.getParameter("state");
  Result ret = new Result();
  AuthToken token = WXUtil.getAuthToken(code);
  if(null != token.getOpenid()){
    ret.setCode(0);
    log.info("====openid=="+token.getOpenid());
    Map<String,String> map = new HashMap<String,String>();
    map.put("openid", token.getOpenid());
    map.put("state", state);
    ret.setData(map);
  }else{
    ret.setCode(-1);
    ret.setMsg("登錄錯(cuò)誤");
  }
  String redUrl = state+"?openid="+token.getOpenid();
  resp.sendRedirect(redUrl);
}

獲取AuthToken(WXUtil.getAuthToken(code))代碼

public static AuthToken getAuthToken(String code){
  AuthToken vo = null;
  try {
    String uri = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    StringBuffer url = new StringBuffer(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(new String(HttpClientUtil.readInputStream(input),"utf-8"),AuthToken.class);
  } catch (Exception e) {
    log.error("getAuthToken error", e);
  }
  return vo;
}

HttpClientUtil類

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 {
  // 設(shè)置body體
  public static void setBodyParameter(String sb, HttpURLConnection conn)
      throws IOException {
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(sb);
    out.flush();
    out.close();
  }
  // 添加簽名header
  public static HttpURLConnection CreatePostHttpConnection(String uri) throws MalformedURLException,
      IOException, ProtocolException {
    URL url = new URL(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");
    return conn;
  }
  public static byte[] readInputStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inStream.read(buffer)) != -1) {
      outStream.write(buffer, 0, len);
    }
    byte[] data = outStream.toByteArray();
    outStream.close();
    inStream.close();
    return data;
  }
}

封裝AuthToken的VO類

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() {
    return access_token;
  }
  public void setAccess_token(String access_token) {
    this.access_token = access_token;
  }
  public Long getExpires_in() {
    return expires_in;
  }
  public void setExpires_in(Long expires_in) {
    this.expires_in = expires_in;
  }
  public String getRefresh_token() {
    return refresh_token;
  }
  public void setRefresh_token(String refresh_token) {
    this.refresh_token = refresh_token;
  }
  public String getOpenid() {
    return openid;
  }
  public void setOpenid(String openid) {
    this.openid = openid;
  }
  public String getScope() {
    return scope;
  }
  public void setScope(String scope) {
    this.scope = scope;
  }
  public String getUnionid() {
    return unionid;
  }
  public void setUnionid(String unionid) {
    this.unionid = unionid;
  }
  public Long getErrcode() {
    return errcode;
  }
  public void setErrcode(Long errcode) {
    this.errcode = errcode;
  }
  public String getErrmsg() {
    return errmsg;
  }
  public void setErrmsg(String errmsg) {
    this.errmsg = errmsg;
  }
}

更多關(guān)于微信小程序可以查看

晴天3223 2017-07-25

千篇一律的復(fù)制粘貼,你們回答問題能不能過過腦子。

一筆荒蕪 2018-05-31

吃瓜群眾,坐等大神來解決。。。。。

1144100656 2018-05-31

好慢呀,空空如也,半天不來大神解決,大佬在哪啦

1152696398 2018-05-31

我也不清楚,坐等大神,火鉗劉明?。?!

微信小程序 實(shí)現(xiàn)了應(yīng)用“觸手可及”的夢想,用戶掃一掃或搜一下即可打開應(yīng)用。不用安裝,即開即用,用完就走。省流量,省安裝時(shí)間,不占用桌面。對(duì)用戶使用上來說,確實(shí)方便,沒有繁瑣的注冊(cè),沒有反復(fù)的驗(yàn)證,只要你是微信用戶,他就隱藏在你的微信里面,要用的時(shí)候打開,不用的時(shí)候關(guān)掉,即用即走。這點(diǎn)比需要下載,還要占用手機(jī)內(nèi)存空間的APP要好。 高效便捷的獲取客流量,對(duì)于小程序擁有者來說,相較于原生APP,推廣更容易更簡單,更省成本。微信小程序意味著有多少人使用微信,就有多少人會(huì)使用小程序,共享9億+微信現(xiàn)成活躍用戶。相比app,小程序擁有眾多流量入口,獲客更高效便捷。搜索功能讓你脫穎而出:騰訊為小程序開放了搜索功能,就是說只要你有了自己的小程序,大家在搜索里就可以找到你;附近小程序流量開放是你引流的利器:只要你自己開發(fā)了小程序,除了微信搜索能找到你以外,微信開放流量,讓你自動(dòng)出現(xiàn)在別人手機(jī)附近小程序的序列里。 最后給大家推薦一個(gè)制作微信小程序不錯(cuò)的網(wǎng)站,大家有時(shí)間可以去看看~http://www.ymznkf.com/index.aspx?tg=6844 交流群:164210836.....期待你的加入!

要回復(fù),請(qǐng)先登錄 或者注冊(cè)