非常好用的wordpress网站微信一键登录源码,可获得头像和用户名

// 添加一个自定义的登录按钮到登录页面
function add_wechat_login_button() {
    if (is_user_logged_in()) {
        return;
    }
    
    $redirect_uri = urlencode(wp_login_url());
    $wechat_login_url = "https://open.weixin.qq.com/connect/qrconnect?appid={YOUR_APP_ID}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_login";
    
    echo '<a href="' . $wechat_login_url . '" class="wechat-login-button">' . __('微信登录', 'text-domain') . '</a>';
}
add_action('login_form', 'add_wechat_login_button');

// 处理微信登录回调
function handle_wechat_login() {
    if (isset($_GET['code'])) {
        $code = $_GET['code'];
        
        // 使用code换取access_token和openid
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={YOUR_APP_ID}&secret={YOUR_APP_SECRET}&code={$code}&grant_type=authorization_code";
        $access_token_response = wp_remote_get($access_token_url);
        $access_token_data = json_decode(wp_remote_retrieve_body($access_token_response), true);
        
        if (isset($access_token_data['access_token'])) {
            $access_token = $access_token_data['access_token'];
            $openid = $access_token_data['openid'];
            
            // 获取用户信息
            $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
            $user_info_response = wp_remote_get($user_info_url);
            $user_info_data = json_decode(wp_remote_retrieve_body($user_info_response), true);
            
            if (isset($user_info_data['nickname'])) {
                $nickname = $user_info_data['nickname'];
                $user_email = $openid . '@wechat.com';
                
                // 检查用户是否已经存在
                $user = get_user_by('email', $user_email);
                if (!$user) {
                    // 创建新用户
                    $random_password = wp_generate_password();
                    $user_id = wp_create_user($user_email, $random_password, $user_email);
                    $user = get_user_by('id', $user_id);
                }
                
                // 自动登录用户
                wp_set_auth_cookie($user->ID, true);
                
                // 重定向到首页
                wp_redirect(home_url());
                exit;
            }
        }
    }
}
add_action('init', 'handle_wechat_login');
 

代码说明:

  1. add_wechat_login_button函数添加一个自定义的登录按钮到WordPress登录页面,点击按钮会跳转到微信登录页面。
  2. handle_wechat_login函数处理微信登录回调,通过code获取access_token和openid,再通过access_token和openid获取用户信息,最后自动登录用户并重定向到首页。
  3. 需要将{YOUR_APP_ID}{YOUR_APP_SECRET}替换成你自己的微信应用的AppID和AppSecret。

注意的是,这只是一个示例的代码,实际使用时需要根据自己的需求进行适当的修改和完善。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值