---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
1、处理页面链接,使后台能获得微信提供的code
对我们自己的链接进行urlencode处理,处理方法
var changeurl=getUrl.replace(/[:]/g,"%3a").replace(/[/]/g,"%2f").replace(/[\?]/g,"%3f").replace(/[=]/g,"%3d").replace(/[&]/g,"%26");
var tourl="https://open.weixin.qq.com/connect/oauth2/authorize?appid=自己的appid&redirect_uri="+changeurl+"&response_type=code&scope=snsapi_base&state=location#wechat_redirect";
企业获取code
企业如果需要员工在跳转到企业网页时带上员工的身份信息,需构造如下的链接:
- 参数说明
参数 | 必须 | 说明 |
---|---|---|
appid | 是 | 企业的CorpID |
redirect_uri | 是 | 授权后重定向的回调链接地址,请使用urlencode对链接进行处理 |
response_type | 是 | 返回类型,此时固定为:code |
scope | 是 | 应用授权作用域,此时固定为:snsapi_base |
state | 否 | 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值,长度不可超过128个字节 |
#wechat_redirect | 是 | 微信终端使用此参数判断是否需要带上身份信息 |
员工点击后,页面将跳转至 redirect_uri?code=CODE&state=STATE,企业可根据code参数获得员工的userid。
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
2、后台根据code获得获得uesid
/**
* 根据code获得人员
*/
public String getUserIdByCode(String code){
//获取微信号
String token=getTokenFromWx();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+token+"&code="+code+"&agentid="+AGENT_ID_REGISTER);
// Create a custom response handler
ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
public JSONObject handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
if(null!=entity){
String result= EntityUtils.toString(entity);
//根据字符串生成JSON对象
JSONObject resultObj = JSONObject.fromObject(result);
return resultObj;
}else{
return null;
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
//返回的json对象
JSONObject responseBody = httpclient.execute(httpPost, responseHandler);
//AppLogUtil.getAppLoger().info(responseBody.toString());
if(null==responseBody.getString("UserId")){
return null;
}else{
return responseBody.getString("UserId");
}
}catch (Exception e) {
//e.printStackTrace();
return null;
}
}
官网API: http://qydev.weixin.qq.com/wiki/index.php?title=OAuth验证接口