代码语言:javascript复制
<?php
declare(ticks=1);
session_start();
require_once __DIR__ . '/vendor/autoload.php';
define("DEBUG" , true);
use EasyWeChatFactory;
if(!$_GET['target']){
$aaaaa='https://www.baidu.com/';
header('location:' . $aaaaa);
}
$appid = "1";
$secret = "2";
$options = [
'app_id' => $appid ,
'secret' => $secret ,
'log' => [
'level' => 'debug' ,
'file' => 'easywechat.log' ,
]
];
$app = Factory::officialAccount($options);
$scope = !empty($_GET['scope']) ? $_GET['scope'] : 'snsapi_userinfo';
$oauth = $app->oauth;
if( empty($_SESSION['wechat_user']) && !isset($_GET['code']) ) {
$target = isset($_GET['target']) ? $_GET['target'] : '';
$_SESSION['target'] = $target;
$oauth->scopes([$scope])->redirect()->send();
}
// 获取 OAuth 授权结果用户信息
if( empty($_SESSION['wechat_user']) ) {
//请求获取用户信息
$user = $oauth->user();
$_SESSION['wechat_user'] = $user->toArray();
//将用户存储到数据库...
}
//跳转回的url
$target = $_SESSION['target'];
$json = json_encode($_SESSION['wechat_user']['id']);
if( preg_match_all("/?[a-zA-z0-9]{1,}=[a-zA-z0-9]{1,}/" , $target) ) {
$target = $_SESSION['target'] . '&openid=' . $json;
}
else {
$target = $_SESSION['target'] . '?openid=' . $json;
}
DEBUG ?: var_dump($_SESSION['wechat_user']);
unset($_SESSION['wechat_user']);
header('location:' . $target); // 跳转到 user/profile