微信小程序 获取微信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 相关文章推荐
html的DOM中document对象images集合用法实例
Jan 21 Javascript
JS根据key值获取URL中的参数值及把URL的参数转换成json对象
Aug 26 Javascript
AngularJS 依赖注入详解及示例代码
Aug 17 Javascript
jQuery EasyUI编辑DataGrid用combobox实现多级联动
Aug 29 Javascript
JavaScript实现垂直向上无缝滚动特效代码
Nov 23 Javascript
AngularJS实现路由实例
Feb 12 Javascript
浅谈js中用$(#ID)来作为选择器的问题(id重复的时候)
Feb 14 Javascript
javascript自定义事件功能与用法实例分析
Nov 08 Javascript
vue-cli3搭建项目的详细步骤
Dec 05 Javascript
layui清空,重置表单数据的实例
Sep 12 Javascript
微信小程序开发中var that =this的用法详解
Jan 18 Javascript
如何在node环境实现“get数据解析”代码实例
Jul 03 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
关于我转生变成史莱姆这档事:第二季PV上线,萌王2021年回归
2020/05/06 日漫
一个PHP缓存类代码(附详细说明)
2011/06/09 PHP
PHP函数getenv简介和使用实例
2014/05/12 PHP
ThinkPHP3.1.3版本新特性概述
2014/06/19 PHP
PHP多文件上传类实例
2015/03/07 PHP
如何实现iframe(嵌入式帧)的自适应高度
2006/07/26 Javascript
用javascript获取当页面上鼠标光标位置和触发事件的对象的代码
2009/12/09 Javascript
jQuery.holdReady()使用方法
2014/05/20 Javascript
基于BootstrapValidator的Form表单验证(24)
2016/12/12 Javascript
ES6中Proxy与Reflect实现重载(overload)的方法
2017/03/30 Javascript
React Native中Navigator的使用方法示例
2017/10/13 Javascript
webpack构建换肤功能的思路详解
2017/11/27 Javascript
基于vue2实现上拉加载功能
2017/11/28 Javascript
vue采用EventBus实现跨组件通信及注意事项小结
2018/06/14 Javascript
Vue头像处理方案小结
2018/07/26 Javascript
JavaScript基础教程之如何实现一个简单的promise
2018/09/11 Javascript
基于mpvue的简单弹窗组件mptoast使用详解
2019/08/02 Javascript
javascript设计模式 ? 访问者模式原理与用法实例分析
2020/04/26 Javascript
[02:33]2014DOTA2 TI每日综述 LGD涉险晋级DK闯入胜者组
2014/07/14 DOTA
python实现巡检系统(solaris)示例
2014/04/02 Python
Python3基础之条件与循环控制实例解析
2014/08/13 Python
使用Python中的线程进行网络编程的入门教程
2015/04/15 Python
Python win32com 操作Exce的l简单方法(必看)
2017/05/25 Python
Python实现变量数值交换及判断数组是否含有某个元素的方法
2017/09/18 Python
EM算法的python实现的方法步骤
2018/01/02 Python
HTML5学习心得总结(推荐)
2016/07/08 HTML / CSS
娇韵诗Clarins意大利官方网站:法国天然护肤品牌
2020/03/11 全球购物
省文明单位申报材料
2014/05/08 职场文书
音乐学专业求职信
2014/07/22 职场文书
“四风”问题对照检查材料思想汇报
2014/09/16 职场文书
2014年维修电工工作总结
2014/11/20 职场文书
酒会开场白大全
2015/06/01 职场文书
2016年社区“6.26”禁毒日宣传活动总结
2016/04/05 职场文书
MySQL表的增删改查(基础)
2021/04/05 MySQL
MySQL 不等于的三种使用及区别
2021/06/03 MySQL
Python中使用Opencv开发停车位计数器功能
2022/04/04 Python