保存微信首次登录修复及当前生产可写预检

这个提交包含在:
mac 于 2026-11-13 01:14:36 +08:00 提交
1 父节点 8c2f226d43
当前提交 d944ad8652
10 个文件已更改
+987 -1

没有与搜索条件相匹配的文件

@@ -75,6 +75,11 @@ final class Dayu_Color_Online_LUTs {
if (!$device || !preg_match('/^[A-Za-z0-9_-]{32,80}$/D', $key)) { return self::error('login', '登录会话无效,请重新登录。', 400); }
$transient='dayu_app_login_' . hash('sha256', $key); $session=get_transient($transient);
if (!is_array($session) || intval($session['expires_at'] ?? 0) < time() || ($session['app_name'] ?? '') !== self::APP || !hash_equals((string)($session['device_uuid'] ?? ''), $device)) { return self::error('expired', '登录会话已过期,请重新登录。', 401); }
// Installed clients stop polling on 401. Do not leave a denied callback
// looking like a pending login until the ten-minute timer expires.
if (in_array($session['status'] ?? '', array('denied', 'expired'), true)) {
return self::error('login_failed', sanitize_text_field($session['message'] ?? '微信登录失败,请重新登录。'), 401);
}
if (($session['status'] ?? '') !== 'approved') { return self::response(array('status'=>sanitize_key($session['status'] ?? 'pending'), 'message'=>sanitize_text_field($session['message'] ?? '等待微信登录'))); }
$user_id=intval($session['user_id'] ?? 0);
if (!$user_id || self::bound_user($device) !== $user_id || !get_user_by('ID', $user_id)) { return self::error('binding', '账号绑定已变化,请重新登录。', 401); }
@@ -0,0 +1,280 @@
<?php
if (!defined('ABSPATH')) {die;} // Cannot access directly.
//启用 session - 检查是否已经启动
if (!session_id()) {
session_start();
}
$dayu_login_log = function ($stage, $fields = array()) {
if (isset($GLOBALS['dayu_macos_app_auth'])
&& is_object($GLOBALS['dayu_macos_app_auth'])
&& method_exists($GLOBALS['dayu_macos_app_auth'], 'log_login_event')) {
$GLOBALS['dayu_macos_app_auth']->log_login_event($stage, $fields);
}
};
//获取后台配置
$wxConfig = _cao('oauth_weixin');
$wxOAuth = new \Yurun\OAuthLogin\Weixin\OAuth2($wxConfig['appid'], $wxConfig['appkey']);
// 尝试提高健壮性:强制 IPv4、设置超时与重试,规避服务器 IPv6/DNS 异常和偶发网络抖动
try {
if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
$wxOAuth->http->option(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
} catch (\Throwable $e) {
// 忽略设置失败
}
// 毫秒
$wxOAuth->http->connectTimeout = 10000; // 10s 连接超时
$wxOAuth->http->timeout = 15000; // 15s 总超时
$wxOAuth->http->retry = 1; // 失败重试 1 次
if (isset($wxConfig['agent']) && $wxConfig['agent']) {
$wxOAuth->loginAgentUrl = esc_url(home_url('/oauth/weixinagent'));
}
// 防止未设置触发 Notice
if (empty($_SESSION['YURUN_WEIXIN_STATE'])) {
cao_wp_die('非法访问,没有经过第三方登录返回');
}
// 获取accessToken,把之前存储的state传入,会自动判断。
// 第三方返回异常(例如 code been used)时,当前代码未捕获会导致致命错误。
// 这里做一次兜底处理,提示用户并引导其重试登录。
try {
$accessToken = $wxOAuth->getAccessToken($_SESSION['YURUN_WEIXIN_STATE']);
} catch (\Throwable $e) {
// 清理已用的 state,避免重复使用
unset($_SESSION['YURUN_WEIXIN_STATE']);
// 记录错误便于排查,但不给用户暴露底层异常内容
if (function_exists('error_log')) {
error_log('Weixin OAuth getAccessToken failed: ' . $e->getMessage());
// 进一步主动探测一次接口,记录更详细的网络错误信息(不影响业务流程)
try {
$probe = new \Yurun\Util\HttpRequest();
if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
$probe->option(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
$probe->connectTimeout = 8000;
$probe->timeout = 12000;
$res = $probe->get('https://api.weixin.qq.com/sns/oauth2/access_token', array(
'appid' => $wxConfig['appid'],
'secret' => $wxConfig['appkey'],
'code' => isset($_GET['code']) ? $_GET['code'] : '',
'grant_type' => 'authorization_code',
));
$snippet = substr($res->body(), 0, 200);
error_log('Weixin OAuth probe status=' . $res->getStatusCode() . ' errno=' . $res->getErrno() . ' error=' . $res->getError() . ' body=' . $snippet);
} catch (\Throwable $e2) {
error_log('Weixin OAuth probe exception: ' . $e2->getMessage());
}
}
// 给出友好提示并提供重新发起登录的入口,避免 Fatal Error 白屏
$restartUrl = esc_url(home_url('/oauth/weixin')) . (isset($_SESSION['oauth_rurl']) ? ('?rurl=' . rawurlencode($_SESSION['oauth_rurl'])) : '');
$msg = '授权码已失效或被重复使用,请返回后重试(请勿刷新回调页)。<br><a href="' . $restartUrl . '">点击这里重新发起微信登录</a>';
cao_wp_die('微信登录失败', $msg);
}
$openid = $wxOAuth->openid; // 唯一ID
$dayu_login_log('oauth_provider_callback', array(
'has_oauth_code' => !empty($_GET['code']),
'has_openid' => !empty($openid),
'has_php_session' => session_status() !== PHP_SESSION_NONE,
));
// 兼容网络异常/返回非JSON导致的空结果:
// 当请求失败时,yurun-http 返回 null,未抛异常,这里显式拦截避免白屏
if (empty($accessToken) || empty($openid)) {
$raw = isset($wxOAuth->result) ? $wxOAuth->result : null;
if (function_exists('error_log')) {
// 记录原始返回,便于排查(一般为 null 或包含 errcode/errmsg)
error_log('Weixin OAuth getAccessToken returned empty. result=' . (is_array($raw) ? json_encode($raw, JSON_UNESCAPED_UNICODE) : var_export($raw, true)));
}
// 进一步主动探测一次接口,记录更详细的网络错误信息(不影响业务流程)
try {
$probe = new \Yurun\Util\HttpRequest();
if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
$probe->option(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
$probe->connectTimeout = 8000;
$probe->timeout = 12000;
$res = $probe->get('https://api.weixin.qq.com/sns/oauth2/access_token', array(
'appid' => $wxConfig['appid'],
'secret' => $wxConfig['appkey'],
'code' => isset($_GET['code']) ? $_GET['code'] : '',
'grant_type' => 'authorization_code',
));
$snippet = substr($res->body(), 0, 200);
error_log('Weixin OAuth probe status=' . $res->getStatusCode() . ' errno=' . $res->getErrno() . ' error=' . $res->getError() . ' body=' . $snippet);
} catch (\Throwable $e2) {
error_log('Weixin OAuth probe exception: ' . $e2->getMessage());
}
$restartUrl = esc_url(home_url('/oauth/weixin')) . (isset($_SESSION['oauth_rurl']) ? ('?rurl=' . rawurlencode($_SESSION['oauth_rurl'])) : '');
$msg = '未能获取微信授权凭证,可能由于服务器无法连接微信接口、网络波动,或回调参数已过期。<br><a href="' . $restartUrl . '">点击这里重新发起微信登录</a>';
cao_wp_die('微信登录失败', $msg);
}
try {
$userInfo = $wxOAuth->getUserInfo(); // 第三方用户信息,失败也可能抛异常
} catch (\Throwable $e) {
if (function_exists('error_log')) {
error_log('Weixin OAuth getUserInfo failed: ' . $e->getMessage());
}
cao_wp_die('微信登录失败', '获取用户信息失败,请返回后重试。');
}
// 防御性校验:避免空数组/空字段导致后续逻辑不执行而白屏
if (empty($userInfo) || !is_array($userInfo) || (empty($userInfo['nickname']) && empty($userInfo['headimgurl']))) {
if (function_exists('error_log')) {
error_log('Weixin OAuth getUserInfo returned invalid: ' . var_export($userInfo, true));
}
$restartUrl = esc_url(home_url('/?oauth=weixin'));
$msg = '未能获取到完整的微信用户资料,请返回后重试。<br><a href="' . $restartUrl . '">点击这里重新发起微信登录</a>';
cao_wp_die('微信登录失败', $msg);
}
// Dayu macOS APP 设备绑定必须能证明本次跳转确实经过了微信 OAuth,不接受仅有旧 WordPress Cookie 的回调。
$dayu_oauth_rurl = isset($_SESSION['oauth_rurl']) ? (string) $_SESSION['oauth_rurl'] : '';
$dayu_target = $dayu_oauth_rurl !== '' ? wp_parse_url($dayu_oauth_rurl) : false;
$dayu_home = wp_parse_url(home_url('/'));
if (is_array($dayu_target)
&& is_array($dayu_home)
&& !empty($dayu_target['host'])
&& !empty($dayu_home['host'])
&& hash_equals(strtolower((string) $dayu_home['host']), strtolower((string) $dayu_target['host']))) {
$dayu_query = array();
parse_str((string) ($dayu_target['query'] ?? ''), $dayu_query);
$dayu_session_key = sanitize_text_field((string) ($dayu_query['fcpxqwen_session'] ?? ''));
$dayu_device_uuid = strtoupper(sanitize_text_field((string) ($dayu_query['device_uuid'] ?? '')));
$dayu_app_name = sanitize_text_field((string) ($dayu_query['app_name'] ?? ''));
$dayu_trace_id = sanitize_text_field((string) ($dayu_query['trace_id'] ?? ''));
if (($dayu_query['action'] ?? '') === 'app_wechat_auth_check'
&& in_array($dayu_app_name, array('FCPXQwen3ASR', 'FCPXPython', 'FCPXSoundEffects', 'qwenzhiyin', 'DayuDownie', 'DayuLightFactory', 'DayuColor'), true)
&& preg_match('/^[A-Za-z0-9_-]{32,80}$/', $dayu_session_key)
&& preg_match('/^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/', $dayu_device_uuid)) {
$dayu_oauth_proof = array(
'session_hash' => hash('sha256', $dayu_session_key),
'device_hash' => hash('sha256', $dayu_device_uuid),
'openid_hash' => hash('sha256', (string) $openid),
'issued_at' => time(),
);
$_SESSION['dayu_fcpx_wechat_oauth'] = $dayu_oauth_proof;
set_transient(
'dayu_fcpx_oauth_proof_' . hash('sha256', $dayu_session_key),
$dayu_oauth_proof,
10 * MINUTE_IN_SECONDS
);
$dayu_login_log('oauth_proof_written', array(
'trace_id' => $dayu_trace_id,
'app_name' => $dayu_app_name,
'device_uuid' => $dayu_device_uuid,
'has_openid' => !empty($openid),
'proof_written' => true,
'proof_transient' => true,
));
} else {
$dayu_login_log('oauth_proof_not_written', array(
'trace_id' => $dayu_trace_id,
'app_name' => $dayu_app_name,
'device_uuid' => $dayu_device_uuid,
'has_openid' => !empty($openid),
'proof_written' => false,
));
}
}
// 处理本地业务逻辑
//
if ($openid && $userInfo) {
$_prefix = 'weixin';
$_openid_meta_key = 'open_' . $_prefix . '_openid';
// 初始化信息
$metaInfo = array(
'openid' => $openid,
'name' => $userInfo['nickname'],
'bind' => 1,
'avatar' => $userInfo['headimgurl'],
);
if (!empty($userInfo['unionid'])) {
$metaInfo['unionid'] = $userInfo['unionid'];
}
global $wpdb, $current_user;
// 查询meta
$user_exist = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key=%s AND meta_value=%s", $_openid_meta_key, $openid));
// 如果当前用户已登录,而$user_exist存在,即该开放平台账号连接被其他用户占用了,不能再重复绑定了
$current_user_id = get_current_user_id();
if ($current_user_id != 0 && isset($user_exist) && $current_user_id != $user_exist) {
cao_wp_die('绑定失败,可能之前已有其他账号绑定,请先登录其他账户解绑。');
}
if (isset($user_exist) && (int) $user_exist > 0) {
// 该开放平台账号已连接过WP系统,再次使用它直接登录
$user_exist = (int) $user_exist;
if (function_exists('dayu_sync_user_payout_wechat_openid')) {
dayu_sync_user_payout_wechat_openid($user_exist, $openid);
}
if (!empty($metaInfo['unionid'])) {
update_user_meta($user_exist, 'open_' . $_prefix . '_unionid', $metaInfo['unionid']);
}
wp_set_current_user($user_exist);
wp_set_auth_cookie($user_exist);
$user = get_user_by('id', $user_exist);
do_action('wp_login', $user->user_login, $user); // 保证挂载的action执行
wp_safe_redirect($_SESSION['oauth_rurl']);
exit;
} elseif ($current_user_id) {
// Open 连接未被占用且当前已登录了本地账号, 那么直接绑定信息到该账号 case: 从个人资料设置中点击了绑定社交账号等操作
update_user_meta($current_user_id, 'open_' . $_prefix . '_openid', $metaInfo['openid']);
update_user_meta($current_user_id, 'open_' . $_prefix . '_bind', $metaInfo['bind']);
update_user_meta($current_user_id, 'open_' . $_prefix . '_name', $metaInfo['name']);
update_user_meta($current_user_id, 'open_' . $_prefix . '_avatar', $metaInfo['avatar']);
if (function_exists('dayu_sync_user_payout_wechat_openid')) {
dayu_sync_user_payout_wechat_openid($current_user_id, $openid);
}
if (!empty($metaInfo['unionid'])) {
update_user_meta($current_user_id, 'open_' . $_prefix . '_unionid', $metaInfo['unionid']);
}
wp_safe_redirect($_SESSION['oauth_rurl']);
exit;
} else {
// 该开放平台账号未连接过WP系统,使用它登录并分配和绑定一个WP本地新用户
$login_name = "u" . mt_rand(1000, 9999) . mt_rand(1000, 9999);
$user_pass = wp_generate_password(64, true, true);
$nickname = $metaInfo['name'];
$userdata = array(
'user_login' => $login_name,
'user_email' => $login_name.'_mail@no.com',
'display_name' => $nickname,
'nickname' => $nickname,
'user_pass' => $user_pass,
'role' => get_option('default_role'),
'first_name' => $nickname,
);
$user_id = wp_insert_user($userdata);
if (is_wp_error($user_id)) {
echo $user_id->get_error_message();
} else {
// 更新用户字段
update_user_meta($user_id, 'open_' . $_prefix . '_openid', $metaInfo['openid']);
update_user_meta($user_id, 'open_' . $_prefix . '_bind', $metaInfo['bind']);
update_user_meta($user_id, 'open_' . $_prefix . '_name', $metaInfo['name']);
update_user_meta($user_id, 'open_' . $_prefix . '_avatar', $metaInfo['avatar']);
update_user_meta($user_id, 'user_avatar_type',$_prefix);
if (function_exists('dayu_sync_user_payout_wechat_openid')) {
dayu_sync_user_payout_wechat_openid($user_id, $openid);
}
if (!empty($metaInfo['unionid'])) {
update_user_meta($user_id, 'open_' . $_prefix . '_unionid', $metaInfo['unionid']);
}
//登录
wp_set_auth_cookie($user_id, true, false);
$user = get_user_by('id', $user_id);
do_action('wp_login', $user->user_login, $user); // 保证挂载的action执行
wp_safe_redirect($_SESSION['oauth_rurl']);
}
exit;
}
} else {
// 理论不会到达,但为防止意外(例如上游返回结构变化),兜底提示,避免白屏
cao_wp_die('微信登录失败', '授权返回数据不完整,请重新尝试登录。');
}