利用企业微信自动登录WordPress网站

软件编程5小时前更新 轩哥谈芯
2,574 0 0

  如果我们想做一些内嵌到企业微信里面的展示网站,可以选择WordPress平台,安装DairyPress插件,这个插件可以将网站变为私有,游客无法查看网站内容,只有登录的用户才可以查看内容。

  同时,在企业微信中嵌入网站,通过企业微信的用户名授权登录wordpress网站后既可以查看网站。

  那么要想实现企业微信登录wordpress就要通过OAuth2.0协议来获取企业微信的用户信息。

  OAuth2的设计背景,在于允许用户在不告知第三方自己的帐号密码情况下,通过授权方式,让第三方服务可以获取自己的资源信息。

企业微信的API文档可以参考链接: https://work.weixin.qq.com/api/doc/90000/90135/91020

接下来是在wordpress的主题目录下添加一个文件,如wechat.php,那么我们可以在企业微信中设置访问此链接,然后处理信息获取企业微信用户信息。

具体代码如下:

<?php

define('WX_APPID','wxadbxxxxxxxc87ae5'); //这里定义企业微信的ID
define('WX_APPSECRET','');
define('WX_KEY','weixin_uid');

require( dirname(__FILE__) . '/../../../wp-load.php' ); //这里获取一些wp的api
session_start(); //利用session存储重定向地址

//判断浏览器
function userBrowser() { 
    $user_OSagent = $_SERVER['HTTP_USER_AGENT']; 
  
    if(strpos($user_OSagent, 'MicroMessenger') !== false)
    {
        $visitor_browser = "wechat";
    } 
    elseif(strpos($user_OSagent, 'wxwork')!== false) 
    {
        $visitor_browser = "wxwork";
    }
    else 
    {
    	 $visitor_browser = "other";
    }
    return $visitor_browser; 
}
define('WX_TOKEN','wechat_token.txt'); 定义一个文件存放token,相当于缓存下来
function update_token($file)
{
    $wechatId = "wxadbxxxxxxxc87ae5"; //企业微信ID
    $secret = "_qZSwhpxxxxxxxxxgez_n9hIdOi2Ed7CP6FFc"; //应用的secret
    
    $tokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$wechatId&corpsecret=$secret"; //利用自建应用获取token的地址   
	$res = httpGet($tokenURL); //获取token
	$secret_token = json_decode($res); //转换为json
	file_put_contents($file,$secret_token->access_token); //将secret写入文件
}

/**
 * 模拟get进行url请求
 * @param string $url
 * @return json
 */
function httpGet($url) {
	
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_URL, $url);

	$res = curl_exec($curl);
	curl_close($curl);

	return $res;
}
function wechat_oauth_redirect(){
    $url = home_url(); //获取主页地址,然后重定向连接过去
    wp_redirect( $url );
    exit;
}

function wechat_oauth(){
    if(!isset($_GET['code'])) wp_die('code empty.');
    $code = $_GET['code'];
    $mytoken = file_get_contents(WX_TOKEN); //获取缓存的token
    //更换为企业微信api
    $id_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$mytoken&code=$code";
    $user_id_data = file_get_contents($id_url); //获取企业用户ID
    $user_id = json_decode($user_id_data,true);
    $weixin_id = $user_id['UserId'];
    echo $weixin_id;
    if(!$weixin_id)  //如果ID没有获取到,则重新更新一下token
    {
    	update_token(WX_TOKEN);
    	wp_die('授权时发生错误');
    }
    else {
    	//-----获取完ID后,要根据ID获取其他用户信息
        $info_url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$mytoken&userid=$weixin_id";
        $user_info_data = file_get_contents($info_url);
        $user_info = json_decode($user_info_data,true);
        $weixin_id = $user_info['userid']; 获取企业微信ID
        echo $user_info['name'];
    }
    if(is_user_logged_in()){  //如果是登录状态,就将当前的企业微信ID和当前用户同步
        $this_user = wp_get_current_user();
        update_user_meta($this_user->ID ,WX_KEY,$weixin_id); //设置ID
        update_user_meta($this_user->ID ,'weixin_avatar',$user_info['avatar']);//设置头像
        wechat_oauth_redirect(); //重定向到首页
    }else{ //创建新用户
        $oauth_user = get_users(array('meta_key'=>WX_KEY,'meta_value'=>$weixin_id)); //产生一个用户
        if(is_wp_error($oauth_user) || !count($oauth_user)){
            $username = $user_info['name']; //名字
            $login_name = 'wx' . wp_create_nonce($weixin_id);//wxid作为登录
            $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
            $userdata=array(
                'user_login' => $login_name,
                'display_name' => $username,
                'user_pass' => $random_password,
                'nickname' => $username,
                'first_name' => $username,
                'user_email' => $usermail
            );
            $user_id = wp_insert_user( $userdata );    wp_signon(array('user_login'=>$login_name,'user_password'=>$random_password),false);
            update_user_meta($user_id ,WX_KEY,$weixin_id);
            update_user_meta($user_id ,'weixin_avatar',$user_info['avatar']);
            wechat_oauth_redirect();

        }else{
            wp_set_auth_cookie($oauth_user[0]->ID);
            wechat_oauth_redirect();
        }
    }
}
if (isset($_GET['code'])){
    wechat_oauth(); //如果存在code参数才进行鉴权登录
}

if(isset($_GET['url'])){
	//session_start();
	$_SESSION['userurl'] = $_GET['url'];
}

//. $_SESSION ['state']   获取授权URL
function wechat_oauth_url(){
    $directory = get_template_directory_uri().'/'.'wechat.php';
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. WX_APPID .'&redirect_uri='.urlencode($directory).'&response_type=code&scope=snsapi_base&state=' . $_SESSION ['state'] . '#wechat_redirect';
    return $url;
}

$url_jump = wechat_oauth_url(); //获取授权的URL,企业微信会自动把重定向连接和code返回
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//获取浏览器信息,判断是否在微信中
$browser_type = userBrowser();
if($browser_type == "wechat"){
//$url_jump = "http://www.baidu.com";
    header("Location:$url_jump");  //到另一个文件获取用户ID
//echo "<script>location.href=$url_jump</script>";
}
else{
	$url_jump = 'http://inside.segway-ninebot.com?'.$_SESSION['userurl'];
	header("Location:$url_jump");  //到另一个文件获取用户ID
}
?>

下面代码利用了diarypress插件,保证在企业微信中直接登录后查看,在其他浏览器中需要登录。

if ($_SERVER['REQUEST_URI'] == get_bloginfo('url').'/wp-mail.php') {
// Don't go any further as we are checking for new e-mails using the mail2blog feature.
// We would expect most to use CRON however for compatibility this is maintained.
}

else {
	
	add_action( 'template_redirect', 'force_login' );
	
	function force_login()
	{
		$redirect_to = $_SERVER['REQUEST_URI']; 
		if ( ! is_user_logged_in() )
		{
		    if ( is_wp_error( $user ) )
		    {
			die();		
		    } // if
                    else
	            {
			
// die and show error message

// Set title in browser
//$title = "Private Diary";

//we know that the page arrived so we need to tell the browser that the status should be http 200 
// Otherwise we would give a false internal server error. Not cool if we use monitoring software

 $args = array( 'response'   => '200', );


// Keep the data in the body instead of a html file and calling it as we want some php variables.
// The default values if none present in database

$dp_ops = array ('dppagetitle' =>'Private Diary', 'title'=>'Private Diary','dpimg'=>'none');
?>

</br>
<?php $options = get_option('DiaryPress_options',$dp_ops); ?><h4><strong><?php echo $options['title']; ?></strong></h4>

<?php $title = $options['dppagetitle']; ?>

<img class="alignnone size-medium wp-image-1623" title="" src="<?php echo $options['dpimg'];?>" alt="" />

<?php

$url = "http://inside.xxxxxx.com".$redirect_to; //保存重定向地址
//获取浏览器信息,判断是否在微信中
$user_OSagent = $_SERVER['HTTP_USER_AGENT']; 
$visitor_browser = "other";
    if(strpos($user_OSagent, 'MicroMessenger') !== false)
    {
        $visitor_browser = "wechat";
    }

if($visitor_browser == "wechat"){ //在微信中,自动登录跳转

wp_die( ('

<head>  
    <meta http-equiv="refresh" content="0;url=http://inside.xxxxxx.com/wp-content/themes/Zing/wechat.php?url='.$url.'">   
</head>

<p>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="'. get_bloginfo('wpurl') .'/xmlrpc.php?rsd" />
</p>

<p>本网站在企业微信内部可查看,如需在企业微信外部查看,请先设置好账户密码,然后请 <a href="'. get_bloginfo('wpurl') .'/wp-login.php">登录</a></p>
<p><strong>如果疑问,请联系</strong></p>
'), $title, $args );

} //在微信中
else
{ //不在微信中,提示信息
wp_die( ('

<p>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="'. get_bloginfo('wpurl') .'/xmlrpc.php?rsd" />
</p>

<p>本网站在企业微信内部可查看,如需在企业微信外部查看,请先设置好账户密码,然后请 <a href="'. get_bloginfo('wpurl') .'/wp-login.php">登录</a></p>
<p><strong>如果疑问,请联系</strong></p>

'), $title, $args );

}
				} // Close die

	  	} // Close user logged in

	} // force_login
	
} // End statement of not logged in and not a mail check
© 版权声明

相关文章