hpdc / sdk
用于实现与HPDC API进行OAuth身份验证的简单PHP SDK。
v11.6
2023-02-10 09:46 UTC
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
- jetstreamlabs/pinte: ^1.0
README
PHP SDK旨在允许HPD协作API合作伙伴轻松地将API中使用的OAuth身份验证集成到其PHP应用程序中。
您必须成为现有的API合作伙伴才能使用该API
一旦您作为合作伙伴获得API访问权限,您就可以开始使用此SDK集成OAuth身份验证和令牌访问,或者您可以使用SDK作为指南自行开发。
安装
SDK使用composer管理依赖项,因此您需要确保您熟悉composer,以便安装并将其集成到您的应用程序中。
要安装SDK,请运行
composer require hpdc/sdk
这将下载SDK到您的vendor目录,并使用PSR-4自动加载约定设置自动加载。
用法
以下是将身份验证SDK集成到给定控制器的示例。此示例是Laravel控制器,但将其集成到您选择的框架中应该非常类似。
每个方法都有文档说明,请注意SDK需要PHP > 7.0,因此您是否可以自动类型提示类取决于您的框架。
<?php namespace App\Http\Controllers; use Hpdc\Authentication; use Illuminate\Http\Request; class HomeController extends Controller { /** * Authentication client. * * @var \Hpdc\Authentication */ protected $client; /** * Instantiate the controller. * * @param \Hpdc\Authentication $auth */ public function __construct(Authentication $auth) { // Set your local client property. $this->client = $auth; /* |-------------------------------------------------------------------------- | Set Required Configuration Variables |-------------------------------------------------------------------------- | | The Authentication SDK requires the API url, Client ID and Secret. You | can set them all in one chainable function, using whatever method | you've created to store them. */ $this->client->setUrl(config('api.url')) ->setCallback(config('api.callback')) ->setClient(config('api.credentials.client')) ->setSecret(config('api.credentials.secret')); } /** * Front facing of controller. * * @return response */ public function index() { return view('api'); } /** * Forget the API session and redirect. * * @return response */ public function forget() { // remove API token from session. session()->forget('api-token'); session()->forget('api'); return redirect('/'); } /** * Build the authorize query and redirect to API. * * @return response */ public function auth() { $url = $this->client->make(); return redirect($url); } /** * Send a token request and store the credentials in your session, * then redirect the user back to a selected page. * * @param \Illuminate\Http\Request $request * @return response */ public function callback(Request $request) { // code variable returned from OAuth // capture this from your request object $code = $request->code; // retrieve your token $response = $this->client->send($code); // store the token in your session session(['api' => $response]); session(['api-token' => $response['access_token']]); return redirect('/'); } }
如果您有任何疑问或担忧,请随时提出问题。