kolovious/melisocialite

Mercadolibre Laravel Socialite 集成

v0.1.13 2017-07-24 10:54 UTC

This package is auto-updated.

Last update: 2024-09-08 07:22:18 UTC


README

许可证

Mercadolibre Laravel Socialite 是一个开源软件,使用 MIT 许可证授权

安装

composer require kolovious/meli-socialite

配置

在安装 Socialite 库后,在你的 config/app.php 配置文件中 Socialite 服务提供者之后注册 Kolovious\MeliSocialite\MeliSocialiteServiceProvider

'providers' => [

    // Other service providers...
    Laravel\Socialite\SocialiteServiceProvider::class,
    
    Kolovious\MeliSocialite\MeliSocialiteServiceProvider::class,
    
],

此外,还提供了 Meli 门面,可用于与 API 进行操作

'alias' => [
    // Other alias...
    
    'Meli' => Kolovious\MeliSocialite\Facade\Meli::class,
    
],

您还需要添加应用程序使用的 OAuth 服务的凭证。这些凭证应放置在您的 config/services.php 配置文件中

'meli' => [
    'client_id' => 'your-meli-app-id',
    'client_secret' => 'your-meli-secret-code',
    'redirect' => 'http://your-callback-url',
],

基本用法

接下来,您已准备好进行用户身份验证!您需要两个路由:一个用于将用户重定向到 OAuth 提供商,另一个用于在身份验证后接收提供者的回调。我们将使用 Socialite 门面访问 Socialite

<?php

namespace App\Http\Controllers;

use Socialite;

class AuthController extends Controller
{
    /**
     * Redirect the user to the Meli authentication page.
     *
     * @return Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('meli')->redirect();
    }

    /**
     * Obtain the user information from Meli.
     *
     * @return Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('meli')->user();

        // $user->token;
    }
}

redirect 方法负责将用户发送到 OAuth 提供商,而 user 方法将读取传入的请求并从提供者检索用户信息。

当然,您需要定义到您的控制器方法的路由

Route::get('auth/meli', 'Auth\AuthController@redirectToProvider');
Route::get('auth/meli/callback', 'Auth\AuthController@handleProviderCallback');

检索用户详细信息

一旦您有了用户实例,您就可以获取更多关于该用户的信息

$user = Socialite::driver('meli')->user();

// Tokens & Expire time
$token         = $user->token;
$refresh_token = $user->refresh_token;
$expires_at    = $user->expires_at; // UNIX TIMESTAMP

// Methods from Socialite User 
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();

// Raw Data
$user->user // Provided by Meli

使用门面进行 API 调用。

// Items from User ( ALL ) 
$offset = 0;
$call= "/users/".$user_id."/items/search";
$result = Meli::get($call, ["offset"=>$offset, 'access_token'=>$access_token]);

// Update Item Description
// Will use the saved access_token in the MeliManager object.
$result = Meli::withToken()->put('/items/'.$item_id.'/description', [ 'text' => $this->description ]); 

or

// Will save this token for future uses. Same as above.
$result = Meli::withToken($token)->put('/items/'.$item_id.'/description', [ 'text' => $this->description ]);

or

// Will use the Access Token in the Auth user, and save it for future uses. You can call withToken() the next time and it will work as espected
$result = Meli::withAuthToken()->put('/items/'.$item_id.'/description', [ 'text' => $this->description ]);