以下是为您定制的 WordPress全功能注册登录插件完整代码方案,包含社交登录(微信/QQ)和手机验证功能。请按照步骤操作:
一、插件文件结构
/wp-content/plugins/custom-super-auth/
├── assets/
│ ├── style.css # 样式文件
│ └── wechat.png # 微信图标
├── includes/
│ ├── social-auth.php # 社交登录处理
│ └── sms-api.php # 短信接口处理
└── custom-super-auth.php # 主文件
二、核心代码实现
1. 主文件 custom-super-auth.php
<?php
/*
Plugin Name: 超级登录注册
Description: 集成微信/QQ登录+手机验证的注册系统
Version: 2.0
Author: Your Name
*/
// 安全检测
defined('ABSPATH') || exit;
// 定义常量
define('CSA_PATH', plugin_dir_path(__FILE__));
define('CSA_URL', plugin_dir_url(__FILE__));
// 包含组件
require_once CSA_PATH . 'includes/social-auth.php';
require_once CSA_PATH . 'includes/sms-api.php';
class Custom_Super_Auth {
public function __construct() {
// 注册短代码
add_shortcode('csa_auth_form', [$this, 'render_auth_form']);
// 处理表单提交
add_action('template_redirect', [$this, 'process_auth']);
// 加载资源
add_action('wp_enqueue_scripts', [$this, 'load_assets']);
}
/**
* 加载前端资源
*/
public function load_assets() {
wp_enqueue_style('csa-style', CSA_URL . 'assets/style.css');
wp_enqueue_script('csa-script', CSA_URL . 'assets/script.js', ['jquery'], null, true);
}
/**
* 渲染认证表单
*/
public function render_auth_form() {
if(is_user_logged_in()) return '<div class="csa-alert">您已登录</div>';
ob_start(); ?>
<div class="csa-container">
<!-- 社交登录 -->
<div class="social-login">
<a href="<?= CSA_Social_Auth::wechat_login_url() ?>" class="wechat-btn">
<img src="<?= CSA_URL ?>assets/wechat.png" alt="微信登录">
</a>
<a href="<?= CSA_Social_Auth::qq_login_url() ?>" class="qq-btn">QQ登录</a>
</div>
<!-- 手机登录表单 -->
<form id="csa-mobile-form" method="post">
<?php wp_nonce_field('csa_mobile_action', 'csa_nonce'); ?>
<div class="csa-field">
<input type="tel" name="phone"
pattern="^1[3-9]\d{9}$"
placeholder="手机号" required>
</div>
<div class="csa-field captcha-group">
<input type="text" name="sms_code"
placeholder="短信验证码" required>
<button type="button" class="get-sms-code"
onclick="sendSMSCode(this)">获取验证码</button>
</div>
<button type="submit" name="csa_submit">立即登录/注册</button>
</form>
</div>
<?php
return ob_get_clean();
}
/**
* 处理认证逻辑
*/
public function process_auth() {
// 处理社交登录回调
if(isset($_GET['csa_social'])) {
CSA_Social_Auth::handle_callback();
}
// 处理手机验证
if(isset($_POST['csa_submit'])) {
$this->process_mobile_auth();
}
}
/**
* 手机认证处理
*/
private function process_mobile_auth() {
// 验证Nonce
if(!wp_verify_nonce($_POST['csa_nonce'], 'csa_mobile_action')) {
$this->add_error('请求非法');
return;
}
// 获取数据
$phone = sanitize_text_field($_POST['phone']);
$code = sanitize_text_field($_POST['sms_code']);
// 验证短信验证码
if(!CSA_SMS_API::verify_code($phone, $code)) {
$this->add_error('验证码错误');
return;
}
// 查找/创建用户
$user = get_users([
'meta_key' => 'csa_phone',
'meta_value' => $phone
]);
if(empty($user)) {
$user_id = $this->create_user_by_phone($phone);
} else {
$user_id = $user->ID;
}
// 自动登录
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect(home_url());
exit;
}
/**
* 通过手机号创建用户
*/
private function create_user_by_phone($phone) {
$username = 'user_' . substr($phone, -4);
$userdata = [
'user_login' => $username,
'user_pass' => wp_generate_password(),
'role' => 'subscriber'
];
$user_id = wp_insert_user($userdata);
update_user_meta($user_id, 'csa_phone', $phone);
return $user_id;
}
/**
* 错误提示系统
*/
private function add_error($message) {
add_action('csa_messages', function() use ($message) {
echo '<div class="csa-error">'.esc_html($message).'</div>';
});
}
}
// 初始化插件
new Custom_Super_Auth();
2. 社交登录组件 includes/social-auth.php
<?php
class CSA_Social_Auth {
// 微信登录配置
const WECHAT_APPID = 'YOUR_WECHAT_APPID';
const WECHAT_SECRET = 'YOUR_WECHAT_SECRET';
// QQ登录配置
const QQ_APPID = 'YOUR_QQ_APPID';
const QQ_SECRET = 'YOUR_QQ_SECRET';
/**
* 生成微信登录链接
*/
public static function wechat_login_url() {
$state = wp_create_nonce('wechat_auth');
$redirect_uri = urlencode(home_url('/?csa_social=wechat'));
return "https://open.weixin.qq.com/connect/qrconnect?" .
"appid=".self::WECHAT_APPID.
"&redirect_uri={$redirect_uri}".
"&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
}
/**
* 处理社交登录回调
*/
public static function handle_callback() {
if(!isset($_GET['code'])) return;
$provider = $_GET['csa_social'];
$code = $_GET['code'];
switch($provider) {
case 'wechat':
$user_info = self::get_wechat_user($code);
break;
case 'qq':
$user_info = self::get_qq_user($code);
break;
default:
return;
}
self::process_social_user($user_info);
}
/**
* 获取微信用户信息
*/
private static function get_wechat_user($code) {
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?" .
"appid=".self::WECHAT_APPID.
"&secret=".self::WECHAT_SECRET.
"&code={$code}&grant_type=authorization_code";
$response = wp_remote_get($token_url);
$data = json_decode($response['body'], true);
$user_url = "https://api.weixin.qq.com/sns/userinfo?" .
"access_token={$data['access_token']}&openid={$data['openid']}";
$user_response = wp_remote_get($user_url);
return json_decode($user_response['body'], true);
}
/**
* 处理社交用户数据
*/
private static function process_social_user($user_data) {
// 查找已绑定用户
$user = get_users([
'meta_key' => 'csa_social_id',
'meta_value' => $user_data['openid']
]);
if(empty($user)) {
$user_id = self::create_social_user($user_data);
} else {
$user_id = $user->ID;
}
// 自动登录
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect(home_url());
exit;
}
/**
* 创建社交用户
*/
private static function create_social_user($data) {
$username = sanitize_user('wx_'.$data['openid']);
$userdata = [
'user_login' => $username,
'user_pass' => wp_generate_password(),
'display_name' => $data['nickname'],
'role' => 'subscriber'
];
$user_id = wp_insert_user($userdata);
update_user_meta($user_id, 'csa_social_id', $data['openid']);
update_user_meta($user_id, 'csa_avatar', $data['headimgurl']);
return $user_id;
}
}
3. 短信接口组件 includes/sms-api.php
<?php
class CSA_SMS_API {
// 短信宝配置
const SMS_USER = 'your_sms_username';
const SMS_PASS = md5('your_sms_password');
/**
* 发送短信验证码
*/
public static function send_code($phone) {
// 生成4位验证码
$code = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
// 存储到临时选项(有效期10分钟)
set_transient("csa_sms_{$phone}", $code, 10 * MINUTE_IN_SECONDS);
// 调用短信接口
$content = "【您的网站】验证码:{$code},10分钟内有效";
$api_url = "http://api.smsbao.com/sms?u=".self::SMS_USER.
"&p=".self::SMS_PASS.
"&m={$phone}&c=".urlencode($content);
return wp_remote_get($api_url);
}
/**
* 验证短信码
*/
public static function verify_code($phone, $code) {
$stored_code = get_transient("csa_sms_{$phone}");
return $stored_code === $code;
}
}
三、前端资源文件
1. 样式文件 assets/style.css
/* 基础容器 */
.csa-container {
max-width: 400px;
margin: 2rem auto;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
/* 社交登录按钮 */
.social-login {
margin-bottom: 2rem;
text-align: center;
}
.wechat-btn, .qq-btn {
display: inline-block;
padding: 12px 25px;
margin: 0 10px;
border-radius: 25px;
text-decoration: none;
}
.wechat-btn {
background: #09bb07;
color: white;
}
.qq-btn {
background: #12B7F5;
color: white;
}
/* 手机表单 */
#csa-mobile-form input {
width: 100%;
padding: 12px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
.captcha-group {
display: flex;
gap: 10px;
}
.get-sms-code {
background: #f0f0f0;
border: 1px solid #ddd;
padding: 12px;
cursor: pointer;
white-space: nowrap;
}
2. JavaScript文件 assets/script.js
// 发送短信验证码
function sendSMSCode(btn) {
const phone = document.querySelector('input[name="phone"]').value;
if(!/^1[3-9]\d{9}$/.test(phone)) {
alert('请输入正确的手机号');
return;
}
// 禁用按钮60秒
btn.disabled = true;
let count = 60;
const timer = setInterval(() => {
btn.textContent = `${count--}秒后重发`;
if(count <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.textContent = '获取验证码';
}
}, 1000);
// 调用后端发送短信
jQuery.post(ajaxurl, {
action: 'csa_send_sms',
phone: phone
}, function(response) {
if(!response.success) {
alert('发送失败: ' + response.data);
}
});
}
// 注册AJAX动作
jQuery(document).ready(function($) {
// 处理短信发送
$(document).on('click', '.get-sms-code', function() {
sendSMSCode(this);
});
});
四、使用说明
- 配置准备:
- 申请微信开放平台和QQ互联的APP ID
- 注册短信服务商(如阿里云、短信宝)
- 修改代码中的配置常量(APPID/密钥)
- 安装步骤:
# 创建插件目录
mkdir -p /wp-content/plugins/custom-super-auth/{assets,includes}
# 上传所有文件到对应目录
- 功能特点:
- 前端响应式登录表单
- 微信/QQ一键登录
- 手机号验证注册
- 短信验证码安全机制
- 自动创建用户系统
- 防御CSRF攻击
- 使用方法:
// 在页面中插入短代码
[csa_auth_form]
五、安全增强建议
- 在
wp-config.php
添加:
define('DISALLOW_FILE_EDIT', true); // 禁止文件编辑
- 建议增加:
- IP请求频率限制
- 人机验证(如reCAPTCHA)
- 登录失败锁定机制
- 用户行为日志
此代码经过模块化设计,可根据需要增删功能模块。建议在生产环境中使用HTTPS协议,并定期更新第三方API密钥。
。
提示:仅供参考