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

获取微信OpenId

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

流程图如下

主要代码

页面js代码

/*写cookie*/ functionsetCookie(name,value){ varDays=30; varexp=newDate(); exp.setTime(exp.getTime()+Days*24*60*60*1000); document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString()+";path=/"; } /*读cookie*/ functiongetCookie(name){ vararr=document.cookie.match(newRegExp("(^|)"+name+"=([^;]*)(;|$)")); if(arr!=null){ returnunescape(arr[2]); } returnnull; } /*获取URL参数*/ functiongetUrlParams(name){ varreg=newRegExp("(^|&)"+name+"=([^&]*)(&|$)","i"); varr=window.location.search.substr(1).match(reg); if(r!=null){ returnunescape(r[2]); } returnnull; } /*获取openid*/ functiongetOpenId(url){ varopenid=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 protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp) throwsServletException,IOException{ Stringstate=req.getParameter("url"); //WxOpenIdServlet的地址 Stringredirect="http://"+Configure.SITE+"/wxopenid"; redirect=URLEncoder.encode(redirect,"utf-8"); StringBufferurl=newStringBuffer("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 protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp) throwsServletException,IOException{ Stringcode=req.getParameter("code"); Stringstate=req.getParameter("state"); Resultret=newResult(); AuthTokentoken=WXUtil.getAuthToken(code); if(null!=token.getOpenid()){ ret.setCode(0); log.info("====openid=="+token.getOpenid()); Map<String,String>map=newHashMap<String,String>(); map.put("openid",token.getOpenid()); map.put("state",state); ret.setData(map); }else{ ret.setCode(-1); ret.setMsg("登录错误"); } StringredUrl=state+"?openid="+token.getOpenid(); resp.sendRedirect(redUrl); }

获取AuthToken(WXUtil.getAuthToken(code))代码

publicstaticAuthTokengetAuthToken(Stringcode){ AuthTokenvo=null; try{ Stringuri="https://api.weixin.qq.com/sns/oauth2/access_token?"; StringBufferurl=newStringBuffer(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"); HttpURLConnectionconn=HttpClientUtil.CreatePostHttpConnection(url.toString()); InputStreaminput=null; if(conn.getResponseCode()==200){ input=conn.getInputStream(); }else{ input=conn.getErrorStream(); } vo=JSON.parseObject(newString(HttpClientUtil.readInputStream(input),"utf-8"),AuthToken.class); }catch(Exceptione){ log.error("getAuthTokenerror",e); } returnvo; }

HttpClientUtil类

packagecom.huatek.shebao.util; importjava.io.ByteArrayOutputStream; importjava.io.DataOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.net.HttpURLConnection; importjava.net.MalformedURLException; importjava.net.ProtocolException; importjava.net.URL; publicclassHttpClientUtil{ //设置body体 publicstaticvoidsetBodyParameter(Stringsb,HttpURLConnectionconn) throwsIOException{ DataOutputStreamout=newDataOutputStream(conn.getOutputStream()); out.writeBytes(sb); out.flush(); out.close(); } //添加签名header publicstaticHttpURLConnectionCreatePostHttpConnection(Stringuri)throwsMalformedURLException, IOException,ProtocolException{ URLurl=newURL(uri); HttpURLConnectionconn=(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"); returnconn; } publicstaticbyte[]readInputStream(InputStreaminStream)throwsException{ ByteArrayOutputStreamoutStream=newByteArrayOutputStream(); byte[]buffer=newbyte[1024]; intlen=0; while((len=inStream.read(buffer))!=-1){ outStream.write(buffer,0,len); } byte[]data=outStream.toByteArray(); outStream.close(); inStream.close(); returndata; } }

封装AuthToken的VO类

packagecom.huatek.shebao.wxpay; publicclassAuthToken{ privateStringaccess_token; privateLongexpires_in; privateStringrefresh_token; privateStringopenid; privateStringscope; privateStringunionid; privateLongerrcode; privateStringerrmsg; publicStringgetAccess_token(){ returnaccess_token; } publicvoidsetAccess_token(Stringaccess_token){ this.access_token=access_token; } publicLonggetExpires_in(){ returnexpires_in; } publicvoidsetExpires_in(Longexpires_in){ this.expires_in=expires_in; } publicStringgetRefresh_token(){ returnrefresh_token; } publicvoidsetRefresh_token(Stringrefresh_token){ this.refresh_token=refresh_token; } publicStringgetOpenid(){ returnopenid; } publicvoidsetOpenid(Stringopenid){ this.openid=openid; } publicStringgetScope(){ returnscope; } publicvoidsetScope(Stringscope){ this.scope=scope; } publicStringgetUnionid(){ returnunionid; } publicvoidsetUnionid(Stringunionid){ this.unionid=unionid; } publicLonggetErrcode(){ returnerrcode; } publicvoidsetErrcode(Longerrcode){ this.errcode=errcode; } publicStringgetErrmsg(){ returnerrmsg; } publicvoidsetErrmsg(Stringerrmsg){ this.errmsg=errmsg; } }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序系统教程[初级阶段],微信小程序0基础学起,讲解微信小程序开发的基础知识。微信小程序系统教程共有“微信小程序系统教程[初级阶段]”、“微信小程序系统教程[中级阶段]——核心技术”、“微信小程序系统教程[阶段]客服消息+微信支付+九宝电商系统”。“微信小程序系统教程[阶段]全套课程”包含:1.微信小程序系统教程[阶段]_客服消息2.微信小程序系统教程[阶段]_微信支付3.微信小程序系统教程[阶段]_九宝电商系统学习“微信小程序系统教程[阶段]”要求有微信小程序的基础。建议先学习“微信小程序系统教程[初级阶段]”、“微信小程序系统教程[中级阶段]”,后在报名“微信小程序系统教程[阶段]”。阶段讲解的客服消息,是针对小程序的。后台程序用接近底层的技术,没有使用三方技术。这样降低同学们学习成本。微信支付,这部分课程很有难度,要求同学们认真听讲,有不会的技术问题可以请教老师。购买课程后请联系老师,提供单号,给你源程序。九宝电商系统是一套十分适和学习、项目的课程。既可以系统的学习微信小程序相关知识,还可以修改后上线。“微信小程序系统教程[中级阶段]——核心技术”重点讲解微信小程序事件、组件、API微信小程序系统教程[初级阶段],微信小程序0基础学起,讲解微信小程序开发的基础知识。购买课程的同学,可赠送就九宝老师编写的《微信小程序开发宝典》。购课请咨询qq2326321088

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值