Skip to content

Instantly share code, notes, and snippets.

@caionorder
Created April 14, 2020 17:30
Show Gist options
  • Save caionorder/5042d027bb1ed682e3c0861512af8859 to your computer and use it in GitHub Desktop.
Save caionorder/5042d027bb1ed682e3c0861512af8859 to your computer and use it in GitHub Desktop.
<?php
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdManager\AdManagerSession;
use Google\AdsApi\AdManager\AdManagerSessionBuilder;
use Google\AdsApi\AdManager\Util\v201905\StatementBuilder;
use Google\AdsApi\AdManager\Util\v201908\AdManagerDateTimes;
use Google\AdsApi\AdManager\v201905\ServiceFactory;
use Google\AdsApi\AdManager\v201905\AdUnit as AdUnitApi;
use Google\AdsApi\AdManager\v201905\ArchiveAdUnits as ArchiveAdUnitsAction;
use Google\AdsApi\AdManager\v201905\ActivityStatus;
use Google\AdsApi\AdManager\v201905\AdUnitTargetWindow;
use Google\AdsApi\AdManager\v201905\Size;
use Google\AdsApi\AdManager\v201905\AdUnitSize;
use Google\AdsApi\AdManager\v201905\EnvironmentType;
use Google\AdsApi\AdManager\v201905\AdUnitParent;
use Google\AdsApi\AdManager\v201908\Order;
use Google\AdsApi\AdManager\v201908\InventoryTargeting;
use Google\AdsApi\AdManager\v201908\CreativePlaceholder;
use Google\AdsApi\AdManager\v201908\CreativeRotationType;
use Google\AdsApi\AdManager\v201908\LineItem;
use Google\AdsApi\AdManager\v201908\LineItemType;
use Google\AdsApi\AdManager\v201908\StartDateTimeType;
use Google\AdsApi\AdManager\v201908\CostType;
use Google\AdsApi\AdManager\v201908\Money;
use Google\AdsApi\AdManager\v201908\Goal;
use Google\AdsApi\AdManager\v201908\GoalType;
use Google\AdsApi\AdManager\v201908\UnitType;
use Google\AdsApi\AdManager\v201908\Targeting;
class GoogleComponent extends Component {
private $file = APP.'Config'.DS.'adsapi_php.ini';
private $json = APP.'Config'.DS.'adsapi_php.json';
public function test(){
echo '<h1 style="text-align:center">#DEV</h1>';
echo '<pre>';
echo $this->criar_item_linha('2685343333');
// pr($this->getAllLinesItems());
die();
}
public function criar_item_linha($orderId=null){
$nativeAppInstallTemplateId = '10004520';
// $placementId = [21961266118,21961265848,21961329290,21961329323,21961329374,21961329395,21961421634,21961266064];
$placementId = ['21961266064'];
$serviceFactory = new ServiceFactory();
$lineItemService = $serviceFactory->createLineItemService($this->session());
// Create inventory targeting.
$inventoryTargeting = new InventoryTargeting();
$inventoryTargeting->setTargetedPlacementIds($placementId);
// Create targeting.
$targeting = new Targeting();
$targeting->setInventoryTargeting($inventoryTargeting);
// Now setup the line item.
$lineItem = new LineItem();
$lineItem->setName('Line item #' . uniqid());
$lineItem->setOrderId($orderId);
$lineItem->setTargeting($targeting);
$lineItem->setLineItemType(LineItemType::STANDARD);
$lineItem->setAllowOverbook(true);
// Create the creative placeholder.
$creativePlaceholder = new CreativePlaceholder();
$creativePlaceholder->setSize(new Size(1, 1, false));
$creativePlaceholder->setCreativeTemplateId($nativeAppInstallTemplateId);
$creativePlaceholder->setCreativeSizeType('NATIVE');
// Set the size of creatives that can be associated with this line item.
$lineItem->setCreativePlaceholders([$creativePlaceholder]);
// Set the creative rotation type to even.
$lineItem->setCreativeRotationType(CreativeRotationType::EVEN);
// Set the length of the line item to run.
$lineItem->setStartDateTimeType(StartDateTimeType::IMMEDIATELY);
$lineItem->setEndDateTime(
AdManagerDateTimes::fromDateTime(
new DateTime('+1 month', new DateTimeZone('America/Sao_Paulo'))
)
);
// Set the cost per unit to $2.
$lineItem->setCostType(CostType::CPM);
$lineItem->setCostPerUnit(new Money('USD', 2000000));
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
$goal = new Goal();
$goal->setUnits(500000);
$goal->setUnitType(UnitType::IMPRESSIONS);
$goal->setGoalType(GoalType::LIFETIME);
$lineItem->setPrimaryGoal($goal);
// Create the line items on the server.
$results = $lineItemService->createLineItems([$lineItem]);
// Print out some information for each created line item.
foreach ($results as $i => $lineItem) {
printf(
"%d) Line item with ID %d, belonging to order ID %d, and name"
. " '%s' was created.%s",
$i,
$lineItem->getId(),
$lineItem->getOrderId(),
$lineItem->getName(),
PHP_EOL
);
}
die();
}
public function getAllLinesItems(){
$serviceFactory = new ServiceFactory();
$lineItemService = $serviceFactory->createLineItemService($this->session());
$pageSize = StatementBuilder::SUGGESTED_PAGE_LIMIT;
$statementBuilder = (new StatementBuilder())->orderBy('id ASC')->limit($pageSize);
$totalResultSetSize = 0;
$saida = array();
do {
$page = $lineItemService->getLineItemsByStatement(
$statementBuilder->toStatement()
);
// Print out some information for each line item.
if ($page->getResults() !== null) {
$totalResultSetSize = $page->getTotalResultSetSize();
$i = $page->getStartIndex();
foreach ($page->getResults() as $lineItem) {
$saida[] = [
'id'=>$lineItem->getId(),
'name'=>$lineItem->getName()
];
}
}
$statementBuilder->increaseOffsetBy($pageSize);
} while ($statementBuilder->getOffset() < $totalResultSetSize);
return $saida;
}
public function criar_pedido(){
$advertiserId = '4862061821';
$salespersonId = '245929621';
$session = $this->session();
$serviceFactory = new ServiceFactory();
$orderService = $serviceFactory->createOrderService($session);
$order = new Order();
$order->setName('Order API #' . uniqid());
$order->setAdvertiserId($advertiserId);
$order->setSalespersonId($salespersonId);
$order->setTraffickerId($salespersonId);
$results = $orderService->createOrders([$order]);
$saida = '';
foreach ($results as $i => $order) {
$saida = $order->getId();
}
return $saida;
}
public function session(){
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile($this->file)
->withJsonKeyFilePath($this->json)
->build();
$session = (new AdManagerSessionBuilder())
->fromFile($this->file)
->withOAuth2Credential($oAuth2Credential)
->build();
return $session;
}
public function listar_dominios_admanager(){
$session = $this->session();
$serviceFactory = new ServiceFactory();
$inventoryService = $serviceFactory->createInventoryService($session);
$networkService = $serviceFactory->createNetworkService($session);
$network = $networkService->getCurrentNetwork();
$effectiveRootAdUnitId = $network->getEffectiveRootAdUnitId();
$ParentId = $effectiveRootAdUnitId;
$AdUnits = $this->getAdUnits(new ServiceFactory(), $session, $ParentId);
return $AdUnits;
}
public function criar_dominio($dominio=null){
$session = $this->session();
$result = $this->CreateAdUnitRoot(new ServiceFactory(), $session, $dominio, '1');
return $result['id_ad_unit'];
}
public function criar_bloco($dominio=null,$ad_id=null,$id_bloco=null){
$session = $this->session();
return $this->CreatAdUnit(new ServiceFactory(), $session, $dominio.'_'.date('dmY').'_native_'.$id_bloco, false, $ad_id, [0=>['width'=>1,'height'=>1]]);
}
public function arquivar_bloco($id=null){
$session = $this->session();
return $this->Archived(new ServiceFactory(), $session, $id);
}
/////////////////////////////////////PADRÃO DE BLOCOS/////////////////////////
/////////////////////////////////////PADRÃO DE BLOCOS/////////////////////////
/////////////////////////////////////PADRÃO DE BLOCOS/////////////////////////
public function CreatAdUnit(ServiceFactory $serviceFactory, AdManagerSession $session, $NameAdUnit, $root, $ParentId = "", $sizes){
$inventoryService = $serviceFactory->createInventoryService($session);
$networkService = $serviceFactory->createNetworkService($session);
$network = $networkService->getCurrentNetwork();
$effectiveRootAdUnitId = $network->getEffectiveRootAdUnitId();
$adUnit = new AdUnitApi();
$adUnit->setAdUnitCode($NameAdUnit);
$adUnit->setName($NameAdUnit);
$adUnit->setTargetWindow(AdUnitTargetWindow::TOP);
if(!$root){
$adUnit->setParentId($ParentId);
foreach($sizes as $sizeSet){
$adUnitSize = new AdUnitSize();
$size = new Size();
$size->setWidth($sizeSet['width']);
$size->setHeight($sizeSet['height']);
$size->setIsAspectRatio(false);
$adUnitSize->setSize($size);
$multsize[] = $adUnitSize;
}
$adUnitSize->setEnvironmentType(EnvironmentType::BROWSER);
$adUnit->setAdUnitSizes($multsize);
}else{
$adUnit->setParentId($effectiveRootAdUnitId);
}
$adUnits = $inventoryService->createAdUnits([$adUnit]);
foreach ($adUnits as $i => $adUnit) {
$return['id_ad_unit'] = $adUnit->getId();
$return['name'] = $adUnit->getName();
$return['code'] = $adUnit->getAdUnitCode();
$return['status'] = $adUnit->getStatus();
}
return $return;
}
public function CreateAdUnitRoot(ServiceFactory $serviceFactory, AdManagerSession $session, $NameAdUnit, $idDomain){
$inventoryService = $serviceFactory->createInventoryService($session);
$networkService = $serviceFactory->createNetworkService($session);
$network = $networkService->getCurrentNetwork();
$effectiveRootAdUnitId = $network->getEffectiveRootAdUnitId();
$adUnit = new AdUnitApi();
$adUnit->setAdUnitCode($NameAdUnit);
$adUnit->setName($NameAdUnit);
$adUnit->setTargetWindow(AdUnitTargetWindow::TOP);
$adUnit->setParentId($effectiveRootAdUnitId);
$adUnits = $inventoryService->createAdUnits([$adUnit]);
foreach ($adUnits as $i => $adUnit) {
$return['id_ad_unit'] = $adUnit->getId();
$return['name'] = $adUnit->getName();
$return['code'] = $adUnit->getAdUnitCode();
}
return $return;
}
public function modelsAdUnitOne($serviceFactory, $session, $idAdUnitRootDB, $idDomain, $AdUnits){
$data = AdUnitFormat::get();
$adunitRoot = AdUnitRoot::where('id_domain', $idDomain)->first();
if(is_array($AdUnits)){
foreach($AdUnits as $AdUnit){
$NamesAdUnits[] = $AdUnit["name"];
}
}else{
$NamesAdUnits = [];
}
$NameRoot = explode('.',str_replace('www.','',$adunitRoot->ad_unit_root_name))[0];
$NameRoot = ucfirst($NameRoot);
$ParentId = $adunitRoot->ad_unit_root_id;
foreach($data as $dado){
$position = $this->getPosition($dado->position);
$contParagraph = 0;
$contAdUnit = 1;
while($contAdUnit <= $dado->quantity){
$sizes = explode(',', $dado->sizes);
$cont = 0;
$sizeAdUnit = '[';
foreach ($sizes as $size) {
$size = explode('x', $size);
$tamanhos[$cont]['width'] = $size[0];
$tamanhos[$cont]['height'] = $size[1];
$sizeAdUnit .= '['.$size[0].', '.$size[1].'],';
$cont++;
}
$sizeAdUnit = rtrim($sizeAdUnit,',');
$sizeAdUnit .= ']';
if($dado->device == 1){
$device = "WEB";
}else if($dado->device == 2){
$device = "MOBILE";
}else{
$device = "AMP";
}
if($dado->quantity > 1){
$nane_ad_unit = $dado->name.$contAdUnit;
}else{
$nane_ad_unit = $dado->name;
}
$NameAdUnit = $NameRoot."_".$device."_".$nane_ad_unit."_".$dado->page."_".date('Ymd');
$sizes = $tamanhos;
$create = true;
foreach ($NamesAdUnits as $value) {
if(strtolower($value) == strtolower($NameAdUnit)){
$create = false;
}
}
if($create){
$result = $this->CreatAdUnit($serviceFactory, $session, $NameAdUnit, false, $ParentId, $sizes);
unset($tamanhos);
$dadosForm['sizes'] = $sizeAdUnit;
$dadosForm['ad_unit_id'] = $result['id_ad_unit'];
$dadosForm['ad_unit_code'] = $result['code'];
$dadosForm['ad_unit_name'] = $result['name'];
$dadosForm['ad_unit_status'] = $result['status'];
$dadosForm['id_ad_unit_root'] = $idAdUnitRootDB;
if($dado->position == 'paragraph' && $contParagraph < 3){
$dadosForm['position'] = $position[$contParagraph];
$contParagraph++;
}elseif($dado->position != 'paragraph'){
$dadosForm['position'] = $position;
}else{
$dadosForm['position'] = '';
}
$dadosForm['device'] = $dado->device;
AdUnit::create($dadosForm);
}else{
foreach($AdUnits as $AdUnit){
$adunitsDB = AdUnit::where('id_ad_unit_root', $idAdUnitRootDB)->where('ad_unit_id', $AdUnit['id'])->first();
if(empty($adunitsDB->id_ad_unit)){
unset($tamanhos);
if($AdUnit['name'] == $NameAdUnit){
$dadosForm['sizes'] = $AdUnit['size'];
$dadosForm['ad_unit_id'] = $AdUnit['id'];
$dadosForm['ad_unit_code'] = $AdUnit['code'];
$dadosForm['ad_unit_name'] = $AdUnit['name'];
$dadosForm['ad_unit_status'] = $AdUnit['status'];
$dadosForm['id_ad_unit_root'] = $idAdUnitRootDB;
if($dado->position == 'paragraph' && $contParagraph < 3){
$dadosForm['position'] = $position[$contParagraph];
$contParagraph++;
}elseif($dado->position != 'paragraph'){
$dadosForm['position'] = $position;
}else{
$dadosForm['position'] = '';
}
$nameParts = explode('_',$AdUnit['name']);
if(in_array('WEB', $nameParts)){
$device = 1;
}else{
$device = 2;
}
$dadosForm['device'] = $device;
AdUnit::create($dadosForm);
}
}
}
}
$contAdUnit++;
}
}
}
public function getPosition($position){
if($position == 'paragraph'){
$result[] = 'first_paragraph';
$result[] = 'four_paragraph';
$result[] = 'after_the_content';
}else if($position == 'after_the_content'){
$result = 'after_the_content';
}else if($position == 'before_the_home'){
$result = 'before_the_home';
}else if($position == 'before_the_pages'){
$result = 'before_the_pages';
}else if($position == 'before_the_content'){
$result = 'before_the_content';
}else if($position == 'ad_shortcode'){
$result = 'ad_shortcode';
}else if($position == 'fixedMobile'){
$result = 'fixedMobile';
}else if($position == 'Horizontal'){
$result = 'before_the_pages';
}else if($position == 'Square'){
$result[] = 'first_paragraph';
$result[] = 'four_paragraph';
$result[] = 'after_the_content';
}else{
$result = '';
}
return $result;
}
public function getAdUnits(ServiceFactory $serviceFactory, AdManagerSession $session, $parentId = "") {
$AdUnitsRoot = [];
$inventoryService = $serviceFactory->createInventoryService($session);
$networkService = $serviceFactory->createNetworkService($session);
if($parentId == ""){
$parentId = $networkService->getCurrentNetwork()->getEffectiveRootAdUnitId();
}
$statementBuilder = new StatementBuilder();
$statementBuilder->where('parentId = :parentId');
$statementBuilder->orderBy('id ASC');
$statementBuilder->limit(StatementBuilder::SUGGESTED_PAGE_LIMIT);
$statementBuilder->withBindVariableValue('parentId', $parentId);
$page = $inventoryService->getAdUnitsByStatement(
$statementBuilder->toStatement()
);
$totalResultSetSize = $page->getTotalResultSetSize();
$adUnits = $page->getResults();
$cont = 0;
if(is_array($adUnits)){
foreach ($adUnits as $adUnit) {
$list[$cont]['id'] = $adUnit->getId();
$list[$cont]['code'] = $adUnit->getAdUnitCode();
$list[$cont]['name'] = $adUnit->getName();
$list[$cont]['status'] = $adUnit->getStatus();
$adUnitSIzes = $adUnit->getAdUnitSizes();
if(isset($adUnitSIzes)){
$sizes = '[';
foreach($adUnit->getAdUnitSizes() as $size){
$sizes .= '['.str_replace('x',',',$size->getFullDisplayString()).'],';
}
$sizes = rtrim($sizes,',');
$sizes .= ']';
}else{
$sizes = '';
}
$list[$cont]['size'] = $sizes;
$cont++;
}
}else{
$list = '';
}
return $list;
}
public function Archived(ServiceFactory $serviceFactory, AdManagerSession $session, $parentAdUnitId) {
$inventoryService = $serviceFactory->createInventoryService($session);
$pageSize = StatementBuilder::SUGGESTED_PAGE_LIMIT;
$statementBuilder = (new StatementBuilder())->where('id = :parentId')->orderBy('id ASC')
->limit($pageSize) ->withBindVariableValue('parentId', $parentAdUnitId);
$totalResultSetSize = 0;
do {
$page = $inventoryService->getAdUnitsByStatement(
$statementBuilder->toStatement()
);
if ($page->getResults() !== null) {
$totalResultSetSize = $page->getTotalResultSetSize();
$i = $page->getStartIndex();
}
$statementBuilder->increaseOffsetBy($pageSize);
} while ($statementBuilder->getOffset() < $totalResultSetSize);
if ($totalResultSetSize > 0) {
$statementBuilder->removeLimitAndOffset();
// Create and perform action.
$action = new ArchiveAdUnitsAction();
$result = $inventoryService->performAdUnitAction(
$action,
$statementBuilder->toStatement()
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment