获取企业微信用户信息
### 1. 前端部分,要运行在微信端 [管理地址:https://work.weixin.qq.com/](https://work.weixin.qq.com/)
``` js
const code = this.getQueryStringByName(window.location.href,'code')
if(code){
const url = `${this.path}/users/info?code=${code}`
const userInfo = await fetch(url)
console.log(userInfo)
}
else
{
//企业的CorpID
const CORPID = 'wxxxxxxxxx'
//企业应用的id
const AGENTID = '8888'
// 回调地址,其中 abc.com.cn 这个域必须要被验证
const REDIRECT_URI = encodeURIComponent('http://abc.com.cn/page')
const SCOPE = 'snsapi_userinfo'
const STATE = '1'//不必须
const url1 = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${CORPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&agentid=${AGENTID}&state=${STATE}#wechat_redirect`
window.location.href = url1
}
```
### 2. 后端部分
``` js
const fetch = require('node-fetch')
//企业的CorpID
const CORPID = 'wx11111111111‘
//企业应用的SECRECT
const SECRECT = 'xxxxxx‘//可以变更
let ACCESS_TOKEN = null;
/**
* 获取access_token
* https://work.weixin.qq.com/api/doc#10013/%E7%AC%AC%E4%B8%89%E6%AD%A5%EF%BC%9A%E8%8E%B7%E5%8F%96access_token
*/
const getAccessToken = async ()=>{
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${CORPID}&corpsecret=${SECRECT}`
const res = await fetch(url)
return await res.json()
}
const getBaseUserInfo = async (code,_access_token)=>{
let access_token = null
if(!_access_token) {
data = await getAccessToken()
access_token = data.access_token
console.log('getAccessToken')
console.log(data)
}
else
access_token = _access_token
ACCESS_TOKEN = access_token
const url2 = `https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=${ACCESS_TOKEN}&code=${code}`
const res2 = await fetch(url2,{
method:'POST'
})
return await res2.json()
}
module.exports.getDetaileUserInfo = async (code,access_token)=>{
const {user_ticket,UserId} = await getBaseUserInfo(code,access_token)
const url3 = `https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=${ACCESS_TOKEN}&userid=${UserId}`
const res3 = await fetch(url3)
const data = await res3.json();
console.log(data)
return Object.assign(data,{access_token:ACCESS_TOKEN})
}
```