LeanderChen
3/12/2018 - 1:54 PM

社交化登陆

社交化登陆

<?php
/**
 * 微信公众号内Oauth连接
 * 将该源文件置于站点根目录,访问该文件测试配置是否生效。
 * 如果程序成功打印授权用户微信信息,则配置有效,反之则需检查开放平台配置
 **/
ini_set('display_errors', TRUE);

$appid = '你的appid';
$appsecret = '你的appsecret';
$url = '你的测试域名';

$code = $_GET['code']?$_GET['code']:'';
$state = $_GET['state']?urlencode($_GET['state']):'';
$redirect = urlencode($url.'oauth.php');
if(!$code){
    _code($redirect,$state,$appid);
} else {
   $access_token = _access_token($code,$appid,$appsecret);
   $wxinfo = json_decode(_user_info($access_token));
   if($wxinfo && $wxinfo->openid){
        var_dump($wxinfo);
   }
   header('HTTP/1.1 307 Temporary Redirect');
   header('Location: '.urldecode($state));
}

function _code($redirect,$state,$appid) {
    
    header('HTTP/1.1 302 Found');
    header('Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect');
    
}

function _access_token($code,$appid,$appsecret) {
    
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
    
    $data = json_decode(@catcher_data($url), true);
    return $data['access_token'];

}

function _user_info($access_token) {
    
    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid=OPENID&lang=zh_CN';
    return @catcher_data($url); 
    
}

function catcher_data($url) {

    // fopen模式
    if (ini_get('allow_url_fopen')) {
        $data = @file_get_contents($url);
        if ($data !== FALSE) {
            return $data;
        }
    }

    // curl模式
    if (function_exists('curl_init') && function_exists('curl_exec')) {
        $ch = curl_init($url);
        $data = '';
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    return NULL;
}