GZHUtil
import com.alibaba.fastjson.JSONObject;
import com.whyrkj.jeepWedding.config.excetion.ServiceException;
import com.whyrkj.jeepWedding.config.global.Mark;
import java.io.IOException;
import java.util.Map;
public class GZHUtil {
/**
* 公众号获取 AccessToken
*/
public static String getAccessToken(String appId,String appSercret) throws IOException {
HttpUtil httpUtil = new HttpUtil();
String url = "https://api.weixin.qq.com/cgi-bin/token";
String result = httpUtil.header("X-Requested-With", "XMLHttpRequest")
.data("appid", appId)
.data("secret", appSercret)
.data("grant_type", Mark.TOKEN_GRANT_TYPE)
.url(url)
.get();
Map<String, Object> map = JSONObject.parseObject(result, Map.class);
if (!map.containsKey("access_token")) {
throw new ServiceException("错误信息:" + map.get("errmsg"));
}
return (String)map.get("access_token");
}
/**
* 公众号菜单链接 根据code 获取用户的openId
* @param code
* @return
*/
public static String gzhGetOpenIdByCode(String code,String appId,String appSecret){
/**
* 根据code 获取openId
*/
HttpUtil httpUtil = new HttpUtil();
String url = Mark.WX_TOKEN_URL;
String result = null;
try {
result = httpUtil.header("X-Requested-With", "XMLHttpRequest")
.data("appid", appId)
.data("secret", appSecret)
.data("code", code)
.data("grant_type", Mark.WX_GRANT_TYPE)
.url(url)
.get();
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object> map = JSONObject.parseObject(result, Map.class);
if (!map.containsKey("openid")) {
throw new ServiceException("错误信息:" + map.get("errmsg"));
}
String openId = (String) map.get("openid");
System.out.println("openId========="+openId);
return openId;
}
}