salla/ouath2-merchant

Salla OAuth 2.0 客户端提供程序,用于 PHP League OAuth2-Client

2.0.3 2024-07-24 14:29 UTC

This package is auto-updated.

Last update: 2024-09-24 14:51:44 UTC


README

Logo

Salla OAuth 2.0 客户端

本包为 PHP 语言 OAuth 2.0 客户端 提供了 Salla OAuth 2.0 支持。
探索我们的博客

报告错误 · 请求功能 · </Salla 开发者>

概述

要使用此包,您需要拥有一个 Salla 客户端 ID 和客户端密钥。在文档中,这些分别称为 {client-id}{client-secret}

请按照 Salla 指令 创建所需的凭证。

OAuth 工作流程

OAuth Workflow

安装

您可以通过 Composer 安装此包

composer require salla/ouath2-merchant

(返回顶部)

使用

授权码流

<?php

require_once './vendor/autoload.php';

use Salla\OAuth2\Client\Provider\Salla;

$provider = new Salla([
    'clientId'     => '{client-id}', // The client ID assigned to you by Salla
    'clientSecret' => '{client-secret}', // The client password assigned to you by Salla
    'redirectUri'  => 'https://yourservice.com/callback_url', // the url for current page in your service
]);

/**
 * In case the current callback url doesn't have an authorization_code
 * Let's redirect the merchant to the installation/authorization app workflow
 */
if (empty($_GET['code'])) {
    $authUrl = $provider->getAuthorizationUrl([
        'scope' => 'offline_access',
        //Important: If you want to generate the refresh token, set this value as offline_access
    ]);

    header('Location: '.$authUrl);
    exit;
}

/**
 * The merchant completes the installation/authorization app workflow
 * And the callback url has an authorization_code as a parameter
 * Let's exchange the authorization_code with access token
 */
try {
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    //
    // ## Access Token
    //
    // You should store the access token
    // which may use in authenticated requests against the Salla's API
    echo 'Access Token: '.$token->getToken()."<br>";

    //
    // ## Refresh Token
    //
    // You should store the refresh token somewhere in your system because the access token expired after 14 days,
    // so you can use the refresh token after that to generate a new access token without asking any access from the merchant
    //
    // $token = $provider->getAccessToken(new RefreshToken(), ['refresh_token' => $token->getRefreshToken()]);
    //
    echo 'Refresh Token: '.$token->getRefreshToken()."<br>";

    //
    // ## Expire date
    //
    // This helps you to know when the access token will be expired
    // so before that date, you should generate a new access token using the refresh token
    echo 'Expire Date : '.$token->getExpires()."<br>";

    //
    // ## Merchant Details
    //
    // Using the access token, we may look up details about the merchant.
    // --- Same request in Curl ---
    // curl --request GET --url 'https://accounts.salla.sa/oauth2/user/info' --header 'Authorization: Bearer <access-token>'

    /** @var \Salla\OAuth2\Client\Provider\SallaUser $user */
    $user = $provider->getResourceOwner($token);

    /**
     *  {
     *    "id": 1771165749,
     *    "name": "Test User",
     *    "email": "testuser@email.partners",
     *    "mobile": "+966500000000",
     *    "role": "user",
     *    "created_at": "2021-12-31 11:36:57",
     *    "merchant": {
     *      "id": 1803665367,
     *      "username": "dev-j8gtzhp59w3irgsw",
     *      "name": "dev-j8gtzhp59w3irgsw",
     *      "avatar": "https://i.ibb.co/jyqRQfQ/avatar-male.webp",
     *      "store_location": "26.989000873354787,49. 62477639657287",
     *      "plan": "special",
     *      "status": "active",
     *      "domain": "https://salla.sa/YOUR-DOMAIN-NAME",
     *      "created_at": "2021-12-31 11:36:57"
     *    }
     *  }
     */
    var_export($user->toArray());

    echo 'User ID: '.$user->getId()."<br>";
    echo 'User Name: '.$user->getName()."<br>";
    echo 'Store ID: '.$user->getStoreID()."<br>";
    echo 'Store Name: '.$user->getStoreName()."<br>";


    //
    // 🥳
    //
    // You can now save the access token and refresh the token in your database
    // with the merchant details and redirect him again to Salla dashboard (https://s.salla.sa/apps)


    //
    // ## Access to authenticated APIs for the merchant
    //
    // You can also use the same package to call any authenticated APIs for the merchant
    // Using the access token, information can be obtained from a list of endpoints.
    //
    // --- Same request in Curl ---
    // curl --request GET --url 'https://api.salla.dev/admin/v2/orders' --header 'Authorization: Bearer <access-token>'
    $response = $provider->fetchResource(
        'GET',
        'https://api.salla.dev/admin/v2/orders',
        $token->getToken()
    );

    var_export($response);

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
    // Failed to get the access token or merchant details.
    // show an error message to the merchant with good UI
    exit($e->getMessage());
}

(返回顶部)

刷新令牌

刷新令牌仅提供给请求离线访问的应用程序。您可以通过在 getAuthorizationUrl() 请求中传递范围选项来指定离线访问。

use Salla\OAuth2\Client\Provider\Salla;

$provider = new Salla([
    'clientId' => '{client-id}',
    'clientSecret' => '{client-secret}',
]);

$refreshToken = 'FromYourStoredData';
$token = $provider->getAccessToken('refresh_token', ['refresh_token' => $refreshToken]);

在 Laravel 中使用 Salla OAuth2

您可以使用本包提供的 facade 辅助程序无缝地将 Salla OAuth2 集成到 Laravel 中。以下是操作方法

首先,在您的 Laravel 项目中使用 facade 辅助程序

use \Salla\OAuth2\Client\Facade\SallaOauth;

// Generate the authorization URL with the required scope
$authUrl = SallaOauth::getAuthorizationUrl([
    'scope' => 'offline_access',
    // Important: Set this value to 'offline_access' to generate a refresh token
]);

// Retrieve the access token using the authorization code
$token = SallaOauth::getAccessToken('authorization_code', [
  'code' => request()->get('code')
]);

要配置 OAuth2 服务,请在您的 .env 文件中设置必要的环境变量

SALLA_OAUTH_CLIENT_ID=""
SALLA_OAUTH_CLIENT_SECRET=""
SALLA_OAUTH_CLIENT_REDIRECT_URI=""

这些设置确保您的 Laravel 应用程序可以正确地与 Salla OAuth2 服务通信,从而允许您高效地处理身份验证和获取访问令牌。

将 Salla OAuth2 用作 Laravel 守卫

在集成 Salla OAuth2 进行身份验证时,您可能需要在请求过程中验证商家的访问令牌并检索用户信息。

为此,将 \Salla\OAuth2\Client\Http\OauthMiddleware 中间件添加到您希望保护的路由中。此中间件确保用户通过 Salla OAuth2 登录。

请注意,此中间件仅验证用户身份验证。根据需要,必须单独实施额外的授权检查。该包方便地将资源所有者信息存储为请求属性,从而便于进一步的授权。

在添加中间件到您的路由后,您可以使用以下代码访问当前认证用户

auth()->guard('salla-oauth');
// To check if a user is authenticated:
auth()->guard('salla-oauth')->check();
// To get the authenticated user's ID:
auth()->guard('salla-oauth')->id();
// To get the merchant information of the authenticated user:
auth()->guard('salla-oauth')->merchant();

通过利用此中间件,您确保了对路由的安全访问,同时保持了额外的授权要求的灵活性。

测试

composer test

(返回顶部)

支持

团队一直在这里为您提供帮助。遇到问题了吗?想要报告一个错误?您可以在GitHub上提交一个,使用问题跟踪器。如果您还有任何问题,请通过加入Telegram上的全球开发者社区或通过支持邮箱联系我们。

贡献

贡献使开源社区成为一个如此美妙的学习、灵感和创造的地方。您所做的一切贡献都备受赞赏。

如果您有改进这点的建议,请fork仓库并创建一个pull请求。您也可以简单地创建一个带有“增强”标签的问题。别忘了为项目加星!再次感谢!

  1. fork项目
  2. 创建您的功能分支(git checkout -b feature/AmazingFeature
  3. 提交您的更改(git commit -m '添加一些AmazingFeature'
  4. 推送到分支(git push origin feature/AmazingFeature
  5. 打开Pull Request

(返回顶部)

安全

如果您发现任何安全相关的问题,请通过security@salla.sa发送邮件,而不是使用问题跟踪器。

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件

(返回顶部)