Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests. #859

Merged
merged 2 commits into from
Aug 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
* with this source code in the file LICENSE.
*/

namespace EasyWeChat\MiniProgram\Encryption;
namespace EasyWeChat\MiniProgram;

use EasyWeChat\Kernel\Encryptor as BaseEncryptor;
use Exception;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Kernel\Support\AES;

/**
* Class Encryptor.
Expand All @@ -34,19 +35,20 @@ class Encryptor extends BaseEncryptor
*/
public function decryptData($sessionKey, $iv, $encrypted)
{
try {
$decrypted = openssl_decrypt(
base64_decode($encrypted, true), 'aes-128-cbc', base64_decode($sessionKey, true),
OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, base64_decode($iv, true)
);
} catch (Exception $e) {
throw new EncryptionException($e->getMessage(), BaseEncryptor::ERROR_DECRYPT_AES);
}
$decrypted = AES::decrypt(
base64_decode($encrypted, true),
base64_decode($sessionKey, true),
base64_decode($iv, true),
OPENSSL_NO_PADDING
);

$result = $this->pkcs7Unpad($decrypted, $this->blockSize);
$content = json_decode($result, true);

if (is_null($result = json_decode($this->decode($decrypted), true))) {
throw new EncryptionException('ILLEGAL_BUFFER', BaseEncryptor::ILLEGAL_BUFFER);
if ($content['watermark']['appid'] !== $this->appId) {
throw new RuntimeException('Invalid appId.', static::ERROR_INVALID_APP_ID);
}

return $result;
return $content;
}
}
30 changes: 2 additions & 28 deletions src/MiniProgram/TemplateMessage/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
*/
class Client extends BaseClient
{
const API_SEND = 'cgi-bin/message/wxopen/template/send';

/**
* {@inheritdoc}.
*/
Expand All @@ -32,36 +34,8 @@ class Client extends BaseClient
'emphasis_keyword' => '',
];

/**
* {@inheritdoc}.
*/
protected $defaults = [
'touser' => '',
'template_id' => '',
'form_id' => '',
'data' => [],
];

/**
* {@inheritdoc}.
*/
protected $required = ['touser', 'template_id', 'form_id'];

/**
* Send a template message.
*
* @param array $data
*
* @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
*
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function send($data = [])
{
$params = $this->formatMessage($data);

$this->restoreMessage();

return $this->httpPostJson('cgi-bin/message/wxopen/template/send', $params);
}
}
4 changes: 3 additions & 1 deletion src/OfficialAccount/TemplateMessage/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
*/
class Client extends BaseClient
{
const API_SEND = 'cgi-bin/message/template/send';

/**
* Attributes.
*
Expand Down Expand Up @@ -122,7 +124,7 @@ public function send($data = [])

$this->restoreMessage();

return $this->httpPostJson('cgi-bin/message/template/send', $params);
return $this->httpPostJson(static::API_SEND, $params);
}

/**
Expand Down
18 changes: 9 additions & 9 deletions src/OpenPlatform/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
*/
class Application extends ServiceContainer
{
const COMPONENT_LOGIN_PAGE = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage';

/**
* @var array
*/
Expand Down Expand Up @@ -95,19 +93,21 @@ public function miniProgram(string $appId, string $refreshToken, AuthorizerAcces
}

/**
* Return the url to redirect to authorization page.
* Return the pre-authorization login page url.
*
* @param string $callbackUrl
*
* @return string
*/
public function getRedirectUrl(string $callbackUrl): string
public function getPreAuthorizationUrl(string $callbackUrl): string
{
return self::COMPONENT_LOGIN_PAGE.'?'.http_build_query([
'component_appid' => $this['config']['app_id'],
'pre_auth_code' => $this->createPreAuthorizationCode()['pre_auth_code'],
'redirect_uri' => $callbackUrl,
]);
$queries = [
'component_appid' => $this['config']['app_id'],
'pre_auth_code' => $this->createPreAuthorizationCode()['pre_auth_code'],
'redirect_uri' => $callbackUrl,
];

return 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?'.http_build_query($queries);
}

/**
Expand Down
21 changes: 9 additions & 12 deletions src/OpenPlatform/Server/Guard.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

namespace EasyWeChat\OpenPlatform\Server;

use EasyWeChat\Kernel\Support\Collection;
use EasyWeChat\Kernel\Traits\Observable;
use EasyWeChat\OfficialAccount\Server\Guard as BaseGuard;
use EasyWeChat\OpenPlatform\Server\Handlers\Authorized;
use EasyWeChat\OpenPlatform\Server\Handlers\Unauthorized;
use EasyWeChat\OpenPlatform\Server\Handlers\UpdateAuthorized;
use EasyWeChat\OpenPlatform\Server\Handlers\VerifyTicketRefreshed;
use Symfony\Component\HttpFoundation\Response;

/**
* Class Guard.
Expand All @@ -33,23 +33,20 @@ class Guard extends BaseGuard
const EVENT_UPDATE_AUTHORIZED = 'updateauthorized';
const EVENT_COMPONENT_VERIFY_TICKET = 'component_verify_ticket';

/**
* {@inheritdoc}.
*/
protected function handleRequest(): array
protected function resolve(): Response
{
$this->registerHandlers();

$message = new Collection($this->getMessage());
$message = $this->getMessage();

return [
'to' => $message['FromUserName'],
'from' => $message['ToUserName'],
'response' => $this->dispatch($message->get('InfoType'), $message->toArray()),
];
if (isset($message['InfoType'])) {
$this->dispatch($message['InfoType'], $message);
}

return new Response(static::SUCCESS_EMPTY_RESPONSE);
}

protected function registerHandlers(): void
protected function registerHandlers()
{
$this->on(self::EVENT_AUTHORIZED, Authorized::class);
$this->on(self::EVENT_UNAUTHORIZED, Unauthorized::class);
Expand Down
69 changes: 69 additions & 0 deletions tests/MiniProgram/AppCode/ClientTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace EasyWeChat\Tests\MiniProgram\AppCode;

use EasyWeChat\MiniProgram\AppCode\Client;
use EasyWeChat\Tests\TestCase;

class ClientTest extends TestCase
{
protected $mockStream;

public function setUp()
{
parent::setUp();

$this->mockStream = \Mockery::mock(\Psr\Http\Message\StreamInterface::class, function ($mock) {
$mock->expects()->getBody()->andReturn('mock-body');
});
}

public function testGetAppCode()
{
$client = $this->mockApiClient(Client::class);

$client->expects()->requestRaw('wxa/getwxacode', 'POST', ['json' => [
'path' => 'foo-path',
'width' => 430,
'auto_color' => false,
'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
]])->andReturn($this->mockStream)->once();

$this->assertSame('mock-body', $client->getAppCode('foo-path'));
}

public function testGetAppCodeUnlimit()
{
$client = $this->mockApiClient(Client::class);

$client->expects()->requestRaw('wxa/getwxacodeunlimit', 'POST', ['json' => [
'scene' => 'scene',
'width' => 430,
'auto_color' => false,
'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
]])->andReturn($this->mockStream)->once();

$this->assertSame('mock-body', $client->getAppCodeUnlimit('scene'));
}

public function testCreateQrCode()
{
$client = $this->mockApiClient(Client::class);

$client->expects()->requestRaw('cgi-bin/wxaapp/createwxaqrcode', 'POST', ['json' => [
'path' => 'foo-path',
'width' => 430,
]])->andReturn($this->mockStream)->once();

$this->assertSame('mock-body', $client->createQrCode('foo-path'));
}
}
34 changes: 34 additions & 0 deletions tests/MiniProgram/Auth/AccessTokenTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace EasyWeChat\Tests\MiniProgram\Auth;

use EasyWeChat\Kernel\ServiceContainer;
use EasyWeChat\MiniProgram\Auth\AccessToken;
use EasyWeChat\Tests\TestCase;

class AccessTokenTest extends TestCase
{
public function testGetCredentials()
{
$app = new ServiceContainer([
'app_id' => 'mock-app-id',
'secret' => 'mock-secret',
]);
$token = \Mockery::mock(AccessToken::class, [$app])->makePartial()->shouldAllowMockingProtectedMethods();

$this->assertSame([
'grant_type' => 'client_credential',
'appid' => 'mock-app-id',
'secret' => 'mock-secret',
], $token->getCredentials());
}
}
Loading