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

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

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

+14
查看文件
@@ -37,3 +37,17 @@ python3 Backend/deploy.py --package '/Volumes/备份/大鱼调色/发行包/大
先从仓库审查、提交并推送,再由部署脚本同步到专项工程;脚本验证实际 SMB 挂载及基线。覆盖原文件前同目录旁路备份并核对字节,新增文件无需不存在的备份。只写明确列出的路径,不加载或输出生产配置。更新包签名、公证、票据与正式 APP 验收通过后才发布;同名包不同字节立即停止。发布后完整下载核对大小与 SHA-256,并核验较低/相同构建号的更新结果。
回滚:先备份当前文件,再恢复部署记录中对应旁路备份;禁止降低已有清单构建号来自动降级。撤下更新时备份并移走 beta.json,更新路由回到没有更新;历史安装包和诊断表保留。源代码可从产品远程仓库恢复,签名私钥及服务端数据库不属于 Git 备份。
## 微信首次扫码登录专项(2026-11-12,待部署)
本轮使用仓库 `Backend/` 为有范围的本机专项工程。新增保存生产主题 `wp-content/themes/ripro5/inc/oauth/weixin/callback.php`,仅将 `DayuColor` 加入现有扫码证明名单;同时在线 LUT 会话接口把拒绝/过期返回为 HTTP 401,让现有 1.22.1 客户端及时结束等待。无需重编 APP。
```sh
php Backend/tests/wechat_callback.php
php Backend/tests/online_luts.php
python3 Backend/deploy_wechat_login.py
```
前两项执行合成账号和 OAuth 的隔离测试,不加载生产配置;后一项仅审阅两个明确目标、SHA-256、挂载与权限。先按仓库约定完成源码提交、推送和回读,再加 `--apply` 进行部署。写入前复核全部目标基线,每个覆盖文件均创建原目录分钟级旁路备份;部署报告保存每个相对路径、备份完整路径与摘要。回退沿用上节规则。若生产基线已变化,先重新比较,不能直接更新预期摘要来绕过保护。
本轮环境禁止写入 NAS 生产目标及 Git 锁目录,尚未提交/推送/部署,也未完成真实未绑定用户扫码验收。现状与接手步骤见 [开发交接](../开发交接.md),证据见 [验证报告](../verification/WeChatLoginFix.json)。
+75
查看文件
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Review by default; --apply deploys only the two WeChat login fixes."""
import argparse
import datetime
import json
import os
from pathlib import Path
import shutil
import subprocess
from deploy import ROOT, NAS, MOUNT, sha, check_mount, deploy_file, write_json
FILES = (
Path('wp-content/themes/ripro5/inc/oauth/weixin/callback.php'),
Path('wp-content/mu-plugins/dayu-color-online-luts.php'),
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
mounts = subprocess.check_output(['/sbin/mount'], text=True).splitlines()
matches = [line for line in mounts if f' on {MOUNT} (smbfs,' in line]
assert len(matches) == 1 and '@192.168.31.21/dayumedia%' in matches[0], 'NAS SMB mount mismatch'
baseline = json.loads((ROOT/'verification/WeChatLoginBaseline.json').read_text())
expected = {row['relativePath']: row['sha256'] for row in baseline['files']}
files = []
# Validate every target before making any production change.
for relative in FILES:
source = ROOT/'Backend'/relative
target = NAS/relative
subprocess.run(['php', '-l', str(source)], check=True, capture_output=True)
assert sha(target) in (expected[str(relative)], sha(source)), 'Production baseline changed: '+str(relative)
files.append(dict(relativePath=str(relative), sourceSHA256=sha(source),
productionSHA256=sha(target), writable=os.access(target.parent, os.W_OK)))
contracts = []
for name in ('wechat_callback.php', 'online_luts.php'):
result = subprocess.run(['php', str(ROOT/'Backend/tests'/name)], check=True, capture_output=True, text=True)
report = json.loads(result.stdout)
assert report['pass']
contracts.append(dict(suite=name, count=report['count'], passed=True))
review = dict(mode='apply' if args.apply else 'review', localProject=str(ROOT/'Backend'),
nasRoot=str(NAS), files=files, contracts=contracts)
if not args.apply:
print(json.dumps(review, ensure_ascii=False, indent=2))
return
check_mount()
assert all(row['writable'] for row in files), 'Production target is read-only'
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
remote = subprocess.check_output(['git', 'ls-remote', 'origin', 'refs/heads/main'], cwd=ROOT, text=True).split()[0]
assert remote == commit, 'Source checkpoint must be pushed and verified first'
for relative in FILES:
saved = subprocess.check_output(['git', 'show', 'HEAD:Backend/'+str(relative)], cwd=ROOT)
assert saved == (ROOT/'Backend'/relative).read_bytes(), 'Source not committed: '+str(relative)
lock = ROOT/'Backend/.wechat-login-deployment.lock'
lock.mkdir()
write_json(lock/'owner.json', dict(pid=os.getpid(), sourceCommit=commit))
try:
results = []
for relative in FILES:
result = deploy_file(ROOT/'Backend'/relative, NAS/relative, expected=expected[str(relative)])
result['relativePath'] = str(relative)
results.append(result)
write_json(ROOT/'verification/WeChatLoginDeployment.json', dict(
checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(), sourceCommit=commit,
localProject=str(ROOT/'Backend'), nasRoot=str(NAS), files=results,
liveScanVerified=False, status='files deployed; fresh unbound-account scan still required'))
print(json.dumps(dict(deployed=len(results), files=results), ensure_ascii=False, indent=2))
finally:
shutil.rmtree(lock)
if __name__ == '__main__':
main()
+13
查看文件
@@ -55,6 +55,19 @@ check(body(Dayu_Color_Online_LUTs::logout(new Request(array(),$restored['token']
$session=array('app_name'=>'DayuColor','device_uuid'=>$device,'expires_at'=>time()+120,'status'=>'pending','user_id'=>7);
$transients[$login]=$session;
check(body(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))))['status']==='pending','pending login cannot mint a credential');
$bound=0;
check(body(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))))['status']==='pending','first unbound device can wait for WeChat approval');
$transients[$login]['status']='approved';
check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'approval cannot bypass missing UUID binding');
check(isset($transients[$login])&&!isset($options['dayu_color_lut_once_'.hash('sha256',$key)]),'missing binding does not consume the login session');
$transients[$login]=$session;$transients[$login]['status']='denied';$transients[$login]['message']='该 UUID 已绑定其他账号,请先解绑';
$failed=Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device)));
check(denied($failed,401)&&$failed->message===$transients[$login]['message'],'callback denial immediately stops installed client polling with the actual reason');
$transients[$login]['status']='expired';
check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'expired callback stops installed client polling');
$transients[$login]=$session;$transients[$login]['expires_at']=time()-1;
check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'past session deadline stops polling');
$transients[$login]=$session;$bound=7;
$transients[$login]['app_name']='FCPXSoundEffects';check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'another product login rejected');
$transients[$login]=$session;$transients[$login]['status']='approved';
$issued=Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device)));$token=body($issued)['token']??'';
+84
查看文件
@@ -0,0 +1,84 @@
<?php
// Execute the actual theme callback with synthetic OAuth and WordPress services.
// Never load wp-config.php, contact WeChat, or read/change real accounts.
namespace Yurun\OAuthLogin\Weixin {
class OAuth2 {
public $http, $openid='synthetic-wechat-openid';
public function __construct(...$args) { $this->http=new \stdClass; }
public function getAccessToken($state) { return 'synthetic-provider-token'; }
public function getUserInfo() { return array('nickname'=>'测试用户', 'headimgurl'=>'https://example.invalid/avatar'); }
}
}
namespace {
define('ABSPATH', __DIR__.'/'); define('MINUTE_IN_SECONDS', 60);
class CallbackRedirect extends \RuntimeException {}
class CallbackRejected extends \RuntimeException {}
class LoginEvents {
public $events=array();
public function log_login_event($stage,$fields=array()) { $this->events[]=array('stage'=>$stage,'fields'=>$fields); }
}
class CallbackDB {
public $usermeta='synthetic_usermeta';
public function prepare(...$args) { return $args; }
public function get_var($query) { return 7; }
}
$wpdb=new CallbackDB;
$GLOBALS['dayu_macos_app_auth']=new LoginEvents;
$transients=array(); $checks=array();
function _cao($key) { return array('appid'=>'synthetic','appkey'=>'synthetic'); }
function home_url($path) { return 'https://dayu.media'.$path; }
function wp_parse_url($url) { return parse_url($url); }
function sanitize_text_field($value) { return trim(strip_tags($value)); }
function set_transient($key,$value,$ttl) { global $transients; $transients[$key]=$value; return true; }
function get_current_user_id() { return 0; }
function wp_set_current_user($id) {}
function wp_set_auth_cookie(...$args) {}
function get_user_by(...$args) { return (object)array('user_login'=>'synthetic-user'); }
function do_action(...$args) {}
function wp_safe_redirect($url) { throw new CallbackRedirect; }
function cao_wp_die(...$args) { throw new CallbackRejected; }
function is_wp_error($value) { return false; }
function check($passed,$name) {
global $checks;
$checks[]=array('name'=>$name,'pass'=>(bool)$passed);
if (!$passed) { fwrite(STDERR,'FAIL '.$name."\n"); exit(1); }
}
// Redirects throw before the production callback's exit statements.
function callback_proof($app, $overrides=array(), $host='dayu.media', $provider_state=true) {
global $transients;
$transients=array(); $GLOBALS['dayu_macos_app_auth']->events=array();
$query=array_merge(array('action'=>'app_wechat_auth_check','app_name'=>$app,
'fcpxqwen_session'=>str_repeat('a',40),'device_uuid'=>'00000000-0000-0000-0000-000000000001'),$overrides);
$_SESSION=array('oauth_rurl'=>'https://'.$host.'/wp-admin/admin-ajax.php?'.http_build_query($query));
if ($provider_state) { $_SESSION['YURUN_WEIXIN_STATE']='synthetic-state'; }
$_GET=array('code'=>'synthetic-code');
try { include $GLOBALS['callback_source']; } catch (CallbackRedirect $e) {} catch (CallbackRejected $e) {}
return $_SESSION['dayu_fcpx_wechat_oauth']??null;
}
$callback_source=$argv[1]??__DIR__.'/../wp-content/themes/ripro5/inc/oauth/weixin/callback.php';
session_start();
$proof=callback_proof('DayuColor');
check(is_array($proof),'DayuColor first scan writes OAuth proof without any prior UUID binding');
check($proof['session_hash']===hash('sha256',str_repeat('a',40))
&&$proof['device_hash']===hash('sha256','00000000-0000-0000-0000-000000000001')
&&$proof['openid_hash']===hash('sha256','synthetic-wechat-openid'),
'proof binds this login session, hardware UUID and provider identity');
check(abs(time()-$proof['issued_at'])<=1,'proof has a fresh server timestamp');
check(($transients['dayu_fcpx_oauth_proof_'.hash('sha256',str_repeat('a',40))]??null)===$proof,
'transient fallback matches proof across PHP session boundaries');
check(in_array('oauth_proof_written',array_column($GLOBALS['dayu_macos_app_auth']->events,'stage'),true),
'successful proof is visible in existing login diagnostics');
foreach (array('FCPXQwen3ASR','FCPXPython','FCPXSoundEffects','qwenzhiyin','DayuDownie','DayuLightFactory') as $app) {
check(is_array(callback_proof($app)),'existing app callback preserved: '.$app);
}
check(callback_proof('UnknownApp')===null,'unrecognized apps do not receive proof');
check(callback_proof('DayuColor',array(),'foreign.example')===null,'foreign redirect host cannot receive proof');
check(callback_proof('DayuColor',array('action'=>'other_action'))===null,'wrong callback action cannot receive proof');
check(callback_proof('DayuColor',array('fcpxqwen_session'=>'short'))===null,'invalid login session cannot receive proof');
check(callback_proof('DayuColor',array('device_uuid'=>'random-client-id'))===null,'non-hardware UUID cannot receive proof');
check(callback_proof('DayuColor',array(),'dayu.media',false)===null,'browser cookie or redirect alone cannot bypass provider state');
session_destroy();
echo json_encode(array('pass'=>true,'count'=>count($checks),
'scope'=>'Actual scoped theme callback with synthetic OAuth and WordPress services; no live scan or user data.',
'checks'=>$checks),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)."\n";
}
@@ -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('微信登录失败', '授权返回数据不完整,请重新尝试登录。');
}