您的位置:首页 > 移动开发 > 微信开发

java开发微信端获取code和opendId,access_token,用户列表

2017-12-11 22:26 651 查看
第一步:页面授权获取code,去你的微信公众平台配置就行
https://open.weixin.qq.com/connect/oauth2/authorize?appid=Appid&redirect_uri=http://xxx/xxx/xxx.html&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect
(1)appid是你微信公众平台里面->基本配置-->公众号开发信息的AppID

(2)redirect_uri后面是你要跳转的页面,例如:某域名/page/index.html

(3)其他参数按照我这个写,或者去看开发文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
(4)然后页面授权完毕后,自动跳转到你指定的页面,在页面的地址信息中有你的code信息,可以在js用var url=location.href;   alert(url)来检查你的code,然后把code值截取下来

第二步:发起ajax请求,把code传到后台,java后台访问   https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=AppSecret&code=CODE&grant_type=authorization_code 地址

(1)参数appid,是你微信公众平台上-->基本配置-->公众号开发信息的AppID

(2)参数secret,是你微信公众平台上-->基本配置-->公众号开发信息的开发着密码(AppSecret)

(3)参数code是你第一步传过来的获取到code,通过ajax传递过来的

(4)参数grant_type,初学者可以看,微信公众平台开发文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839  详细了解这个参数

java后台代码

@Controller

@RequestMapping("/login/api")

public class LoginControllerApi {

private final static String appid = "";//自己的配置appid

private final static String appsecret = "";//自己的配置APPSECRET;

@Autowired

private UserService userService;

@RequestMapping("/login")

@ResponseBody

public User login(User user){

//保存用户的方法

User user2=this.userService.userLoginCheck(user);

return user2;

}

@ResponseBody

@RequestMapping("/openId")

public void postJsonData(String code,HttpServletResponse response2,HttpSession session) throws IOException {

String requestUrl ="https://api.weixin.qq.com/sns/oauth2/access_token";

CloseableHttpClient httpclient = LoginControllerApi.createDefault();

HttpPost httppost=new HttpPost(requestUrl);

List<NameValuePair> formparams = new ArrayList<NameValuePair>();

formparams.add(new BasicNameValuePair("appid", appid));

formparams.add(new BasicNameValuePair("secret", appsecret));

formparams.add(new BasicNameValuePair("code", code));

formparams.add(new BasicNameValuePair("grant_type", "authorization_code"));

CloseableHttpResponse response=null;

try {

httppost.setEntity(new UrlEncodedFormEntity(formparams));

response = httpclient.execute(httppost);

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

JSONObject jsonObject=null;

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

HttpEntity httpEntity = response.getEntity();

String result=null;

try {

result = EntityUtils.toString(httpEntity);

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}// 返回json格式:

jsonObject = JSONObject.fromObject(result);

}

//获取到opendId后,通过opendId获取用户信息

String access_token=jsonObject.getString("access_token");

String opendId=jsonObject.getString("openid");

//调用方法获取微信端信息,自己本类中的方法

JSONObject jsonObject1=LoginControllerApi.getUserInfo(access_token, opendId);

User user=new User();

user.setUserOpenId(opendId);

user.setUserImg(jsonObject1.getString("headimgurl"));

//把微信默认的字符编码ISO-8859-1转化成utf-8;

byte[] bytes=jsonObject1.getString("nickname").getBytes("ISO-8859-1");

String name=new String(bytes,"utf-8");

user.setUserName(name);

//查询用户的方法

User user2=this.login(user);

//放入数据

Map<String,Object> map=new HashMap<String,Object>();

map.put("user", user2);

map.put("user2", user);

Gson gson=new Gson();

String data=gson.toJson(map);

//设置返回的字符编码

response2.setContentType("text/html;charset=utf-8");

//返回的数据

response2.getWriter().print(data);

//这个返回的是获取到的信息

//response2.getWriter().print(jsonObject1.toString());

}

//获取微信端用户信息

public static JSONObject getUserInfo(String access_token,String opendId){

String requestUrl ="https://api.weixin.qq.com/sns/userinfo?"+

"access_token="+access_token+"&openid="+opendId+"&lang=zh_CN";

CloseableHttpClient httpclient = LoginControllerApi.createDefault();

HttpGet httpget=new HttpGet(requestUrl);

CloseableHttpResponse response=null;

try {

response = httpclient.execute(httpget);

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

JSONObject jsonObject=null;

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

HttpEntity httpEntity = response.getEntity();

String result=null;

try {

result = EntityUtils.toString(httpEntity);

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}// 返回json格式:

jsonObject = JSONObject.fromObject(result);

}

//String data=jsonObject.toString();

return jsonObject;

}

public static CloseableHttpClient createDefault() {

return HttpClientBuilder.create().build();

}

}

//注:参数是我定义好了的

第三步:处理完毕后,后台response2.getWriter().print(jsonObject.toString());这个会返回你发起ajax请求的页面,并在你的successl里面返回你的值,

.... //ajax请求地址什么的省略了,本人用的是jq发起的ajax请求,

.....

datatype:json,

success:function(data){

//把返回的json字符串转化成字符输出

alert(JSON.stringify(data));

}

四:注意的细节,微信给你返回的是ios-8859-1这种格式的编码,所以如果你通过后台取值保存数据库的时候,一定要把存的可能是中文的值,转化成你的数据库编码格式,一般都是转化成utf-8

9500
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信 access java