Skip to content

Commit

Permalink
Merge branch 'simplified-use'
Browse files Browse the repository at this point in the history
  • Loading branch information
Eflyax committed Nov 2, 2017
2 parents f24101e + cdf084e commit 5ebc37d
Show file tree
Hide file tree
Showing 13 changed files with 212 additions and 185 deletions.
115 changes: 51 additions & 64 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#Nette extension for Facebook Pixel.
# Nette extension for Facebook Pixel.

TODO
* implement missing events (search, addToWishList, etc..)
* support for ajax

## Requirements

Expand All @@ -8,8 +12,8 @@

The best way to install Eflyax/Facebook-pixel is using [Composer](http://getcomposer.org/):

```sh
$ composer require eflyax/facebook-pixel
```bash
$ composer require eflyax/facebook-pixel
```

## Usage
Expand All @@ -25,7 +29,7 @@ and configuration with you FB pixel ID:
```
facebookPixel:
id: '111122223333444'
productIdPrefix: '42' // optional
productIdPrefix: '42' # optional
```

Be careful you add FB pixel ID as string, there was issues with integer
Expand All @@ -35,29 +39,37 @@ Be careful you add FB pixel ID as string, there was issues with integer
Inject FB pixel factory and service to your module where you want to render FB pixel. FB pixel service
will help you to render specific events.

```
```php
abstract class BaseFrontPresenter extends BasePresenter
{

/** @var IFacebookPixelFactory @inject */
public $facebookPixelFactory;
public $IFacebookPixelFactory;

/** @var FacebookPixel */
public $facebookPixel;


/** @var FacebookPixelService @inject */
public $facebookPixelService;
protected function startup()
{
parent::startup();
$this->facebookPixel = $this['facebookPixel'];
}


.
.

protected function createComponentFacebookPixel()
{
return $this->facebookPixelFactory->create();
return $this->IFacebookPixelFactory->create();
}

}
```
#### Frontend

Now you are ready to render basic FB pixel for event PageView. Render control faceboobPixel in layout
Now you are ready to render FB pixel in layout

`{control facebookPixel}`

Expand All @@ -66,82 +78,57 @@ Now you are ready to render basic FB pixel for event PageView. Render control fa

#### AddToCart

##### Backend
In method where you add product to cart call eventStart like this:

````
public function actionAddProduct($idProduct, $quantity = 1)
{
...
$this->facebookPixelService->eventStart(FacebookPixelService::EVENT_ADD_TO_CART);
}
````php
$this->facebookPixel->addToCart(
$productId,
$productTitle,
$productCategory,
$productPrice,
$currencyCode
);

````

##### Frontend
This control is rendered only if you call eventStart addToCart on backend. When you render this control event is automatically deactivated

```
{control facebookPixel:addToCart,
$product->getId(),
$product->getTitle(),
$product->getDescription(),
$product->getPrice(),
$currency->getCode()
}
```

#### Purchase

##### Backend
Before you redirect customer on thank you page call startEvent:

`$this->facebookPixelService->eventStart(FacebookPixelService::EVENT_PURCHASE);`

##### Frontend

```
{control facebookPixel:purchase,
$totalPrice,
$currency->getCode(),
$itemIds
}
$this->facebookPixel->purchase($totalPrice, $currencyCode);
```

`$itemIds` can contains id for one or more products


#### ViewContent
##### Frontend

For one product:
```
{control facebookPixel:viewContent,
$product->getId(),
$product->getTitle(),
$product->getDescription(),
$product->getPrice(),
$currency->getCode()
}
```php
$this->facebookPixel->viewContent(
$productId,
$productTitle,
$productCategory,
$productPrice,
$currencyCode
);
```
For more products (category):
```
{control facebookPixel:viewContent,

```php
$this->facebookPixel->viewContent(
$productIds
}
);
```

## Events validation

If you want to validate events sended to facebook I can recommend this browser plugin:
If you want to validate events which you send to facebook I can recommend this browser plugin:
[Facebook Pixel Helper](https://chrome.google.com/webstore/detail/FacebookPixel-helper/fdgfkebogiimcoedlicjlajpkdmockpc)


## How to run tests
```
$ cd tests
$ composer install
$ ./vendor/bin/codecept build
$ ./vendor/bin/codecept run
```bash
$ cd tests
$ composer install
$ mkdir temp
$ ./vendor/bin/codecept build
$ ./vendor/bin/codecept run
```


1 change: 0 additions & 1 deletion src/DI/FacebookPixelExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,3 @@ public function loadConfiguration()
}

}

103 changes: 56 additions & 47 deletions src/FacebookPixel/FacebookPixel.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@
class FacebookPixel extends Control
{

const EVENT_VIEW_CONTENT = 'ViewContent',
EVENT_PURCHASE = 'Purchase',
EVENT_ADD_TO_CART = 'AddToCart';

private $sessionEvents = [
self::EVENT_ADD_TO_CART,
self::EVENT_VIEW_CONTENT,
self::EVENT_PURCHASE,
];

/** @var string */
private $facebookId;

Expand All @@ -33,75 +43,67 @@ public function __construct($id, FacebookPixelService $facebookPixelService, $pr
public function render()
{
$this->template->id = $this->facebookId;
$events = [];
foreach ($this->sessionEvents as $sessionEvent) {
$events[] = $this->facebookPixelService->getEventContent($sessionEvent);
}
$this->template->specialEvents = $events;
$this->template->setFile(__DIR__ . '/templates/facebookPixel.latte');
$this->template->render();
$this->clearEventsFromSession();
}

public function renderViewContent(
public function viewContent(
$contentIds,
$contentName = null,
$contentCategory = null,
$value = null,
$currency = null
)
{
$this->template->parameters =
$this->prepareProductsToParameters($contentIds, $contentName, $contentCategory, $value, $currency);
$this->template->event = FacebookPixelService::EVENT_VIEW_CONTENT;
$this->template->id = $this->facebookId;
$this->template->render(__DIR__ . '/templates/commonEvent.latte');
$this->sendEventToOutput(
self::EVENT_VIEW_CONTENT,
$this->prepareProductsToParameters(
$contentIds,
$contentName,
$contentCategory,
$value,
$currency
)
);
}

public function renderAddToCart(
public function addToCart(
$contentIds,
$contentName = null,
$contentCategory = null,
$value = null,
$currency = null,
$selector = null
$currency = null
)
{
if (!$this->facebookPixelService->eventStatus(FacebookPixelService::EVENT_ADD_TO_CART) && !$selector) {

return;
}
$this->template->selector = $selector;
$this->template->id = $this->facebookId;
$this->template->event = FacebookPixelService::EVENT_ADD_TO_CART;
$this->template->parameters =
$this->prepareProductsToParameters($contentIds, $contentName, $contentCategory, $value, $currency);
$this->template->render(__DIR__ . '/templates/addToCart.latte');
if (!$selector) {
$this->facebookPixelService->eventEnd(FacebookPixelService::EVENT_ADD_TO_CART);
}
$this->sendEventToOutput(
self::EVENT_ADD_TO_CART,
$this->prepareProductsToParameters($contentIds, $contentName, $contentCategory, $value, $currency)
);
}

public function renderPurchase($value, $currency, $contentIds = null)
public function purchase($value, $currency, $contentIds = null)
{
if (!$this->facebookPixelService->eventStatus(FacebookPixelService::EVENT_PURCHASE)) {
$this->sendEventToOutput(
self::EVENT_PURCHASE,
$this->prepareProductsToParameters($contentIds, null, null, $value, $currency)
);
}

return;
}
if ($value) {
$parameters['value'] = $this->formatPrice($value);
}
if ($currency) {
$parameters['currency'] = "'{$currency}'";
}
if (!is_array($contentIds)) {
$contentIds = [$contentIds];
}
$idsWithPrefix = [];
foreach ($contentIds as $id) {
$idsWithPrefix[] = $this->productIdPrefix . $id;
private function sendEventToOutput($event, $eventParameters)
{
$output = "fbq('track', '" . $event . "'";
if (isset($eventParameters)) {
$output .= ', ' . $eventParameters;
}
$idsWithPrefix = array_map('strval', $idsWithPrefix);
$parameters['content_type'] = count($idsWithPrefix) > 1 ? 'product_group' : 'product';
$parameters['content_ids'] = $idsWithPrefix;
$this->template->parameters = json_encode($parameters);
$this->template->event = FacebookPixelService::EVENT_PURCHASE;
$this->template->render(__DIR__ . '/templates/commonEvent.latte');
$this->facebookPixelService->eventEnd(FacebookPixelService::EVENT_PURCHASE);
$output .= ");";
$output = str_replace('"', "'", $output);
$this->facebookPixelService->saveEvent($event, $output);
}

/**
Expand Down Expand Up @@ -132,7 +134,7 @@ private function prepareProductsToParameters(
$parameters['content_name'] = $contentName;
$parameters['content_category'] = $contentCategory ? $contentCategory : null;
$parameters['value'] = $value ? $this->formatPrice($value) : null;
$parameters['currency'] = $currency ? "'{$currency}'" : null;
$parameters['currency'] = $currency ?: null;

foreach ($parameters as $key => $value) {
if (!$value) {
Expand All @@ -151,4 +153,11 @@ private function formatPrice($value)
return number_format($value, 2, '.', '');
}

}
private function clearEventsFromSession()
{
foreach ($this->sessionEvents as $sessionEvent) {
$this->facebookPixelService->removeEvent($sessionEvent);
}
}

}
26 changes: 11 additions & 15 deletions src/FacebookPixel/FacebookPixelService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
class FacebookPixelService
{

const EVENT_VIEW_CONTENT = 'ViewContent',
EVENT_PURCHASE = 'Purchase',
EVENT_ADD_TO_CART = 'AddToCart';

/** @var SessionSection */
private $sessionSection;

Expand All @@ -30,31 +26,31 @@ public function __construct(Session $session)
}

/**
* Activates given event
* @param String $eventName
* Save special events to session
* @param String[] $eventName
* @param String[] $eventContent
*/
public function eventStart($eventName)
public function saveEvent($eventName, $eventContent)
{
$this->sessionSection->$eventName = true;
$this->sessionSection->$eventName = serialize($eventContent);

}

/**
* Deactivates given event
* @param String $eventName
* @return String
*/
public function eventEnd($eventName)
public function getEventContent($eventName)
{
unset($this->sessionSection->$eventName);
return unserialize($this->sessionSection->$eventName);
}

/**
* Gets status of given event
* @param String $eventName
* @return String
*/
public function eventStatus($eventName)
public function removeEvent($eventName)
{
return $this->sessionSection->$eventName;
$this->sessionSection->$eventName = null;
}

}
Loading

0 comments on commit 5ebc37d

Please sign in to comment.