微信公众号获取用户openid有两种方式 一种需要用户授权获取的用户数据相对较多,如用户名称、头像等,还有一种无需授权获取直接上代码 ,
获取用户openid首先要获取code,然后将code作为参数调用微信api获取openid代码如下,
package com.manage.spring.GetOpendiddemo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.wx.consts.WxConfig;
@Controller
public class GetOpendiddemo {
@RequestMapping(value = "getCode")
public void getOpenId(HttpServletResponse response, Model model)
throws IOException {
//先获取code
String url = getOpenIdUrl();
//得到的code传入获取openid参数
response.sendRedirect(url);
}
//获取code
public static String getOpenIdUrl() throws ClientProtocolException,
UnsupportedEncodingException {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//appid
String appid = WxConfig.APPID;
String REDIRECT_URI = "https://XXXX/XXX";// 你的回调页
//参数utf-8
url = url.replace("APPID", java.net.URLEncoder.encode(appid, "utf-8"));
url = url.replace("REDIRECT_URI",java.net.URLEncoder.encode(REDIRECT_URI, "utf-8"));
return url;
}
//获取openid
@RequestMapping({ "getOpendid" })
@ResponseBody
public static String getopendid(String code,Model model) throws ClientProtocolException, IOException, JSONException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
url = url.replace("AppId", WxConfig.APPID).replace("AppSecret", WxConfig.APPSECRET).replace("CODE", code);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
com.alibaba.fastjson.JSONObject jsonTexts = JSON.parseObject(jsonStr);
String openid = "";
if (jsonTexts.get("openid") != null) {
openid = jsonTexts.get("openid").toString();
}
return openid;
}
}
需要注意的是回调页面的域名须在微信公众号进行授权 :