PHP code example of artisanpack-ui / apple-oauth

1. Go to this page and download the library: Download artisanpack-ui/apple-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/ */

    

artisanpack-ui / apple-oauth example snippets


use ArtisanPackUI\AppleOAuth\Contracts\ConfigurationRepository;

app( ConfigurationRepository::class )->save( [
    'client_id'    => 'com.acme.app.web',
    'team_id'      => 'ABCDE12345',
    'key_id'       => 'XXXXXXXXXX',
    'private_key'  => file_get_contents( '/path/to/AuthKey_XXXXXXXXXX.p8' ),
    'redirect_uri' => 'https://acme.example.com/apple/callback',
] );

use ArtisanPackUI\AppleOAuth\Facades\AppleOAuth;
use Illuminate\Http\Request;

Route::get( '/apple/connect', function ( Request $request ) {
    $url = AppleOAuth::oauth()->authorizationUrl( $request->user()->id );

    return redirect( $url );
} )->middleware( 'auth' )->name( 'apple.connect' );

->withMiddleware( function ( Middleware $middleware ) {
    $middleware->validateCsrfTokens( except: [
        'apple/callback',
    ] );
} )

use ArtisanPackUI\AppleOAuth\Exceptions\OAuthException;
use ArtisanPackUI\AppleOAuth\Facades\AppleOAuth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

Route::post( '/apple/callback', function ( Request $request ) {
    try {
        $response = AppleOAuth::oauth()->handleCallback(
            code:          $request->input( 'code', '' ),
            returnedState: $request->input( 'state', '' ),
            userPayload:   $request->input( 'user' ),
        );
    } catch ( OAuthException $e ) {
        // Log the specific reason for operators; do NOT surface $e->getMessage()
        // to the end user — messages carry interpolated diagnostics (Apple's
        // error codes, an unexpected id_token issuer, a filesystem path to the
        // .p8 file). Render a fixed, translated message instead.
        Log::warning( 'Apple OAuth callback failed', [ 'exception' => $e ] );

        return redirect( '/' )->withErrors( [
            'apple' => __( 'We could not complete the Sign in with Apple flow. Please try again.' ),
        ] );
    }

    $connection = AppleOAuth::tokens()->store( $response );

    return redirect( '/account' )->with( 'status', 'apple.connected' );
} )->name( 'apple.callback' );

$connection = AppleOAuth::tokens()->store( $response );

if ( $response->profile->hasName() ) {
    $user = $request->user();
    $user->first_name ??= $response->profile->firstName;
    $user->last_name  ??= $response->profile->lastName;
    $user->save();
}

use ArtisanPackUI\AppleOAuth\OAuth\AppleClient;
use ArtisanPackUI\AppleOAuth\OAuth\AppleCredentials;

$client = AppleOAuth::client( new AppleCredentials(
    clientId: 'com.acme.app.web', teamId: 'ABCDE12345', keyId: 'XXXXXXXXXX',
    privateKey: $pem, redirectUri: 'https://broker.example.com/oauth/apple/callback',
) );

$url = $client->authorizationUrl( $state, [ 'name', 'email' ], $nonce );

AppleClient::verifyState( $expectedState, $request->input( 'state', '' ) );
$tokens = $client->exchangeCode( $request->input( 'code' ), $expectedNonce, $request->input( 'user' ) );

$refreshed = $client->refresh( $refreshToken );

return response()->json( $tokens->toArray() ); // the broker's wire shape

use ArtisanPackUI\Hooks\Facades\Filter;

// Reserved for when Apple issues new scopes. Do NOT register a made-up scope
// against production Apple today — Apple will reject the whole authorization.
Filter::add( 'ap.apple-oauth.scopes', function ( array $scopes ): array {
    // $scopes[] = '<future-apple-scope>';
    return $scopes;
} );

use ArtisanPackUI\AppleOAuth\Facades\AppleOAuth;

$connection = $user->appleConnection; // however you load it

$response = AppleOAuth::manager()
    ->request( $connection )
    ->acceptJson()
    ->get( 'https://caldav.icloud.com/...' );

$token = AppleOAuth::manager()->tokens()->accessTokenFor( $connection );

use ArtisanPackUI\AppleOAuth\Contracts\TokenProvider;
use ArtisanPackUI\AppleOAuth\Models\AppleConnection;

public function __construct( protected TokenProvider $apple ) {}

public function fetch( AppleConnection $connection ): array
{
    $token = $this->apple->accessTokenFor( $connection );
    // ...
}

AppleOAuth::clientSecret()->forget();
bash
php artisan migrate
bash
php artisan vendor:publish --tag=apple-oauth-migrations
bash
php artisan vendor:publish --tag=apple-oauth-config