Skip to content

Commit

Permalink
Migrated To Saloon SDK Package
Browse files Browse the repository at this point in the history
  • Loading branch information
Combind committed Apr 2, 2023
1 parent c699c8d commit 24f8f56
Show file tree
Hide file tree
Showing 14 changed files with 250 additions and 258 deletions.
17 changes: 7 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ return [
| Version of the auth can be OAuth2 or BasicAuth. OAuth2 is the default value.
|
*/
'version' => 'OAuth2', //or BasicAuth
'version' => env('MAUTIC_VERSION', 'OAuth2'), //or BasicAuth

/*
* Base URL of the Mautic instance
Expand Down Expand Up @@ -95,7 +95,7 @@ Within Mautic, go to the Configuration page (located in the Settings menu) and u

After saving the configuration, go to the API Credentials page (located in the Settings menu) and create a new client.

Enter the callback/redirect URI (Should be `https://your-domain.com/login/mautic/callback`). Click Apply, then copy the Client ID and Client Secret to the .env file.
Enter the callback/redirect URI (Should be `https://your-domain.com/integration/mautic/callback`). Click Apply, then copy the Client ID and Client Secret to the .env file.

This is an example of .env file:

Expand All @@ -104,7 +104,7 @@ MAUTIC_VERSION="OAuth2"
MAUTIC_BASE_URL="https://mautic-domain.com"
MAUTIC_PUBLIC_KEY="XXXXXXXXXXXXXXXX"
MAUTIC_SECRET_KEY="XXXXXXXXXX"
MAUTIC_CALLBACK="https://your-domain.com/login/mautic/callback"
MAUTIC_CALLBACK="https://your-domain.com/integration/mautic/callback"
```

## BasicAuth Mautic Setup
Expand All @@ -119,28 +119,25 @@ MAUTIC_PASSWORD="password"
## Registering Application (Only OAuth2 Authentication)
In order to register you application with mautic ping this url one time to register your application.
```url
https://your-domain.com/login/mautic
https://your-domain.com/integration/mautic
```

## Usage

```php
use Combindma\Mautic\Facades\Mautic;

Mautic::subscribe('email@gmail.com');
Mautic::contacts()->create('email@gmail.com');

//or
$params = array(
'firstname' => 'bullet',
'lastname' => 'proof',
);
Mautic::subscribe('email@gmail.com', $params);
Mautic::contacts()->create('email@gmail.com', $params);

//Delete a contact
Mautic::unsubscribe(567);//ID contact

//build your request to use it accordingly to Mautic documentation
$response = Mautic::buildRequest()?->get($this->endpoint.'contacts/'.$id);
Mautic::contacts()->delete(567);//ID contact
```

Please refer to [Documentation](https://developer.mautic.org).
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"php": "^8.1",
"guzzlehttp/guzzle": "^7.5",
"illuminate/contracts": "^10.0",
"sammyjo20/saloon": "^2.5",
"spatie/laravel-package-tools": "^1.14.0"
},
"require-dev": {
Expand Down
4 changes: 2 additions & 2 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
use Illuminate\Support\Facades\Route;

Route::group(['middleware' => ['web']], function () {
Route::get('login/mautic', [MauticController::class, 'login']);
Route::get('login/mautic/callback', [MauticController::class, 'callback']);
Route::get('integration/mautic', [MauticController::class, 'login']);
Route::get('integration/mautic/callback', [MauticController::class, 'callback']);
});
14 changes: 0 additions & 14 deletions src/Exceptions/UnauthorizedStateIsReturned.php

This file was deleted.

9 changes: 6 additions & 3 deletions src/Http/Controllers/MauticController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@

namespace Combindma\Mautic\Http\Controllers;

use Combindma\Mautic\Facades\Mautic;
use Combindma\Mautic\MauticAuthConnector;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class MauticController extends Controller
{
public function login()
{
return Mautic::authorize();
$authConnector = new MauticAuthConnector;

return $authConnector->authorize();
}

public function callback(Request $request)
{
Mautic::requestToken($request);
$authConnector = new MauticAuthConnector;
$authConnector->requestToken($request);

return view('mautic::index');
}
Expand Down
190 changes: 25 additions & 165 deletions src/Mautic.php
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -2,205 +2,65 @@

namespace Combindma\Mautic;

use Combindma\Mautic\Exceptions\UnableToGetMauticTokensException;
use Combindma\Mautic\Exceptions\UnableToHandleCallbackMauticUrl;
use Combindma\Mautic\Exceptions\UnableToStoreMauticDataException;
use Combindma\Mautic\Exceptions\UnauthorizedStateIsReturned;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;

class Mautic
use Combindma\Mautic\Resources\ContactResource;
use Combindma\Mautic\Traits\MauticStorage;
use Saloon\Contracts\Authenticator;
use Saloon\Http\Auth\BasicAuthenticator;
use Saloon\Http\Auth\TokenAuthenticator;
use Saloon\Http\Connector;

class Mautic extends Connector
{
use Traits\MauticApi;
use MauticStorage;

private string $version;
private readonly string $version;

private readonly string $baseUrl;

private readonly string $clientKey;

private readonly string $clientSecret;

private readonly string $callback;

private readonly string $username;

private readonly string $password;

private readonly string $apiUrl;

private string $endpoint;

private readonly string $fileName;

private bool $apiEnabled;

public function __construct()
{
$this->version = config('mautic.version');
$this->baseUrl = config('mautic.baseUrl');
$this->clientKey = config('mautic.clientKey');
$this->clientSecret = config('mautic.clientSecret');
$this->callback = config('mautic.callback');
$this->username = config('mautic.username');
$this->password = config('mautic.password');
$this->apiUrl = $this->baseUrl.'/oauth/v2/';
$this->endpoint = $this->baseUrl.'/api/';
$this->fileName = config('mautic.fileName');
$this->apiEnabled = config('mautic.apiEnabled');
}

public function getVersion(): string
{
return $this->version;
}

public function getBaseUrl(): string
{
return $this->baseUrl;
}

public function getClientKey(): string
{
return $this->clientKey;
}

public function getClientSecret(): string
{
return $this->clientSecret;
}

public function getCallback(): string
{
return $this->callback;
}

public function getUsername(): string
{
return $this->username;
}

public function getPassword(): string
{
return $this->password;
}

public function isApiEnabled(): bool
{
return $this->apiEnabled;
}

public function getFileName(): string
{
return $this->fileName;
}

public function disable(): void
{
$this->apiEnabled = false;
}

public function enable(): void
public function resolveBaseUrl(): string
{
$this->apiEnabled = true;
return $this->baseUrl.'/api';
}

//Obtain Authorization Code
public function authorize(): \Illuminate\Http\RedirectResponse
public function contacts(): ContactResource
{
//The state is recommended to prevent CSRF attacks.
$state = md5(time().mt_rand());
//It should be a uniquely generated string and stored locally in session. to be compared with the returned value.
Session::put('mautic.oauth_state', $state);
$authUrl = $this->apiUrl.'authorize'.'?client_id='.$this->clientKey.'&redirect_uri='.urlencode($this->callback).'&state='.$state.'&response_type=code&grant_type=authorization_code';
//Redirect the user to the authorize endpoint oauth/v2/authorize:
return Redirect::away($authUrl);
}

//Replace with an Access Token
public function requestToken(Request $request): void
{
$oauth_session = $request->session()->pull('mautic');

if (! $request->input('code') && ! $request->input('state')) {
throw new UnableToHandleCallbackMauticUrl();
}

if (empty($oauth_session)) {
throw new UnauthorizedStateIsReturned();
}

if ($request->input('state') != $oauth_session['oauth_state']) {
throw new UnauthorizedStateIsReturned();
}

$response = Http::post($this->apiUrl.'token', [
'client_id' => $this->clientKey,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->callback,
'grant_type' => 'authorization_code',
'code' => $request->input('code'),
]);

if ($response->failed()) {
Log::error('Mautic error: '.$response->body());
}

$this->storeAccessToken($response->json());
return new ContactResource($this);
}

//Refresh Tokens
private function refreshToken(): array
protected function defaultAuth(): ?Authenticator
{
$response = Http::post($this->apiUrl.'token', [
'client_id' => $this->clientKey,
'client_secret' => $this->clientSecret,
'refresh_token' => $this->getAccessToken()['refresh_token'],
'redirect_uri' => $this->callback,
'grant_type' => 'refresh_token',
]);

if ($response->failed()) {
Log::error('Mautic error: '.$response->body());
throw new Exception($response->body());
if ($this->version === 'BasicAuth') {
return new BasicAuthenticator($this->username, $this->password);
}

$this->storeAccessToken($response->json());

return $response->json();
}
$authenticator = $this->getToken();

//Store mautic data in local storage
private function storeAccessToken(array $accessToken): void
{
if (! Storage::disk('local')->put(config('mautic.fileName', 'mautic.json'), json_encode($accessToken))) {
throw new UnableToStoreMauticDataException();
if ($authenticator->hasExpired() === true) {
$authConnector = new MauticAuthConnector;
$authenticator = $authConnector->refreshAccessToken($authenticator);
$authConnector->updateAuthenticator($authenticator);
}
}

//Get mautic data from local storage
/*
* access_token
* expires_in
* refresh_token
*/
private function getAccessToken(): array
{
if ($accessToken = Storage::disk('local')->json($this->fileName)) {
return $accessToken;
}

throw new UnableToGetMauticTokensException();
return new TokenAuthenticator($authenticator->getAccessToken());
}

//Check AccessToken Expiration Time
private function checkExpirationTime($expireTimestamp): bool
public function isApiEnabled(): bool
{
return time() > time() + $expireTimestamp;
return $this->apiEnabled;
}
}

0 comments on commit 24f8f56

Please sign in to comment.