1.创建Index.php文件
<?php
include_once('Tools.php');
include_once('GetWxUser.php');
// 载入配置文件
$config = require('Config.php');
// 配置信息
$appId = $config['appId'] ?? '';
$appSecret = $config['appSecret'] ?? '';
$agentId = $config['agentId'] ?? '';
$ssoSecretKey = $config['ssoSecretKey'] ?? '';
$toDomain = $config['toDomain'] ?? '';
$debug = $config['debug'] ?? '';
// 获取token
$tokenData = file_get_contents('./wechat_token.txt');
if (!empty($tokenData)) {
$tokenData = json_decode($tokenData, true);
}
$time = time() - $tokenData['time'];
if ($time > 3600) {
$tokenRes = Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$appId}&corpsecret={$appSecret}");
$tokenRes = json_decode($tokenRes, true);
$token = $tokenRes['access_token'];
$data = array(
'time' => time(),
'token' => $token
);
$res = file_put_contents('./wechat_token.txt', json_encode($data));
if ($res) {
echo '更新 token 成功';
}
} else {
$token = $tokenData['token'];
}
// 获取ticket
$ticketData = file_get_contents('./wechat_ticket.txt');
if (!empty($ticketData)) {
$ticketData = json_decode($ticketData, true);
}
$time = time() - $ticketData['time'];
if ($time > 3600) {
// 如果是企业号用以下 URL 获取 ticket
$ticketRes = Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={$token}");
$ticketRes = json_decode($ticketRes, true);
$ticket = $ticketRes['ticket'];
$data = array(
'time' => time(),
'ticket' => $ticket
);
$res = file_put_contents('./wechat_ticket.txt', json_encode($data));
if ($res) {
echo '更新 ticket 成功';
}
} else {
$ticket = $ticketData['ticket'];
}
// 进行sha1签名
$timestamp = time();
$nonceStr = Tools::createNonceStr();
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$shaStr = sha1($str);
//获取用户信息
$obj = new GetWxUser($appId, $appSecret, $agentId);
$userInfo = $obj->getUserInfo();
$email = $userInfo['email'] ?? '';
$token = md5($ssoSecretKey . $email . date('Y-m-d', time()));
$url = $toDomain . "/simple_sso/?user={$email}&token={$token}&next=/";// 单点登录跳转链接
?>
<html>
<head>
<title>已授权登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<div style="text-align: center;margin-top: 30%;">
<img src="./image.png" alt="" style="margin-bottom: 20%">
<h2>已经在外部浏览器打开该页面33</h2>
</div>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
function init() {
var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
//PC端企业微信
if (isComWx && !isMobile) {
// 初始化内容
wx.config({
beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
debug: '<?= $debug ?>', // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '<?= $appId ?>', // 必填,公众号的唯一标识
timestamp: '<?= $timestamp ?>', // 必填,生成签名的时间戳
nonceStr: '<?= $nonceStr ?>', // 必填,生成签名的随机串
signature: '<?= $shaStr ?>',// 必填,签名
jsApiList: ['openDefaultBrowser'] // 必填,需要使用的JS接口列表 openDefaultBrowser只有在真机中才能用(坑)
});
wx.ready(function () {
//openDefaultBrowser只有在真机中才能用(坑)
wx.invoke('openDefaultBrowser', {
'url': '<?= $url ?>'
}, function (res) {
if (res.errMsg == "openDefaultBrowser:ok") {
wx.closeWindow();
window.close();
}
});
});
wx.error(function (res) {
console.log(res)
});
} else {
//重定向
window.location.href = '<?= $toDomain ?>' + '/dtable/';
}
}
init();
</script>
</body>
</html>
2.获取企业用户信息 GetWxUser.php
<?php
include_once('Tools.php');
/**
* 获取企业微信用户信息
* OAuth2.0
*/
class GetWxUser
{
private $appId;
private $appSecret;
private $agentId;
public function __construct($appId, $appSecret, $agentId)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
$this->agentId = $agentId;
}
/**
* 1、获取微信用户信息,判断有没有code,有使用code换取access_token,没有去获取code。
* @return array 微信用户信息数组
*/
public function getUserInfo()
{
if (!isset($_GET['code'])) {//没有code,去微信接口获取code码
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //微信服务器回调url,这里是本页url
$this->getCode($callback);
} else {
// 获取code后跳转回来到这里了
$code = $_GET['code'];
$accessToken = $this->getAccessToken();
$userTicket = $this->getUserTicketUseCode($accessToken, $code);
$userId = $userTicket['UserId'] ?? '';
return $this->getUserInfoUseUid($accessToken, $userId); //获取微信用户信息 /静默授权 getUserInfoUseUid
// return $this->getUserInfoUseTicket($accessToken,$userTicket['user_ticket'] ?? ''); //获取微信用户信息 snsapi_privateinfo:手动授权
}
}
/**
* 用户授权并获取code
* @param string $callback 微信服务器回调链接url
*/
private function getCode($callback = '')
{
$appId = $this->appId;
$agentId = $this->agentId;
$scope = 'snsapi_userinfo'; //静默授权 getUserInfoUseUid | snsapi_privateinfo:手动授权 getUserInfoUseTicket
$state = md5(uniqid(rand(), true)); //唯一ID标识符绝对不会重复
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appId . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&agentid=' . $agentId . '&state=' . $state . '#wechat_redirect';
header("Location:$url");
}
/**
* 获取token
*
* @return mixed
*/
private function getAccessToken()
{
$tokenData = file_get_contents('./wechat_token.txt');
if (!empty($tokenData)) {
$tokenData = json_decode($tokenData, true);
}
$time = time() - $tokenData['time'];
if ($time > 3600) {
$appId = $this->appId;
$appSecret = $this->appSecret;
$res = \Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$appId}&corpsecret={$appSecret}");
if (isset($res->errcode)) {
echo 'error:' . $res->errcode . '<hr>msg :' . $res->errmsg;
exit;
}
$res = json_decode($res, true);
$token = $res['access_token'] ?? '';
if (!$token) {
echo 'token Error';
exit;
}
$data = [
'time' => time(),
'token' => $token,
];
$res = file_put_contents('./wechat_token.txt', json_encode($data));
if ($res) {
echo '更新 token 成功';
}
} else {
$token = $tokenData['token'];
}
return $token;
}
/**
* 4、使用access_token获取用户信息
* @param string access_token
* @param string 用户的openid
* @return array 用户信息数组
*/
private function getUserTicketUseCode($accessToken, $code)
{
$res = \Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$accessToken}&code={$code}");
if (isset($res->errcode)) {
echo 'error:' . $res->errcode . '<hr>msg :' . $res->errmsg;
exit;
}
return json_decode($res, true);
}
/**
* 获取用户信息
*
* @param $accessToken
* @param string $ticket
* @return mixed
*/
private function getUserInfoUseTicket($accessToken, $ticket = '')
{
$data = json_encode(['user_ticket' => $ticket]);
$res = \Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token={$accessToken}",
$data);
if (isset($res->errcode)) {
echo 'error:' . $res->errcode . '<hr>msg :' . $res->errmsg;
exit;
}
return json_decode($res, true);
}
/**
* @param $accessToken
* @param $uid
*/
private function getUserInfoUseUid($accessToken, $uid)
{
$res = \Tools::httpsRequest("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={$accessToken}&userid={$uid}");
if (isset($res->errcode)) {
echo 'error:' . $res->errcode . '<hr>msg :' . $res->errmsg;
exit;
}
return json_decode($res, true);
}
}
3.工具类Tools.php
<?php
/**
* 工具类
*/
class Tools
{
/**
* http 请求函数
*
* @param $url
* @param array $data
* @return bool|string
*/
public static function httpsRequest($url, $data = [])
{
// curl 初始化
$curl = curl_init();
// curl 设置
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// 判断 $data get or post
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 执行
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
/**
* 生成随机字符串
*
* @param int $length
* @return string
*/
public static function createNonceStr($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
}
4.配置文件Conf.php
<?php
/**
* 企业微信 + seaTable单点登录 配置
*/
return array(
'appId' => '',
'appSecret' => '',
'agentId' => '',
'ssoSecretKey' => '',
'toDomain' => 'http://XXX',
'debug' => true
);