1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 微信授权获取基本信息java_Java微信网页授权授权获取用户基本信息

微信授权获取基本信息java_Java微信网页授权授权获取用户基本信息

时间:2022-05-14 20:19:31

相关推荐

微信授权获取基本信息java_Java微信网页授权授权获取用户基本信息

微信测试号申请地址:http://mp./debug/cgi-bin/sandbox?t=sandbox/login;

微信公众平台开发者文档地址:https://mp./wiki/home/index.html;

网页授权获取用户基本信息

具体步骤:

if(openId == null || openId.equals("")){

//get userInfo

//第一步:用户同意授权,获取code

String code = (String)request.getParameter("code");

System.out.println("code:"+code);

if(null == code || code.equals("")){

String GetCodeRequest = WxConfig.WEIXIN_OPENID_URL;

String result = null;

String uri = basePath + "lottery/toLottery.action?lottery.id=" + this.lottery.getId();

System.out.println("rui:"+uri);

if(flag == null){

flag="game";

}

try{

GetCodeRequest = GetCodeRequest.replace("APPID", URLEncoder.encode(serviceConf.getAppId(),"UTF-8"));

GetCodeRequest = GetCodeRequest.replace("REDIRECT_URI",URLEncoder.encode(uri,"UTF-8"));

GetCodeRequest = GetCodeRequest.replace("SCOPE", URLEncoder.encode(WxConfig.WEIXIN_SCOPE,"UTF-8"));

GetCodeRequest = GetCodeRequest.replace("STATE", URLEncoder.encode(flag,"UTF-8"));

result = GetCodeRequest;

System.out.println("result:"+result);

request.setAttribute("result", result);

return "getOpenId";

}catch(Exception e){

e.printStackTrace();

logger.error("get code error"+e);

}

}else{

openId = WxConfig.getOpenId(code,serviceConf.getAppId(),serviceConf.getAppSecret());

request.getSession().setAttribute("openId", openId);

logger.info("get openId:"+openId);

}WxConfig.java代码

public final static String WEIXIN_OPENID_URL ="https://open./connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

//根据access_token获取openid

public final static String WEIXIN_ACCESS_TOKEN_OPENID_URL ="/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

//获取用户标识openid

public static String getOpenId(String code,String appId,String appSecret){

String GetOpenidRequest = HttpUtil.WEIXIN_HOST_API +WEIXIN_ACCESS_TOKEN_OPENID_URL;

logger.info("getOpenId微信提交路径:"+GetOpenidRequest);

GetOpenidRequest = GetOpenidRequest.replace("APPID", appId);

GetOpenidRequest = GetOpenidRequest.replace("SECRET", appSecret);

GetOpenidRequest = GetOpenidRequest.replace("CODE", code);

logger.info("getOpenId微信提交路径:"+WEIXIN_ACCESS_TOKEN_OPENID_URL);

JSONObject json = JSONObject.fromObject(HttpUtil.get(GetOpenidRequest));

System.out.println(json);

String openid;

try{

logger.info("获取openid--getOpenId()");

openid = json.getString("openid");

String accessToken = json.getString("access_token");

logger.info("微信获取到的用户标识openid:"+openid+";access_token:"+accessToken);

return openid;

}catch (JSONException e) {

openid = null;

// 获取openid失败

e.printStackTrace();

logger.error("获取token失败 errcode:{}:"+json.getInt("errcode")+"errmsg:{}:"+json.getString("errmsg"));

}

return openid;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。