一个简单的PHP微信OAuth2.0登录客户端
文章目录
想法
最近公司要求接入微信,支付宝三方登录, 于是我萌生了一个想法,贡献一个开箱即用的OAuth2.0的登录客户端,方便以后使用。
基本思想
通过这次经历学到了不少东西,包括git,github的使用, 面向对象程序设计,单元测试等等,感觉受益颇多。
也认识到想要把所有知识融会贯通起来,创建一个好的项目是很不容易的。还是要多实践才能出真知
实现
基本抽象
Provider 服务提供者 例如 支付宝,微信等OAuth服务端
<?php
namespace CnOAuth\Provider;
use CnOAuth\AccessToken\AccessToken;
use Psr\Http\Message\ResponseInterface;
/**
* OAuth2 服务提供者接口
*/
interface Provider
{
/**
* 获取 authorizing 地址
*/
public function getBaseAuthorizationUrl();
/**
* 获取 access token 地址
*
* @param array
*/
public function getBaseAccessTokenUrl(array $params);
/**
* 获取 用户详细信息 地址
*
* @param AccessToken access token
*/
public function getResourceOwnerDetailsUrl(AccessToken $token);
/**
* 获取默认scope
*/
public function getDefaultScopes();
/**
* Checks a provider response for errors.
*
* @throws IdentityProviderException
* @param array $response
* @param array|string $data Parsed response data
* @return void
*/
public function checkResponse($response, $data);
/**
* 生成用户详细信息对象
*
* @param array $response
* @param AccessToken $token
* @return ResourceOwnerInterface
*/
public function createResourceOwner(array $response, AccessToken $token);
}
授权类型 旨在区分各种不同的授权类型 如 authorization, password 等
<?php
namespace CnOAuth\Grant;
abstract class AbstractGrant
{
/**
* Returns the name of this grant, eg. 'grant_name', which is used as the
* grant type when encoding URL query parameters.
*
* @return string
*/
abstract protected function getName();
/**
* Prepares an access token request's parameters by checking that all
* required parameters are set, then merging with any given defaults.
*
* @param array $defaults
* @param array $options
* @return array
*/
public function prepareRequestParameters(array $defaults, array $options)
{
$defaults['grant_type'] = $this->getName();
$provided = array_merge($defaults, $options);
$this->checkRequiredParameters($provided);
return $provided;
}
abstract protected function checkRequiredParameters(array $options);
}
使用
redirect.php
<?php
# 微信
$wechat = new \CnOAuth\Provider\WechatOfficialAccount([
'clientId' => 'you client id',
'clientSecret' => 'you client secret',
'redirectUri' => 'redirect uri'
]);
$url = $wechat->getAuthorizationUrl([
'scope' => $this->getDefaultScopes(),
'state' => 'state'
]);
header('Location: '.$url);
callback.php
# 微信
$wechat = new \CnOAuth\Provider\WechatOfficialAccount([
'clientId' => 'you client id',
'clientSecret' => 'you client secret',
'redirectUri' => 'redirect uri'
]);
$grant = $wechat->getGrant('authorization');
if ($grant->getCode()) {
$access_token = $wechat->getAccessToken($grant);
$owner = $wechat->getResourceOwner($access_token);
print_r($owner->toArray());
} else {
// 用户取消授权
}
希望有相同想法的一起完善,指教
项目地址CnOAuth
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论