微信小程序 获取微信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 应用类库代码
Jun 02 Javascript
网页和浏览器兼容性问题汇总(draft1)
Jun 01 Javascript
Ext.get() 和 Ext.query()组合使用实现最灵活的取元素方式
Sep 26 Javascript
调用DOM对象的focus使文本框获得焦点
Feb 19 Javascript
基于javascript的JSON格式页面展示美化方法
Jul 02 Javascript
AngularJS 中的事件详解
Jul 28 Javascript
js下拉菜单生成器dropMenu使用方法详解
Aug 01 Javascript
纯js实现隔行变色效果
Nov 29 Javascript
微信小程序性能优化之checkSession的使用
Mar 06 Javascript
你可能不知道的CORS跨域资源共享
Mar 13 Javascript
JS字符串补全方法padStart()和padEnd()
May 27 Javascript
ant design charts 获取后端接口数据展示
May 25 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+SqlServer实现分页显示
2006/10/09 PHP
第六节--访问属性和方法
2006/11/16 PHP
php反弹shell实现代码
2009/04/22 PHP
PHP CLI模式下的多进程应用分析
2013/06/03 PHP
关于zend studio 出现乱码问题的总结
2013/06/23 PHP
JavaScript是否可实现多线程  深入理解JavaScript定时机制
2009/12/22 Javascript
jquery 单引号和双引号的区别及使用注意
2013/07/31 Javascript
jquery中focus()函数实现当对象获得焦点后自动把光标移到内容最后
2013/09/29 Javascript
如何从jQuery的ajax请求中删除X-Requested-With
2013/12/11 Javascript
javascript面向对象程序设计(一)
2015/01/29 Javascript
JS实现超精简响应鼠标显示二级菜单代码
2015/09/12 Javascript
基于jQuery Circlr插件实现产品图片360度旋转
2015/09/20 Javascript
ionic js 模型 $ionicModal 可以遮住用户主界面的内容框
2016/06/06 Javascript
js select实现省市区联动选择
2020/04/17 Javascript
作为老司机使用 React 总结的 11 个经验教训
2017/04/08 Javascript
微信小程序页面开发注意事项整理
2017/05/18 Javascript
基于Bootstrap下拉框插件bootstrap-select使用方法详解
2018/08/07 Javascript
使用rollup打包JS的方法步骤
2018/12/05 Javascript
layui-tree实现Ajax异步请求后动态添加节点的方法
2019/09/23 Javascript
ESLint 是如何检查 .vue 文件的
2020/11/30 Vue.js
Python中random模块生成随机数详解
2016/03/10 Python
python3大文件解压和基本操作
2017/12/15 Python
儿童python练习实例
2018/05/27 Python
实践Vim配置python开发环境
2018/07/02 Python
python 使用 requests 模块发送http请求 的方法
2018/12/09 Python
对python中的try、except、finally 执行顺序详解
2019/02/18 Python
python实现图像拼接
2020/03/05 Python
python中数字是否为可变类型
2020/07/08 Python
python UDF 实现对csv批量md5加密操作
2021/01/01 Python
美国美发品牌:Bumble and Bumble
2016/10/08 全球购物
自荐信格式
2013/12/01 职场文书
学生保证书范文
2014/04/28 职场文书
小学清明节活动总结
2014/07/04 职场文书
颂军魂爱军营演讲稿
2014/09/13 职场文书
个人德育工作总结
2015/03/05 职场文书
ubuntu20.04虚拟机无法上网的问题及解决
2022/12/24 Servers