Skip to content

Commit

Permalink
Merge pull request #31 from wwenling/master
Browse files Browse the repository at this point in the history
开放平台代小程序实现登录
  • Loading branch information
kiss291323003 authored Aug 15, 2019
2 parents 4b7a443 + 7f57e7d commit bdfae3b
Show file tree
Hide file tree
Showing 8 changed files with 294 additions and 5 deletions.
71 changes: 71 additions & 0 deletions src/OpenPlatform/AccessToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
/**
* Created by PhpStorm.
* User: wwl
* Date: 2019/08/13
* Time: 12:19 AM
*/

namespace EasySwoole\WeChat\OpenPlatform;

use EasySwoole\HttpClient\Exception\InvalidUrl;
use EasySwoole\WeChat\Exception\RequestError;
use EasySwoole\WeChat\Utility\NetWork;
use EasySwoole\WeChat\Exception\OpenPlatformError;

/**
* 访问令牌管理
* Class AccessToken
* @package EasySwoole\WeChat\MiniProgram
*/
class AccessToken extends OpenPlatformBase
{

/**
* 获取访问令牌 默认刷新一次
* @param int $refreshTimes 获取失败的重试次数
* @return string|null
* @throws OpenPlatformError
* @throws RequestError
* @throws InvalidUrl
*/
public function getComponentAccessToken($refreshTimes = 1): ?string
{
if ($refreshTimes < 0) {
return null;
}
$data = $this->getOpenPlatform()->getConfig()->getStorage()->get('component_access_token');
if (!empty($data)) {
return $data;
} else {
$this->refresh();
return $this->getComponentAccessToken($refreshTimes - 1);
}
}

/**
* 刷新访问令牌
* @return string
* @throws OpenPlatformError
* @throws RequestError
* @throws InvalidUrl
*/
public function refresh(): string
{
$verifyTicket = $this->getOpenPlatform()->verifyTicket()->getTicket();
$config = $this->getOpenPlatform()->getConfig();
$data = [
'component_appid' => $config->getComponentAppId(),
'component_appsecret' => $config->getComponentAppSecret(),
'component_verify_ticket' => $verifyTicket
];
$responseArray = NetWork::postForJson(ApiUrl::API_COMPONENT_TOKEN, $data);
$ex = OpenPlatformError::hasException($responseArray);
if ($ex) {
throw $ex;
}
$token = $responseArray['component_access_token'];
$config->getStorage()->set('component_access_token', $token, time() + 7180);
return $token;
}
}
9 changes: 9 additions & 0 deletions src/OpenPlatform/ApiUrl.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ class ApiUrl
// 获取用户信息
const GET_USER_INFO = 'https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID';

/*
* 三方平台代替小程序 code 换取 session_key
* @see https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1492585163_FtTNA&token=&lang=
*/
const COMPONENT_AUTH_CODE2SESSION = 'https://api.weixin.qq.com/sns/component/jscode2session';

//获取第三方平台component_access_token
const API_COMPONENT_TOKEN = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';

public static function generateURL(string $baseUrl, array $data): string
{
foreach ($data as $key => $item) {
Expand Down
29 changes: 29 additions & 0 deletions src/OpenPlatform/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,33 @@ function authCheck(SnsAuthBean $authBean)
{

}

/**
* session2code
*
* @param string $code
* @return array
* @throws OpenPlatformError
* @throws RequestError
* @throws \EasySwoole\HttpClient\Exception\InvalidUrl
*/
public function session(string $code): array
{
$accessToken = $this->getOpenPlatform()->accessToken()->getComponentAccessToken();
$config = $this->getOpenPlatform()->getConfig();
$data = [
'appid' => $config->getAppId(),
'js_code' => $code,
'grant_type' => 'authorization_code',
'component_appid' => $config->getComponentAppId(),
'component_access_token' => $accessToken,
];
$responseArray = NetWork::getForJson(ApiUrl::COMPONENT_AUTH_CODE2SESSION, $data);
$ex = OpenPlatformError::hasException($responseArray);
if ($ex) {
throw $ex;
}

return $responseArray;
}
}
28 changes: 28 additions & 0 deletions src/OpenPlatform/Encryptor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/**
* Created by PhpStorm.
* User: wwl
* Date: 2019/082/13
* Time: 11:39 AM
*/

namespace EasySwoole\WeChat\OpenPlatform;


class Encryptor extends OpenPlatformBase
{
/**
* decryptData
*
* @param string $sessionKey
* @param string $iv
* @param string $encryptedData
* @return array
*/
public function decryptData(string $sessionKey, string $iv, string $encryptedData): array
{
$jsonString = openssl_decrypt(base64_decode($encryptedData), "aes-128-cbc", base64_decode($sessionKey), OPENSSL_RAW_DATA, base64_decode($iv));
return json_decode($jsonString, true);
}
}
42 changes: 42 additions & 0 deletions src/OpenPlatform/OpenPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,46 @@ public function getConfig(): OpenPlatformConfig
{
return $this->config;
}

/**
* accessToken
*
* @return AccessToken
*/
public function accessToken(): AccessToken
{
if (!isset($this->accessToken)) {
$this->accessToken = new AccessToken($this);
}

return $this->accessToken;
}

/**
* VerifyTicket
*
* @return VerifyTicket
*/
public function verifyTicket(): VerifyTicket
{
if (!isset($this->verifyTicket)) {
$this->verifyTicket = new VerifyTicket($this);
}

return $this->verifyTicket;
}

/**
* encryptor
*
* @return Encryptor
*/
public function encryptor(): Encryptor
{
if (!isset($this->encryptor)) {
$this->encryptor = new Encryptor($this);
}

return $this->encryptor;
}
}
40 changes: 40 additions & 0 deletions src/OpenPlatform/OpenPlatformConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,44 @@ public function setTempDir($tempDir): OpenPlatformConfig
$this->tempDir = $tempDir;
return $this;
}

/**
* 获取第三方平台appid
* @return mixed
*/
public function getComponentAppId()
{
return $this->componentAppId;
}

/**
* 设置第三方平台appid
* @param mixed
* @return OpenPlatformConfig
*/
public function setComponentAppId($componentAppId): OpenPlatformConfig
{
$this->componentAppId = $componentAppId;
return $this;
}

/**
* 获取第三方平台appsecret
* @return mixed
*/
public function getComponentAppSecret()
{
return $this->componentAppSecret;
}

/**
* 设置第三方平台appsecret
* @param mixed
* @return OpenPlatformConfig
*/
public function setComponentAppSecret($componentAppSecret): OpenPlatformConfig
{
$this->componentAppSecret = $componentAppSecret;
return $this;
}
}
57 changes: 57 additions & 0 deletions src/OpenPlatform/VerifyTicket.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
/**
* Created by PhpStorm.
* User: wwl
* Date: 2019/082/13
* Time: 11:39 AM
*/

namespace EasySwoole\WeChat\OpenPlatform;

use EasySwoole\WeChat\Exception\Exception;

/**
* component_verify_ticket 微信服务器 每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,用于获取第三方平台接口调用凭据
* Class AccessToken
* @package EasySwoole\WeChat\OpenPlatform
*/

class VerifyTicket extends OpenPlatformBase
{

/**
* set component_verify_ticket
*/
public function setTicket(string $ticket)
{
$cacheKey = $this->getCacheKey();
$this->getOpenPlatform()->getConfig()->getStorage()->set($cacheKey, $ticket, time() + 580);

if (!$this->getOpenPlatform()->getConfig()->getStorage()->get($this->getCacheKey())) {
throw new Exception('Failed to cache verify ticket');
}

return $this;

}

/**
* get component_verify_ticket
* @return string
*/
public function getTicket(): string
{
if ($cached = $this->getOpenPlatform()->getConfig()->getStorage()->get($this->getCacheKey())) {
return $cached;
}
}

/**
* 获取 cache key
* @return string
*/
protected function getCacheKey(): string
{
return 'wechat.open_platform.verify_ticket.'.$this->getOpenPlatform()->getConfig()->getAppId();
}
}
23 changes: 18 additions & 5 deletions src/Utility/NetWork.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ static function get(string $url): Response
return (new HttpClient($url))->setTimeout(self::$TIMEOUT)->get();
}

/**
* 发起一次Get请求并获得返回
* @param string $url
* @param array $data
* @return Response
* @throws InvalidUrl
*/
static function getByArray(string $url, array $data): Response
{
return (new HttpClient($url))->setTimeout(self::$TIMEOUT)->setQuery($data)->get();
}

/**
* 返回内容进行Json解析
Expand All @@ -50,9 +61,13 @@ static function get(string $url): Response
* @throws InvalidUrl
* @throws RequestError
*/
static function getForJson(string $url): array
static function getForJson(string $url, array $data = []): array
{
return self::parserJson(self::get($url));
if ($data) {
return self::parserJson(self::getByArray($url, $data));
} else {
return self::parserJson(self::get($url));
}
}

/**
Expand All @@ -65,9 +80,7 @@ static function getForJson(string $url): array
*/
static function post(string $url, $data = null)
{
$client = new HttpClient($url);
$client->setTimeout(self::$TIMEOUT);
return $client->postJson($data);
return self::postJson($url, $data);
}

/**
Expand Down

0 comments on commit bdfae3b

Please sign in to comment.