PHP code example of milpa / oauth-providers

1. Go to this page and download the library: Download milpa/oauth-providers 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/ */

    

milpa / oauth-providers example snippets


use Milpa\OAuth\Providers\GitHubOAuthService;

$github = new GitHubOAuthService($_ENV['GITHUB_CLIENT_ID'], $_ENV['GITHUB_CLIENT_SECRET']);

// 1. Redirect the user to GitHub. Generate + store $state yourself (session,
//    signed cookie, whatever your app already uses) — see "The state parameter" below.
$state = bin2hex(random_bytes(16));
$_SESSION['oauth_state'] = $state;

header('Location: ' . $github->getAuthUrl('https://app.example.com/callback/github', $state));

// 2. In the callback route: verify the state YOU stored matches the one GitHub echoed
//    back, then exchange the code. exchangeCode() makes two curl calls (token, then
//    userinfo) and returns an immutable Milpa\OAuth\DTO\GitHubUserInfo — never null,
//    never an array; a failure throws \RuntimeException.
if (!hash_equals($_SESSION['oauth_state'] ?? '', $_GET['state'] ?? '')) {
    throw new \RuntimeException('OAuth state mismatch — possible CSRF');
}

$user = $github->exchangeCode($_GET['code'], 'https://app.example.com/callback/github');

$user->id;         // GitHub's numeric user id, as a string
$user->login;      // GitHub username
$user->email;      // ?string — null if the user hides their email
$user->toArray();  // ['id' => ..., 'login' => ..., 'name' => ..., 'email' => ..., 'avatar_url' => ...]

use Milpa\OAuth\Providers\TelegramAuthService;

$telegram = new TelegramAuthService($_ENV['TELEGRAM_BOT_TOKEN']);

// $_GET (or $_POST) as sent by the Telegram Login Widget's onauth callback.
$user = $telegram->verify($_GET);

$user->getFullName();  // "Ada Lovelace" — joins first_name + last_name, trimmed
$user->username;       // ?string — Telegram usernames are optional
$user->toArray();      // ['id' => ..., 'first_name' => ..., 'last_name' => ..., 'username' => ..., 'photo_url' => ...]