微信支付后台获取openid
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信支付后台获取openid相关的知识,希望对你有一定的参考价值。
@RequestMapping(value = "/postOpenid", method = RequestMethod.POST)
@ResponseBody
public String getOpenid(@RequestParam(value = "code", required = false) String code, HttpServletRequest request,
ModelMap model) throws IOException {
System.out.println("code:" + code);
String openid = "";
List<Object> list = accessToken(code);
if (list.size() != 0) {
openid = list.get(0).toString();
}
return openid;
}
public List<Object> accessToken(String code) throws IOException {
List<Object> list = new ArrayList<Object>();
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + " " + "&secret="
+ " " + "&code=" + code + "&grant_type=authorization_code";
GetMethod get = null;
get = new GetMethod(url);
HttpClient client = new HttpClient();
client.getParams().setParameter("http.protocol.content-charset", "utf-8");
client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
client.getHttpConnectionManager().getParams().setSoTimeout(30000);
get.addRequestHeader("Content-type", "te|xt/html;charset=UTF-8");
int statusCode = 0;
try {
statusCode = client.executeMethod(get);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (statusCode == 200) {
InputStream resInputStream = null;
try {
resInputStream = get.getResponseBodyAsStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resInputStream, "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line:" + line);
JSONObject jsonObject = new JSONObject();
try {
jsonObject = JSONObject.fromObject(line);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
System.out.println("openid:" + openid);
list.add(openid);
list.add(access_token);
} catch (Exception e) {
jsonObject = JSONObject.fromObject(line);
String errcode = jsonObject.getString("errcode");
System.out.println("errcode:" + errcode);
}
}
}
return list;
}
以上是关于微信支付后台获取openid的主要内容,如果未能解决你的问题,请参考以下文章