网站开发中微信一键登录,为什么带www域名提醒登录失败,不带www却可以正常登录?
在微信开放平台中的授权回调域填写的是yuming.com,业务域名是https://www.yuming.com;https://yuming.com。
尝试多次,不知道怎么处理了??请指点。
'redirect_uri' => '', // 动态处理,在SocialAuth类中设置
// 微信登录业务逻辑配置
'trial_days' => 1,
'trial_limit' => 1,
// 生成微信授权链接(仅用微信state机制)
public function getAuthUrl() {
$state = bin2hex(random_bytes(16)); // 生成高强度随机字符串
$_SESSION['oauth_state'] = $state; // 存储到session
// 动态获取当前域名并确保使用主域名
$currentDomain = $_SERVER['HTTP_HOST'];
$mainDomain = str_replace('www.', '', $currentDomain);
$redirectUri = 'https://' . $mainDomain . '/login.php';
// 构建符合微信官方要求的URL
return sprintf(
"%s?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect",
$this->config['wechat']['authorize_url'],
$this->config['wechat']['app_id'],
rawurlencode($redirectUri), // RFC 3986编码
$state
);
}
// 处理微信回调(核心安全验证)
public function handleCallback($code, $state) {
// 基础参数检查
if (empty($code) || empty($state)) {
throw new Exception("缺失必要参数");
}
// 安全验证:state比对(防御CSRF攻击)
if (empty($_SESSION['oauth_state']) || !hash_equals($_SESSION['oauth_state'], $state)) {
error_log("[安全告警] State不匹配 Session:".($_SESSION['oauth_state']??'空')." vs 传入:".$state);
throw new Exception("非法请求来源");
}
unset($_SESSION['oauth_state']); // 立即销毁
// 获取微信Access Token
$token = $this->getAccessToken($code);
if (isset($token['errcode'])) {
throw new Exception("微信通信失败:" . $token['errmsg']);
}
// 获取用户信息
$userInfo = $this->getUserInfo($token['access_token'], $token['openid']);
if (isset($userInfo['errcode'])) {
throw new Exception("用户信息获取失败:" . $userInfo['errmsg']);
}
// 返回标准化用户数据
return $this->createOrUpdateUser($userInfo);
}
// 获取Access Token(微信API通信)
private function getAccessToken($code) {
$url = $this->config['wechat']['access_token_url'] . '?' . http_build_query([
'appid' => $this->config['wechat']['app_id'],
'secret' => $this->config['wechat']['app_secret'],
'code' => $code,
'grant_type' => 'authorization_code'
]);