怎么h5获取微信用户openid的openid

The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.浏览(3846)
微信小程序要怎样获取微信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]);
/* 获取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]);
/* 获取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=& +
setCookie(&usropenid&, openid);
WxCodeServlet代码
//访问微信获取code
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./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
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);
(&====openid==&+token.getOpenid());
Map&String,String& map = new HashMap&String,String&();
map.put(&openid&, token.getOpenid());
map.put(&state&, state);
ret.setData(map);
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 =
String uri = &https://api./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 =
if (conn.getResponseCode() == 200) {
input = conn.getInputStream();
input = conn.getErrorStream();
vo = JSON.parseObject(new String(HttpClientUtil.readInputStream(input),&utf-8&),AuthToken.class);
} catch (Exception e) {
log.error(&getAuthToken error&, e);
HttpClientUtil类
package com.huatek.shebao.
import java.io.ByteArrayOutputS
import java.io.DataOutputS
import java.io.IOE
import java.io.InputS
import java.net.HttpURLC
import java.net.MalformedURLE
import java.net.ProtocolE
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&);
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();
封装AuthToken的VO类
package com.huatek.shebao.
public class AuthToken {
private String access_
private Long expires_
private String refresh_
public String getAccess_token() {
return access_
public void setAccess_token(String access_token) {
this.access_token = access_
public Long getExpires_in() {
return expires_
public void setExpires_in(Long expires_in) {
this.expires_in = expires_
public String getRefresh_token() {
return refresh_
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_
public String getOpenid() {
public void setOpenid(String openid) {
this.openid =
public String getScope() {
public void setScope(String scope) {
this.scope =
public String getUnionid() {
public void setUnionid(String unionid) {
this.unionid =
public Long getErrcode() {
public void setErrcode(Long errcode) {
this.errcode =
public String getErrmsg() {
public void setErrmsg(String errmsg) {
this.errmsg =
更多关于微信小程序可以查看
千篇一律的复制粘贴,你们回答问题能不能过过脑子。
广告等垃圾信息
不友善内容
违反法律法规的内容
不宜公开讨论的政治内容
微信号:w3cschoolcn
意见反馈:
联系方式:如何获取微信用户openid? - 知乎92被浏览98951分享邀请回答 &xml&
&ToUserName&&![CDATA[toUser]]&&/ToUserName&
&FromUserName&&![CDATA[fromUser]]&&/FromUserName&
&CreateTime&&/CreateTime&
&MsgType&&![CDATA1]&&/MsgType&
&Content&&![CDATA[this is a test]]&&/Content&
&MsgId&3456&/MsgId&
“FromUserName”标签中的内容即为该用户的OpenID我没它们那么贪,我只要100赞= =|||567 条评论分享收藏感谢收起279 条评论分享收藏感谢收起查看更多回答2 个回答被折叠()The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.

我要回帖

更多关于 h5获取微信用户openid 的文章

 

随机推荐