PHP code example of wiseadmin / wise-oauth
1. Go to this page and download the library: Download wiseadmin/wise-oauth library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wiseadmin / wise-oauth example snippets
return [
// 平台配置
'platforms' => [
'github' => [
'enabled' => true,
'driver' => \wise\oauth\driver\GithubDriver::class,
'client_id' => env('OAUTH_GITHUB_CLIENT_ID'),
'client_secret' => env('OAUTH_GITHUB_CLIENT_SECRET'),
'redirect_uri' => 'https://example.com/oauth/callback/github',
'scopes' => ['user:email'],
],
'wechat_open' => [
'enabled' => false,
'driver' => \wise\oauth\driver\WechatOpenDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'wechat_mp' => [
'enabled' => false,
'driver' => \wise\oauth\driver\WechatMpDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'qq' => [
'enabled' => false,
'driver' => \wise\oauth\driver\QqDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'dingtalk' => [
'enabled' => false,
'driver' => \wise\oauth\driver\DingtalkDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'gitee' => [
'enabled' => false,
'driver' => \wise\oauth\driver\GiteeDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'google' => [
'enabled' => false,
'driver' => \wise\oauth\driver\GoogleDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
'weibo' => [
'enabled' => false,
'driver' => \wise\oauth\driver\WeiboDriver::class,
'client_id' => '',
'client_secret' => '',
'redirect_uri' => '',
],
],
// 自动注册(无匹配本地用户时自动创建)
'auto_register' => true,
// 自动关联(email/mobile 匹配时自动绑定)
'auto_link' => [
'email' => false,
'mobile' => false,
],
// PKCE 增强安全(RFC 7636)
'pkce_enabled' => false,
// 频率限制
'rate_limit' => [
'enabled' => false,
'max_attempts' => 10,
'decay_minutes' => 1,
],
// Token 加密
'token_encryption' => [
'enabled' => true,
'key' => env('OAUTH_ENCRYPT_KEY', ''),
],
// 用户模型映射
'user_model' => [
'admin' => \app\admin\model\Admin::class,
'member' => \app\api\model\Member::class,
],
];
namespace app\admin\model;
use think\Model;
use wise\oauth\trait\HasOAuth;
class Admin extends Model
{
use HasOAuth;
// 可选:覆盖默认 user_type(默认取类名小写)
public function getOAuthUserType(): string
{
return 'admin';
}
}
use wise\oauth\facade\OAuth;
// 获取 GitHub 授权 URL
$authUrl = OAuth::getAuthUrl('github');
// 指定自定义回调地址
$authUrl = OAuth::getAuthUrl('github', 'https://example.com/custom/callback');
// 在回调控制器中
use wise\oauth\facade\OAuth;
public function callback(string $platform)
{
$code = request()->get('code');
$state = request()->get('state');
try {
// 获取标准化用户信息
$userInfo = OAuth::handleCallback($platform, $code, $state);
// 登录或注册,返回 ['user' => Admin, 'action' => 'login'|'register']
$result = OAuth::loginOrRegister($userInfo, 'admin');
// 登录成功,写入 Session
session('admin_id', $result['user']->id);
return redirect('/admin/dashboard');
} catch (\Exception $e) {
return redirect('/admin/login')->with('error', '登录失败: ' . $e->getMessage());
}
}
use wise\oauth\facade\OAuth;
// 绑定(先获取授权 URL,回调时绑定)
$authUrl = OAuth::getAuthUrl('github');
// 回调中绑定
$userInfo = OAuth::handleCallback('github', $code, $state);
OAuth::bindUser($userId, 'admin', $userInfo);
// 解绑
OAuth::unbindUser($userId, 'admin', 'github');
// 检查绑定状态
$bound = OAuth::hasBinding($userId, 'admin', 'github');
// 获取用户所有绑定
$bindings = OAuth::getUserBindings($userId, 'admin');
$admin = Admin::find(1);
// 获取绑定列表
$bindings = $admin->getOAuthBindings();
// [['platform' => 'github', 'nickname' => 'octocat', 'avatar' => '...'], ...]
// 检查是否绑定
if ($admin->hasOAuthBinding('github')) {
echo '已绑定 GitHub';
}
// 解绑
$admin->unbindOAuth('weibo');
use wise\oauth\entity\OAuthUserInfo;
// 属性
$userInfo->platform; // 平台标识: 'github', 'wechat_open', ...
$userInfo->openid; // 平台 OpenID
$userInfo->unionId; // 联合 ID(微信/QQ 等,可能为 null)
$userInfo->nickname; // 昵称
$userInfo->avatar; // 头像 URL
$userInfo->email; // 邮箱(平台授权获取)
$userInfo->mobile; // 手机号(平台授权获取)
$userInfo->gender; // 性别
$userInfo->accessToken; // 访问令牌(加密存储)
$userInfo->refreshToken; // 刷新令牌(加密存储)
$userInfo->expiresIn; // 令牌过期时间
$userInfo->raw; // 原始响应数据
// app/event.php
return [
'listen' => [
\wise\oauth\event\OAuthUserRegistered::class => [
\app\listener\SendWelcomeEmail::class,
\app\listener\GrantDefaultRole::class,
],
\wise\oauth\event\OAuthUserLoggedIn::class => [
\app\listener\RecordLoginHistory::class,
],
\wise\oauth\event\OAuthUserBound::class => [
\app\listener\NotifyBinding::class,
],
],
];
use wise\oauth\driver\AbstractDriver;
use wise\oauth\entity\OAuthUserInfo;
class CustomOAuthDriver extends AbstractDriver
{
public function getPlatform(): string { return 'custom'; }
public function getPlatformName(): string { return '自定义平台'; }
public function getDefaultScopes(): array { return ['read']; }
public function getAuthUrl(string $state, ?string $redirectUri = null): string
{
return 'https://custom-oauth.com/authorize?' . http_build_query([
'client_id' => $this->getAppId(),
'redirect_uri' => $redirectUri ?? $this->getRedirectUri(),
'state' => $state,
]);
}
public function getUser(string $code, ?string $state = null, ?string $redirectUri = null): OAuthUserInfo
{
// 1. 用 code 换取 access_token
$tokenResponse = $this->httpPost('https://custom-oauth.com/token', [
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'code' => $code,
]);
// 2. 用 access_token 获取用户信息
$userResponse = $this->httpGet('https://custom-oauth.com/user', [
'access_token' => $tokenResponse['access_token'],
]);
return new OAuthUserInfo([
'platform' => 'custom',
'openid' => $userResponse['id'],
'nickname' => $userResponse['name'],
'avatar' => $userResponse['avatar'],
'email' => $userResponse['email'] ?? null,
'accessToken' => $tokenResponse['access_token'],
'refreshToken' => $tokenResponse['refresh_token'] ?? null,
'expiresIn' => $tokenResponse['expires_in'] ?? null,
'raw' => $userResponse,
]);
}
public function refreshToken(string $refreshToken): array
{
$response = $this->httpPost('https://custom-oauth.com/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
]);
return $response;
}
}
bash
php think wise:oauth:publish
php think migrate:run