Skip to content

Commit

Permalink
Add facebook auth support
Browse files Browse the repository at this point in the history
  • Loading branch information
danielstonies committed Dec 1, 2020
1 parent 047c854 commit d6629db
Show file tree
Hide file tree
Showing 2,175 changed files with 176,583 additions and 28,791 deletions.
83 changes: 41 additions & 42 deletions Platforms/FacebookAds/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
*
* @author Daniel Stonies <daniel.stonies@googlemail.com>
*/

namespace Piwik\Plugins\AOM\Platforms\FacebookAds;

use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook;
use Exception;
use League\OAuth2\Client\Provider\Facebook;
use Piwik\Common;
use Piwik\Option;
use Piwik\Piwik;
Expand All @@ -32,12 +32,12 @@ public function addAccount($websiteId, $clientId, $clientSecret, $accountId)
$configuration = $settings->getConfiguration();

$configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][uniqid('', true)] = [
'websiteId' => $websiteId,
'clientId' => $clientId,
'websiteId' => $websiteId,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'accountId' => $accountId,
'accessToken' => null,
'active' => true,
'accountId' => $accountId,
'accessToken' => null,
'active' => true,
];

$settings->setConfiguration($configuration);
Expand Down Expand Up @@ -66,15 +66,13 @@ public function getAccessToken()
$idSites = [$configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['websiteId']]
);

$fb = $this->getFacebookApiClient($configuration, $id);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(
Option::get('piwikUrl')
. '?module=AOM&action=platformAction&platform=FacebookAds&method=processAccessTokenCode&id=' . $id,
['ads_read']
);
$provider = $this->getFacebookAuthProvider($configuration, $id);
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl(['scope' => ['ads_read']]);
$_SESSION['oauth2state'] = $provider->getState();
$_SESSION['aom_facebook_website_id'] = $id;

header('Location: ' . $loginUrl);
header('Location: ' . $authUrl);
exit;
}

Expand All @@ -88,8 +86,14 @@ public function processAccessTokenCode()
$settings = new SystemSettings();
$configuration = $settings->getConfiguration();

// Does the account exist?
$id = Common::getRequestVar('id', false);
if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
echo 'Invalid state.';
exit;
}

$id = $_SESSION['aom_facebook_website_id'];

if (!array_key_exists($id, $configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'])) {
throw new \Exception('Facebook Ads account "' . $id . '" does not exist.');
}
Expand All @@ -98,43 +102,38 @@ public function processAccessTokenCode()
$idSites = [$configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['websiteId']]
);

$fb = $this->getFacebookApiClient($configuration, $id);
$helper = $fb->getRedirectLoginHelper();
$provider = $this->getFacebookAuthProvider($configuration, $id);

$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code'],
]);

try {
$accessToken = $helper->getAccessToken();
} catch (FacebookResponseException $e) {
throw new \Exception('Graph returned an error: ' . $e->getMessage());
} catch (FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: ' . $e->getMessage());
$token = $provider->getLongLivedAccessToken($token);
} catch (Exception $e) {
echo 'Failed to exchange the token: ' . $e->getMessage();
exit();
}

if (isset($accessToken)) {

$configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['accessToken'] = $accessToken->getValue();
$settings->setConfiguration($configuration);

header('Location: ?module=AOM&action=settings');
exit;
$configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['accessToken'] = $token->getToken();
$settings->setConfiguration($configuration);

} elseif ($helper->getError()) {
throw new \Exception('The user denied the request.');
}
header('Location: ?module=AOM&action=settings');
exit;
}

/**
* @param array $configuration
* @param string $id
* @return Facebook
*/
private function getFacebookApiClient($configuration, $id)
private function getFacebookAuthProvider($configuration, $id)
{
$fb = new Facebook([
'app_id' => $configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['clientId'],
'app_secret' => $configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['clientSecret'],
'default_graph_version' => 'v2.5',
return new Facebook([
'clientId' => $configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['clientId'],
'clientSecret' => $configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'][$id]['clientSecret'],
'redirectUri' => Option::get('piwikUrl') . '?module=AOM&action=platformAction&platform=FacebookAds&method=processAccessTokenCode',
'graphApiVersion' => 'v9.0',
]);

return $fb;
}
}
121 changes: 117 additions & 4 deletions Platforms/FacebookAds/Importer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,45 @@
*/
namespace Piwik\Plugins\AOM\Platforms\FacebookAds;

use DateTime;
use Exception;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Values\AdsInsightsLevelValues;
use Monolog\Logger;
use Piwik\Plugins\AOM\AOM;
use Piwik\Plugins\AOM\Platforms\AbstractImporter;
use Piwik\Plugins\AOM\Platforms\ImporterInterface;
use Piwik\Plugins\AOM\SystemSettings;

use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;


class Importer extends AbstractImporter implements ImporterInterface
{

/**
* @var array
*/
protected $adsInsightsFields = [
AdsInsightsFields::DATE_START,
AdsInsightsFields::ACCOUNT_NAME,
AdsInsightsFields::ACCOUNT_ID,
AdsInsightsFields::CAMPAIGN_ID,
AdsInsightsFields::CAMPAIGN_NAME,
AdsInsightsFields::ADSET_ID,
AdsInsightsFields::ADSET_NAME,
AdsInsightsFields::AD_NAME,
AdsInsightsFields::AD_ID,
AdsInsightsFields::IMPRESSIONS,
AdsInsightsFields::CLICKS,
AdsInsightsFields::INLINE_LINK_CLICKS,
AdsInsightsFields::SPEND,
];

/**
* Imports all active accounts day by day
*/
Expand All @@ -27,7 +57,7 @@ public function import()
foreach ($configuration[AOM::PLATFORM_FACEBOOK_ADS]['accounts'] as $accountId => $account) {
if (array_key_exists('active', $account) && true === $account['active']) {
foreach (AOM::getPeriodAsArrayOfDates($this->startDate, $this->endDate) as $date) {
$this->importAccount($accountId, $account, $date);
$this->importAccount($account, $date);
}
} else {
$this->log(Logger::INFO, 'Skipping inactive account.');
Expand All @@ -41,14 +71,97 @@ public function import()
* @param string $date
* @throws \Exception
*/
private function importAccount($accountId, $account, $date)
private function importAccount($account, $date)
{
$this->log(Logger::INFO, 'Will import FacebookAds account ' . $accountId. ' for date ' . $date . ' now.');
$this->deleteExistingData(AOM::PLATFORM_FACEBOOK_ADS, $accountId, $account['websiteId'], $date);

throw new Exception('Not implemented');
// var_dump($account);

// var_dump([$account['clientId'], $account['clientSecret'], $account['accessToken']]);
$api = Api::init($account['clientId'], $account['clientSecret'], $account['accessToken']);

$adAccount = new AdAccount($account['accountId'], null, $api);


foreach ($this->fetchAdsInsights($adAccount, $date) as $insight) {
var_dump([
$insight->{AdsInsightsFields::ACCOUNT_NAME},
$insight->{AdsInsightsFields::ACCOUNT_ID},
$insight->{AdsInsightsFields::CAMPAIGN_NAME},
$insight->{AdsInsightsFields::CAMPAIGN_ID},
$insight->{AdsInsightsFields::ADSET_NAME},
$insight->{AdsInsightsFields::ADSET_ID},
$insight->{AdsInsightsFields::AD_NAME},
$insight->{AdsInsightsFields::AD_ID},
$insight->{AdsInsightsFields::CLICKS},
$insight->{AdsInsightsFields::IMPRESSIONS},
$insight->{AdsInsightsFields::SPEND},
]
);
die();
// $ad = new FacebookAds();
// $ad
// ->setDate(new DateTime($date))
// ->setSaasUserId($user->getId())
// ->setAccountName($insight->{AdsInsightsFields::ACCOUNT_NAME})
// ->setAccountId($insight->{AdsInsightsFields::ACCOUNT_ID})
// ->setCampaignName($insight->{AdsInsightsFields::CAMPAIGN_NAME})
// ->setCampaignId($insight->{AdsInsightsFields::CAMPAIGN_ID})
// ->setAdsetName($insight->{AdsInsightsFields::ADSET_NAME})
// ->setAdSetId($insight->{AdsInsightsFields::ADSET_ID})
// ->setAdName($insight->{AdsInsightsFields::AD_NAME})
// ->setAdId($insight->{AdsInsightsFields::AD_ID})
// ->setClicks($insight->{AdsInsightsFields::CLICKS})
// ->setImpressions($insight->{AdsInsightsFields::IMPRESSIONS})
// ->setCosts($insight->{AdsInsightsFields::SPEND});
//
// $this->entityManager->persist($ad);
}



// $adAccount = new AdAccount($account['accountId']);


var_dump($adAccount->getData());

$cursor = $adAccount->getCampaigns();

// Loop over objects
foreach ($cursor as $campaign) {
echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}





// $this->deleteExistingData(AOM::PLATFORM_FACEBOOK_ADS, $accountId, $account['websiteId'], $date);

// throw new Exception('Not implemented');
}

/**
* @param AdAccount $adAccount
* @param string $date
* @return \FacebookAds\ApiRequest|\FacebookAds\Cursor|\FacebookAds\Http\ResponseInterface|null
*/
protected function fetchAdsInsights(AdAccount $adAccount, $date)
{
$insights = $adAccount->getInsights($this->adsInsightsFields, [
'level' => AdsInsightsLevelValues::AD,
'time_range' => [
'since' => $date,
'until' => $date,
],
]);

$insights->setUseImplicitFetch(true);

return $insights;
}


/**
* Convenience function for shorter logging statements
*
Expand Down
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"require": {
"php": ">=5.5.0",
"bramus/monolog-colored-line-formatter": "~2.0",
"googleads/googleads-php-lib": "^34.0.0"
"facebook/php-business-sdk": "^9.0.1",
"googleads/googleads-php-lib": "^34.0.0",
"league/oauth2-facebook": "^2.0"
}
}
Loading

0 comments on commit d6629db

Please sign in to comment.