最近做了一个企业微信的应用项目,公司内部使用,需求员工在登录之后需要获取并显示该员工的职位等信息,故此记录一下。
/**
* 获取授权地址
*/
public function getUrl()
{
$redirect_uri = urlencode('应用链接地址');
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_privateinfo&agentid=" . $agentid . "&state=STATE#wechat_redirect";
$this->success('', $url);
}
/**
* 第三方登录
*
*/
public function third()
{
$code = $this->request->post('code');
$access_token = getAccessToken();
//获得用户信息
$url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$access_token&code=$code";
$ret = file_get_contents($url);
$ret = json_decode($ret, true);
if (isset($ret['user_ticket'])) {
//获取用户敏感信息
$url_ = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&userid=" . $ret['UserId'];
$res = Http::get($url_);
$res = json_decode($res, true);
//获取所有部门
$url1 = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=' . getAccessToken();
$row = Http::get($url1);
$row = json_decode($row, true);
// Log::error($row);
$department = [];
foreach ($row['department'] as $value) {
if (in_array($value['id'], $res['department'])) $department[] = $value['name'];
}
if ($res['errcode'] == 0) {
//判断用户是否注册
$user = db('user')->where('username', $res['userid'])->find();
if ($user) {
if ($user['status'] != 'normal') {
$this->error(__('Account is locked'));
}
db('user')->where('id', $user['id'])->update([
'nickname' => $res['name'],
'position' => $res['position'],
'department' => implode(',', $department),
]);
//如果已经有账号则直接登录
$ret = $this->auth->direct($user['id']);
} else {
$userid = $res['userid'];
$extend = [
'nickname' => $res['name'],
'position' => $res['position'],
'department' => implode(',', $department),
];
$ret = $this->auth->register($userid, Random::alnum(), '', '', $extend);
}
if ($ret) {
$data = ['userInfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
$this->error($res['errmsg']);
}
$this->error($ret['errmsg']);
}
if (!function_exists('getAccessToken')) {
/**
* 获取access_token
* @return mixed
*/
function getAccessToken()
{
$accessToken = \think\Cache::get('accessToken');
if (!$accessToken)
{
$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$corpID.'&corpsecret='.$corpsecret;
$data = \fast\Http::get($url);
$data = json_decode($data,true);
\think\Cache::set('accessToken',$data['access_token'],$data['expires_in']);
$accessToken = $data['access_token'];
}
return $accessToken;
}
}