Skip to content

Commit

Permalink
Merge pull request #18 from AlexandreBellas/develop
Browse files Browse the repository at this point in the history
fix: corrigir tratamento de retorno da API quando há erro
  • Loading branch information
AlexandreBellas authored Apr 26, 2024
2 parents e4f7d29 + a8316bc commit f0c54b2
Show file tree
Hide file tree
Showing 49 changed files with 9,629 additions and 383 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ Vale destacar que o fluxo de criação e autorização do aplicativo **não é f
pela biblioteca**. Ou seja, a biblioteca somente recebe o `access_token` gerado
a partir do _endpoint_ `/token`. [Veja a referência](https://developer.bling.com.br/aplicativos#tokens-de-acesso).

Para entender na prática como a autenticação citada acima funciona, [veja o
projeto de demonstração](https://github.com/AlexandreBellas/bling-erp-api-php/tree/v1.13.1/demo).

## Entidades disponíveis

Todas as entidades do Bling atualmente são permitidas para interação. São elas:
Expand Down Expand Up @@ -99,5 +102,5 @@ vendor/phpunit/phpunit/phpunit -c phpunit.xml

## Contribuindo ao projeto

- [Guia de contribuição](https://github.com/AlexandreBellas/bling-erp-api-php/blob/v5.0.0/CONTRIBUTING.md)
- [Guia de contribuição](https://github.com/AlexandreBellas/bling-erp-api-php/blob/v1.13.1/CONTRIBUTING.md)
- [Apoie o projeto](https://www.paypal.com/donate/?hosted_button_id=G2NJKZ5MUMKBS)
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "alebatistella/bling-erp-api",
"description": "Pacote de integração com a API do Bling ERP",
"type": "library",
"version": "1.13.0",
"version": "1.13.1",
"license": "MIT",
"autoload": {
"psr-4": {
Expand Down
18 changes: 18 additions & 0 deletions demo/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml}]
indent_size = 2

[docker-compose.yml]
indent_size = 4
59 changes: 59 additions & 0 deletions demo/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost

APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US

APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database

BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=sqlite

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=null

CACHE_STORE=array
CACHE_PREFIX=

MEMCACHED_HOST=127.0.0.1

REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=log
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

VITE_APP_NAME="${APP_NAME}"
11 changes: 11 additions & 0 deletions demo/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
* text=auto eol=lf

*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php

/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
19 changes: 19 additions & 0 deletions demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode
32 changes: 32 additions & 0 deletions demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Projeto de demonstração

## Aplicativo no Bling

Crie um aplicativo para teste [como esta página descreve](https://developer.bling.com.br/aplicativos#introdu%C3%A7%C3%A3o).

É obrigatório que você crie com a URL de redirecionamento como `http://localhost:8000/auth`.

Além disso, para fins de teste, conceda a permissão para listar produtos.

## Execução

Crie um arquivo `.env` copiando o `.env.example` existente:

```bash
cp .env.example .env
```

Inicie o servidor executando:

```bash
php artisan serve
```

Abra no navegador a URL `http://localhost:8000` e siga o que é apresentado.

## Passo a passo

1. Insira o _client ID_ e o _client secret_;
2. Conceda as permissões pedidas;
3. O _token_ de acesso aparecerá em seu navegador em formato JSON. Além disso,
será feita uma listagem de seus produtos ilustrando o uso da biblioteca.
99 changes: 99 additions & 0 deletions demo/app/Http/Controllers/BlingController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

namespace App\Http\Controllers;

use AleBatistella\BlingErpApi\Bling;
use AleBatistella\BlingErpApi\Exceptions\BlingInternalException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class BlingController extends Controller
{
private string $tmpFile = "access.json";

public function renderHtmlPage()
{
return view('bling');
}

public function receiveCredentials(Request $request)
{
$clientId = $request->input('client_id');
$clientSecret = $request->input('client_secret');

if (is_null($clientId) || is_null($clientSecret)) {
return response()->json([
'message' => 'Envie o clientId e o clientSecret.'
], 400);
}

$baseUrl = 'https://www.bling.com.br';
$endpoint = 'Api/v3/oauth/authorize';
$state = "1234567890";
$redirectUri = 'http://localhost:8000/auth';

Storage::put($this->tmpFile, json_encode([
'clientId' => $clientId,
'clientSecret' => $clientSecret
]));

return response()->redirectTo(
"$baseUrl/$endpoint?response_type=code&client_id=$clientId&state=$state&redirect_uri=$redirectUri"
);
}

public function showAuthData(Request $request)
{
$code = $request->query('code');

if (is_null($code)) {
return response()->json([
'message' => 'É necessário que seja enviado o "code".'
], 400);
}

@[
'clientId' => $clientId,
'clientSecret' => $clientSecret
] = json_decode(Storage::get($this->tmpFile), true);
Storage::delete($this->tmpFile);

if (is_null($clientId) || is_null($clientSecret)) {
return response()->json([
'message' => 'clientId ou clientSecret não encontrados.'
], 500);
}

$authResponse = Http::asForm()
->withBasicAuth($clientId, $clientSecret)
->post('https://www.bling.com.br/Api/v3/oauth/token', [
'grant_type' => 'authorization_code',
'code' => $code,
]);

if (!$authResponse->ok()) {
return response()->json([
'message' => 'Não foi possível autenticar no Bling.'
], 500);
}

$authResponseContent = $authResponse->json();

// $accessToken é o que você precisa fornecer para a biblioteca! 😄
@['access_token' => $accessToken] = $authResponseContent;
if (is_null($accessToken)) {
return response()->json([
'message' => 'Não foi possível obter o token de requisição.'
], 500);
}

$bling = new Bling($accessToken);
$products = $bling->produtos->get();

return response()->json([
...$authResponseContent,
'products' => $products->toArray()
]);
}
}
8 changes: 8 additions & 0 deletions demo/app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace App\Http\Controllers;

abstract class Controller
{
//
}
24 changes: 24 additions & 0 deletions demo/app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}

/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
15 changes: 15 additions & 0 deletions demo/artisan
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env php
<?php

use Symfony\Component\Console\Input\ArgvInput;

define('LARAVEL_START', microtime(true));

// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';

// Bootstrap Laravel and handle the command...
$status = (require_once __DIR__.'/bootstrap/app.php')
->handleCommand(new ArgvInput);

exit($status);
17 changes: 17 additions & 0 deletions demo/bootstrap/app.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
2 changes: 2 additions & 0 deletions demo/bootstrap/cache/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!.gitignore
5 changes: 5 additions & 0 deletions demo/bootstrap/providers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
App\Providers\AppServiceProvider::class,
];
Loading

0 comments on commit f0c54b2

Please sign in to comment.