微信小程序 获取微信OpenId详解及实例代码


Posted in Javascript onOctober 31, 2016

获取微信OpenId

  1. 先获取code
  2. 再通过code获取authtoken,从authtoken中取出openid给前台
  3. 微信端一定不要忘记设定网页账号中的授权回调页面域名

流程图如下

微信小程序 获取微信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.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("登录错误");
  }
  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 {

  // 设置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;
  }
}

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! 

Javascript 相关文章推荐
Javascript下判断是否为闰年的Datetime包
Oct 26 Javascript
基于jquery的内容循环滚动小模块(仿新浪微博未登录首页滚动微博显示)
Mar 28 Javascript
javascript模拟实现C# String.format函数功能代码
Nov 25 Javascript
使用jquery组件qrcode生成二维码及应用指南
Feb 22 Javascript
jQuery之简单的表单验证实例
Jul 07 Javascript
微信小程序 Button 组件详解及简单实例
Jan 10 Javascript
用JavaScript实现让浏览器停止载入页面的方法
Jan 19 Javascript
JS正则表达式验证账号、手机号、电话和邮箱是否合法
Mar 08 Javascript
jQuery实现web页面樱花坠落的特效
Jun 01 jQuery
vue深入解析之render function code详解
Jul 18 Javascript
vue todo-list组件发布到npm上的方法
Apr 04 Javascript
Vue+iview+webpack ie浏览器兼容简单处理
Sep 20 Javascript
JavaScript事件用法浅析
Oct 31 #Javascript
js中通过getElementsByName访问name集合对象的方法
Oct 31 #Javascript
JavaScript递归操作实例浅析
Oct 31 #Javascript
在html中引入外部js文件,并调用带参函数的方法
Oct 31 #Javascript
Validform表单验证总结篇
Oct 31 #Javascript
Javascript数组中push方法用法分析
Oct 31 #Javascript
JavaScript中的await/async的作用和用法
Oct 31 #Javascript
You might like
在同一窗体中使用PHP来处理多个提交任务
2008/05/08 PHP
php重定向的三种方法分享
2012/02/22 PHP
thinkphp中字符截取函数msubstr()用法分析
2016/01/09 PHP
Docker搭建自己的PHP开发环境
2018/02/24 PHP
简单的php购物车代码
2020/06/05 PHP
Aster vs Newbee BO5 第二场2.19
2021/03/10 DOTA
超强的IE背景图片闪烁(抖动)的解决办法
2007/09/09 Javascript
javascript offsetX与layerX区别
2010/03/12 Javascript
javascript学习笔记(九) js对象 设计模式
2012/06/19 Javascript
js实现类似菜单风格的TAB选项卡效果代码
2015/08/28 Javascript
javascript实现无法关闭的弹框
2016/11/27 Javascript
VUE+Element UI实现简单的表格行内编辑效果的示例的代码
2018/10/31 Javascript
Vue混入mixins滚动触底的方法
2019/11/22 Javascript
jquery 插件重新绑定的处理方法分析
2019/11/23 jQuery
TypeScript之调用栈的实现
2019/12/31 Javascript
vue 根据选择的月份动态展示日期对应的星期几
2021/02/06 Vue.js
[00:59]DOTA2英雄背景故事——上古巨神
2020/06/28 DOTA
Python实现各种排序算法的代码示例总结
2015/12/11 Python
requests和lxml实现爬虫的方法
2017/06/11 Python
基于使用paramiko执行远程linux主机命令(详解)
2017/10/16 Python
python中将zip压缩包转为gz.tar的方法
2018/10/18 Python
python实现n个数中选出m个数的方法
2018/11/13 Python
python 获取utc时间转化为本地时间的方法
2018/12/31 Python
Django如何使用第三方服务发送电子邮件
2019/08/14 Python
python实现超市商品销售管理系统
2019/11/22 Python
Python numpy.zero() 初始化矩阵实例
2019/11/27 Python
python关闭占用端口方式
2019/12/17 Python
Python2和Python3中@abstractmethod使用方法
2020/02/04 Python
Python3 ID3决策树判断申请贷款是否成功的实现代码
2020/05/21 Python
韩国三星集团旗下时尚品牌官网:SSF SHOP
2016/08/02 全球购物
优秀中专生推荐信
2013/11/17 职场文书
财务人员求职自荐书范文
2014/02/10 职场文书
青安岗事迹材料
2014/05/14 职场文书
民族团结好少年事迹材料
2014/08/19 职场文书
护士个人总结范文
2015/02/13 职场文书
vue中data里面的数据相互使用方式
2022/06/05 Vue.js