微信小程序 获取微信OpenId详解及实例代码
网络编程 2021-07-04 20:01www.168986.cn编程入门
这篇文章主要介绍了微信小程序 获取微信OpenId详解及实例代码的相关资料,需要的朋友可以参考下
获取微信OpenId
- 先获取code
- 再通过code获取authtoken,从authtoken中取出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参数 / 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./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("登录错误"); } 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./sns/oauth2/aess_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 .huatek.shebao.util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java..HttpURLConnection; import java..MalformedURLException; import java..ProtocolException; import java..URL; public class HttpClientUtil { // 设置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("Aept-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 .huatek.shebao.wxpay; public class AuthToken { private String aess_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 getAess_token() { return aess_token; } public void setAess_token(String aess_token) { this.aess_token = aess_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; } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
编程语言
- 如何快速学会编程 如何快速学会ug编程
- 免费学编程的app 推荐12个免费学编程的好网站
- 电脑怎么编程:电脑怎么编程网咯游戏菜单图标
- 如何写代码新手教学 如何写代码新手教学手机
- 基础编程入门教程视频 基础编程入门教程视频华
- 编程演示:编程演示浦丰投针过程
- 乐高编程加盟 乐高积木编程加盟
- 跟我学plc编程 plc编程自学入门视频教程
- ug编程成航林总 ug编程实战视频
- 孩子学编程的好处和坏处
- 初学者学编程该从哪里开始 新手学编程从哪里入
- 慢走丝编程 慢走丝编程难学吗
- 国内十强少儿编程机构 中国少儿编程机构十强有
- 成人计算机速成培训班 成人计算机速成培训班办
- 孩子学编程网上课程哪家好 儿童学编程比较好的
- 代码编程教学入门软件 代码编程教程