diff --git a/README.md b/README.md index 50bc324..52d1830 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,192 @@ -# laravel-mautic-api +## Mautic API in Laravel/Lumen. Free and Open Source Marketing Automation API + +## Requirements +* PHP 5.5.* or newer +* cURL support + +## Mautic Setup +The API must be enabled in Mautic. Within Mautic, go to the Configuration page (located in the Settings menu) and under API Settings enable +Mautic's API. You can also choose which OAuth2 protocol to use here. 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 that the request will be sent from. Click Apply +then copy the Client ID and Client Secret to the application that will be using the API. + +## Installation + +First, you'll need to require the package with Composer: +```sh +composer require princealikhan/laravel-mautic-api +``` +Aftwards, run `composer update` from your command line. + +Then, update `config/app.php` by adding an entry for the service provider. + +```php +'providers' => [ + // ... + 'Princealikhan\Mautic\MauticServiceProvider', +], +``` +Then, register class alias by adding an entry in aliases section +```php +'aliases' => [ + //..... + 'Mautic' => 'Princealikhan\Mautic\Facades\Mautic', +], +``` +Finally, from the command line run `php artisan vendor:publish` to publish the default configuration file. +This will publish a configuration file name `mautic.php` ,`consumer migration` and `consumer model`. + +Run `php artisan migrate` migration command to create consumer table in your database. + +## Configuration +You need to add your `client id`, `client secret` and `callback url` in `mautic.php` file that is found in your applications `config` directory. + +## Authorization +This Library only support OAuth2 Authorization +you must need to create a OAuth2 client in order to use api. + +## Registering Application +In order to register you application with mautic ping this url this is one time registration. +```url +http://your-app/mautic/application/register +``` + + +# Usage +Add Mautic Facade in your controller. +```php +use Mautic; +``` +#### Send a request to mautic ( Example ) +Create a new contact in mautic. +```php +$params = array( + 'firstname' => 'Prince', + 'lastname'=> 'Ali Khan', + 'email' => 'princealikhan08@gmail.com' +); + +Mautic::request('POST','contacts/new',$param); +``` +Get List of all contacts +```php +Mautic::request('GET','contacts'); +``` +Get a unique contact +```php +Mautic::request('GET','contacts/1'); +//where 1 is unique id for a contact. +``` + +Delete a contact +```php +Mautic::request('Delete','contacts/1/delete'); +``` +##### And many more endpoints support by mautic. +### List of Endpoints supported by Mautic. + +#### Contacts +```json +[ + "contacts", + "contacts/{id}", + "contacts/list/fields", + "contacts/list/owners", + "contacts/new", + "contacts/{id}/edit", + "contacts/{id}/delete", + "contacts/{id}/notes", + "contacts/{id}/segments", + "contacts/{id}/campaigns" +] +``` + +#### Assets +```json +[ + "assets", + "assets/{id}" +] +``` + +#### Campaigns +```json +[ + "campaigns", + "campaigns/{id}", + "campaigns/contact/{id}/add/{leadId}", + "campaigns/contact/{id}/remove/{leadId}" +] +``` + +#### Data +```json +[ + "data", + "data/{type}", +] +``` +#### Emails +```json +[ + "emails", + "emails/{id}", + "emails/{id}/send", + "emails/{id}/send/lead/{leadId}" +] +``` + +#### Forms +```json +[ + "forms", + "forms/{id}" +] +``` +#### Pages +```json +[ + "pages", + "pages/{id}" +] +``` +#### Points +```json +[ + "points", + "points/{id}", + "points/triggers", + "points/triggers/{id}" +] +``` +#### Reports +```json +[ + "reports", + "reports/{id}" +] +``` +#### Segments +```json +[ + "segments", + "segments/contact/{id}/add/{leadId}", + "segments/contact/{id}/remove/{leadId}" +] +``` +#### Users +```json +[ + "roles", + "roles/{id}", + "users", + "users/{id}", + "users/list/roles", + "users/self", + "users/{id}/permissioncheck", +] +``` + +Please refer to [Documentation](https://developer.mautic.org). +for all customizable parameters. diff --git a/composer.json b/composer.json index 776c602..9b4c291 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "princealikhan/laravel-mautic-api", "description": "Free and Open Source Marketing Automation API", "license": "MIT", - "keywords": ["mautic","laravel","princealikhan","api","sync"], + "keywords": ["mautic","laravel","lumen","princealikhan","api","sync","automation","email","marketing"], "authors": [ { "name": "Prince Ali Khan", @@ -12,9 +12,17 @@ "minimum-stability": "dev", "require": { "php": ">=5.5.9", +<<<<<<< HEAD "illuminate/contracts": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*|5.5.*", "illuminate/support": "5.0.*|5.1.*|5.2.*||5.3.*|5.4.*|5.5.*", "mautic/api-library":"2.1.1" +======= + "illuminate/contracts": "5.0.*|5.1.*|5.2.*|5.3.*", + "illuminate/support": "5.0.*|5.1.*|5.2.*|5.3.*", + "mautic/api-library": "^2.1", + "guzzlehttp/guzzle": "^6.2", + "graham-campbell/manager": "^2.0" +>>>>>>> origin/master }, "autoload": { "psr-4": { diff --git a/src/Factories/MauticFactory.php b/src/Factories/MauticFactory.php index e2cb715..13b28a2 100644 --- a/src/Factories/MauticFactory.php +++ b/src/Factories/MauticFactory.php @@ -1,11 +1,21 @@ >>>>>> origin/master class MauticFactory { /** +<<<<<<< HEAD * Make a new Mautic client. * * @param array $config @@ -15,13 +25,57 @@ public function make(array $config) { $config = $this->getConfig($config); +======= + * Make a new Mautic url. + * + * @param string $endpoints + * @return url + */ + protected function getMauticUrl($endpoints=null) + { + if(!empty($endpoints)) + return config('mautic.connections.main.baseUrl').'/'.$endpoints; + else + return config('mautic.connections.main.baseUrl').'/'; + + } + + /** + * Check AccessToken Expiration Time + * @param $expireTimestamp + * @return bool + */ + public function checkExpirationTime($expireTimestamp) + { + $now = time(); + if($now > $expireTimestamp) + return true; + else + return false; + + } + /** + * Make a new Mautic client. + * + * @param array $config + * @return \Mautic\Config + */ + public function make(array $config) + { + + $config = $this->getConfig($config); +>>>>>>> origin/master return $this->getClient($config); } /** * Get the configuration data. * +<<<<<<< HEAD * @param string[] $config +======= + * @param array $config +>>>>>>> origin/master * * @throws \InvalidArgumentException * @@ -37,12 +91,17 @@ protected function getConfig(array $config) } } +<<<<<<< HEAD return array_only($config, ['client_id', 'client_secret', 'access_token']); +======= + return array_only($config, ['version','baseUrl', 'clientKey', 'clientSecret','callback']); +>>>>>>> origin/master } /** * Get the Mautic client. * +<<<<<<< HEAD * @param array $auth * * @return \Mautic\MauticApi @@ -54,5 +113,111 @@ protected function getClient(array $auth) $auth['secret_key'], $auth['access_token'] ); +======= + * @param array $setting + * + * @return \Mautic\MauticConsumer + */ + protected function getClient(array $setting) + { + session_name("mauticOAuth"); + session_start(); + + // Initiate the auth object + $auth = ApiAuth::initiate($setting); + // Initiate process for obtaining an access token; this will redirect the user to the authorize endpoint and/or set the tokens when the user is redirected back after granting authorization + + if ($auth->validateAccessToken()) + { + if ($auth->accessTokenUpdated()) { + $accessTokenData = $auth->getAccessTokenData(); + return MauticConsumer::create($accessTokenData); + } + } + + } + + + /** + * Call Mautic Api + * + * @throws \ClientException + * + * @param $method + * @param $endpoints + * @param $body + * @param $token + * + * @return mixed + */ + public function callMautic($method, $endpoints, $body, $token) + { + + $mauticURL = $this->getMauticUrl('api/'.$endpoints); + + $params = array(); + if(!empty($body)){ + $params = array(); + foreach ($body as $key => $item){ + $params['form_params'][$key] = $item; + } + } + + $headers = array('headers' => ['Authorization' => 'Bearer '. $token]); + $client = new Client($headers); + try { + + $response = $client->request($method,$mauticURL,$params); + $responseBodyAsString = $response->getBody(); + + return json_decode($responseBodyAsString,true); + } + catch (ClientException $e) { + $exceptionResponse = $e->getResponse(); + return $statusCode = $exceptionResponse->getStatusCode(); + } + } + + + /** + * Generate new token once old one expire + * and store in consumer table. + * + * @throws \ClientException + * + * @param $refreshToken + * + * @return MauticConsumer + */ + public function refreshToken($refreshToken) + { + $mauticURL = $this->getMauticUrl('oauth/v2/token'); + $config = config('mautic.connections.main'); + + $client = new Client(); + + try { + $response = $client->request('POST',$mauticURL,array( + 'form_params' => [ + 'client_id' => $config['clientKey'], + 'client_secret' => $config['clientSecret'], + 'redirect_uri' => $config['callback'], + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token' + ])); + $responseBodyAsString = $response->getBody(); + $responseBodyAsString = json_decode($responseBodyAsString,true); + + return MauticConsumer::create([ + 'access_token' => $responseBodyAsString['access_token'], + 'expires' => time() + $responseBodyAsString['expires_in'], + 'token_type' => $responseBodyAsString['token_type'], + 'refresh_token' => $responseBodyAsString['refresh_token'] + ]); + } + catch (ClientException $e) { + return $exceptionResponse = $e->getResponse(); + } +>>>>>>> origin/master } } diff --git a/src/Http/Controllers/MauticController.php b/src/Http/Controllers/MauticController.php new file mode 100644 index 0000000..3d7c214 --- /dev/null +++ b/src/Http/Controllers/MauticController.php @@ -0,0 +1,34 @@ +Mautic App Already Register'; + } + + } + + } \ No newline at end of file diff --git a/src/Http/routes.php b/src/Http/routes.php new file mode 100644 index 0000000..401258e --- /dev/null +++ b/src/Http/routes.php @@ -0,0 +1,11 @@ +>>>>>> origin/master class Mautic extends AbstractManager { @@ -14,12 +19,20 @@ class Mautic extends AbstractManager /** * The factory instance. * +<<<<<<< HEAD * @var \Vinkla\Vimeo\Factories\VimeoFactory +======= + * @var \Mautic\Factory +>>>>>>> origin/master */ protected $factory; /** +<<<<<<< HEAD * Create a new Vimeo manager instance. +======= + * Create a new Mautic manager instance. +>>>>>>> origin/master * * @param $config * @param $factory @@ -58,13 +71,18 @@ protected function getConfigName() /** * Get the factory instance. * +<<<<<<< HEAD * @return \Vinkla\Vimeo\Factories\VimeoFactory +======= + * @return \Mautic\MauticFactory +>>>>>>> origin/master */ public function getFactory() { return $this->factory; } +<<<<<<< HEAD public function test() { session_name("oauthtester"); @@ -155,6 +173,31 @@ public function test() // dd($auth); // return array('test' => 'asdf');; // } +======= + /** + * @param null $method + * @param null $endpoints + * @param null $body + * @return mixed + */ + public function request($method=null, $endpoints=null, $body=null) + { + + $consumer = MauticConsumer::whereNotNull('id') + ->orderBy('created_at', 'desc') + ->first(); + + $expirationStatus = $this->factory->checkExpirationTime($consumer->expires); + + if($expirationStatus==true){ + $newToken = $this->factory->refreshToken($consumer->refresh_token); + return $this->factory->callMautic($method,$endpoints,$body,$newToken->access_token); + } else{ + return $this->factory->callMautic($method,$endpoints,$body,$consumer->access_token); + } + } + +>>>>>>> origin/master } diff --git a/src/MauticServiceProvider.php b/src/MauticServiceProvider.php index a386152..71b0e98 100644 --- a/src/MauticServiceProvider.php +++ b/src/MauticServiceProvider.php @@ -15,8 +15,12 @@ public function boot() // Publish Configuration File to base Path. $this->publishes([ __DIR__.'/config/mautic.php' => base_path('config/mautic.php'), +<<<<<<< HEAD +======= + __DIR__ . '/migrations' => $this->app->databasePath() . '/migrations' +>>>>>>> origin/master ]); - } + } /** * Register the service provider. @@ -27,6 +31,45 @@ public function register() { $this->registerFactory($this->app); $this->registerManager($this->app); +<<<<<<< HEAD + } + + /** + * Register the factory class. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * + * @return void + */ + protected function registerFactory(Application $app) + { + $app->singleton('mautic.factory', function () { + return new Factories\MauticFactory(); + }); + + $app->alias('mautic.factory', 'Princealikhan\Mautic\Factories\MauticFactory'); + } + + /** + * Register the manager class. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * + * @return void + */ + protected function registerManager(Application $app) + { + $app->singleton('mautic', function ($app) { + $config = $app['config']; + $factory = $app['mautic.factory']; + + return new Mautic($config, $factory); + }); + + $app->alias('mautic', 'Princealikhan\Mautic\Mautic'); + } +======= + $this->registerRoutes($this->app); } /** @@ -64,6 +107,19 @@ protected function registerManager(Application $app) $app->alias('mautic', 'Princealikhan\Mautic\Mautic'); } + /** + * Get the routes services provided by the provider. + * + * @return routes + */ + protected function registerRoutes(Application $app) { + $app['router']->group(['namespace' => 'Princealikhan\Mautic\Http\Controllers', "prefix" => "mautic"], function () { + require __DIR__.'/Http/routes.php'; + }); + } + +>>>>>>> origin/master + /** * Get the services provided by the provider. * diff --git a/src/Models/MauticConsumer.php b/src/Models/MauticConsumer.php new file mode 100644 index 0000000..b5d2931 --- /dev/null +++ b/src/Models/MauticConsumer.php @@ -0,0 +1,27 @@ + [ 'main' => [ + 'version' => 'OAuth2', 'baseUrl' => env('MAUTIC_BASE_URL'), 'clientKey' => env('MAUTIC_PUBLIC_KEY'), 'clientSecret' => env('MAUTIC_SECRET_KEY'), diff --git a/src/migrations/0000_00_00_000000_mautic_api_consumer_key.php b/src/migrations/0000_00_00_000000_mautic_api_consumer_key.php new file mode 100644 index 0000000..1c1aed0 --- /dev/null +++ b/src/migrations/0000_00_00_000000_mautic_api_consumer_key.php @@ -0,0 +1,36 @@ +increments('id'); + $table->string('access_token'); + $table->integer('expires'); + $table->string('token_type'); + $table->string('refresh_token'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('mautic_consumer'); + } + +}