Posts tagged with php

I've build a own tracking template for Google ads, which looks like this:

http://tracking.example.com?lpurl={lpurl}

This tracking link (where {lpurl} is the final url) leads to our website and triggers the script below.

<?php     header("Status: 301 Moved Permanently"); // some code to add data to our database // then redirect traffic to url:     header("Location:".$_GET["lpurl"]."?". $_SERVER['QUERY_STRING']);     exit; ?> 

I have started using ClickPatrol.com for click fraud protection and PPC protection. However, they also require a tracking template. They work well with Hubspot, but I don't know how to combine their tracking template with mine and modify my script.

their trackingtemplate is: https://example.com/?uid=[unique id]&adp={adposition}&lpm={loc_physical_ms}&lim={loc_interest_ms}&adi={adgroupid}&k={keyword}&n={network}&ci={campaignid}&d={device}&p={placement}&u={lpurl}&ma={matchtype}&ta={target}&cr={creative}

Any idea how I can combine:

http://example.com?url={lpurl}

and

https://example.com/?uid=[unique id]&adp={adposition}&lpm={loc_physical_ms}&lim={loc_interest_ms}&adi={adgroupid}&k={keyword}&n={network}&ci={campaignid}&d={device}&p={placement}&u={lpurl}&ma={matchtype}&ta={target}&cr={creative}

I want to track my traffic with my own script and also use ClickPatrol

I attempted to merge the querystring and redirect it, but the urls in the querystring made it difficult to decode and encode, resulting in redirecting errors.

I am trying to limit the number of returned keyword ideas. The code works fine, but when I try to set limit to the keywordIdeas that I get using 'pageSize' I get the following error:

An unexpected error occurred: { "message": "Resource has been exhausted (e.g. check quota).", "code": 8, "status": "RESOURCE_EXHAUSTED", "details": [ { "@type": "type.googleapis.com\/google.ads.googleads.v14.errors.GoogleAdsFailure", "errors": [ { "errorCode": { "quotaError": "RESOURCE_EXHAUSTED" }, "message": "Too many requests. Retry in 4 seconds.", "details": { "quotaErrorDetails": { "rateScope": "ACCOUNT", "rateName": "Requests per service per method", "retryDelay": "4s" } } } ], "requestId": "eTMFNxlHYYTzZGDT7Cksfw" } ] }

Which is odd, because I am trying to limit the results and without pageSize this is error is not displayed.

Here is the code:

namespace Google\Ads\GoogleAds\Examples\Planning; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V14\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V14\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V14\GoogleAdsException; use Google\Ads\GoogleAds\Util\V14\ResourceNames; use Google\Ads\GoogleAds\V14\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork; use Google\Ads\GoogleAds\V14\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V14\Services\GenerateKeywordIdeaResult; use Google\Ads\GoogleAds\V14\Services\KeywordAndUrlSeed; use Google\Ads\GoogleAds\V14\Services\KeywordSeed; use Google\Ads\GoogleAds\V14\Services\UrlSeed; use Google\ApiCore\ApiException; function generateKeywordIdeas($customerId, $url, $language, $locationId){     try {         // Google Ads API Configurations        $config = [             'developerToken' => '***',             'clientId' => '***',             'clientSecret' => '***',             'refreshToken' => '***',             'loginCustomerId' => '***',              'useSandbox' => true, // Set to true if you want to use the sandbox environment for testing.             'useImplicitConversion' => false, // Set to true if you want to automatically convert currency and units.         ];                 $oAuth2Credential = (new OAuth2TokenBuilder())         ->fromFile($_SERVER['DOCUMENT_ROOT'] . '/google-ads-php/google_ads_php.ini')         ->build();         $googleAdsClient = (new GoogleAdsClientBuilder())         ->fromFile($_SERVER['DOCUMENT_ROOT'] . '/google-ads-php/google_ads_php.ini')         ->withOAuth2Credential($oAuth2Credential)         ->build();                  $pageUrl = null;         $keywords = ['marketing','seo','advertising'];                        $locationIds = [21167];         $geoTargetConstants =  array_map(function ($locationId) {             return ResourceNames::forGeoTargetConstant($locationId);         }, $locationIds);         $keywordPlanIdeaServiceClient = $googleAdsClient->getKeywordPlanIdeaServiceClient();               $requestOptionalArgs = [];         if (empty($keywords)) {             // Only page URL was specified, so use a UrlSeed.             $requestOptionalArgs['urlSeed'] = new UrlSeed(['url' => $pageUrl]);         } elseif (is_null($pageUrl)) {             // Only keywords were specified, so use a KeywordSeed.             $requestOptionalArgs['keywordSeed'] = new KeywordSeed(['keywords' => $keywords]);         } else {             // Both page URL and keywords were specified, so use a KeywordAndUrlSeed.             $requestOptionalArgs['keywordAndUrlSeed'] =                 new KeywordAndUrlSeed(['url' => $pageUrl, 'keywords' => $keywords]);         }         $response = $keywordPlanIdeaServiceClient->generateKeywordIdeas(             [                 // Set the language resource using the provided language ID.                 'language' => ResourceNames::forLanguageConstant(1000),                 'customerId' => ***,                 // Add the resource name of each location ID to the request.                 'geoTargetConstants' => $geoTargetConstants,                 'keywordPlanNetwork' => KeywordPlanNetwork::GOOGLE_SEARCH,                 'pageSize'=>50                            ]+$requestOptionalArgs         );         // Iterate over the results and print its detail.         foreach ($response->iterateAllElements() as $result) {         var_dump($result->getText());                 } catch (GoogleAdsException $e) {         printf(             "An error occurred while generating keyword ideas: %s\n",             $e->getMessage()         );     } catch (\Throwable $e) {         printf(             "An unexpected error occurred: %s\n",             $e->getMessage()         );     } } generateKeywordIdeas($customerId, $url, $language, $locationId); ?> 

I'm attempting to use the Google Ads API Client Library for PHP with a Service Account json.

Inviting the Service Account to Google Ads account has status of "Awaiting response" - but I cannot login to the Service Account to accept the invite.

Here is the code being used:

<?php // Include the Google Ads API PHP client library require_once 'googleads_google-ads-php/vendor/autoload.php'; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsServerStreamDecorator; use Google\Ads\GoogleAds\Util\V13\ResourceNames; use Google\Ads\GoogleAds\V13\Services\GoogleAdsQuery; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; $developerToken = "developerToken"; $jsonKeyFilePath = "json_key.json"; $customerId = "CustomerId"; // Set up authentication using a service account JSON file $googleAdsClient = (new GoogleAdsClientBuilder())     ->withDeveloperToken($developerToken) ->withOAuth2Credential((new OAuth2TokenBuilder())     ->withJsonKeyFilePath($jsonKeyFilePath)     ->withScopes(['https://www.googleapis.com/auth/adwords'])     ->build())     ->build(); // Define the query to retrieve data from the age_range_view $query = "SELECT segments.date, segments.device, metrics.clicks, ad_group_criterion.criterion_id, ad_group_criterion.display_name           FROM age_range_view           LIMIT 1000"; try {     // Execute the query and get the results     $response = $googleAdsClient->getGoogleAdsServiceClient()->search($customerId, $query);     // Loop through the rows of data and extract the desired values     foreach ($response->iterateAllElements() as $googleAdsRow) {         $date = $googleAdsRow->getSegments()->getDate()->getValue();         $device = $googleAdsRow->getSegments()->getDevice()->getValue();         $clicks = $googleAdsRow->getMetrics()->getClicks()->getValue();         $criterionId = $googleAdsRow->getAdGroupCriterion()->getCriterionId()->getValue();         $displayName = $googleAdsRow->getAdGroupCriterion()->getDisplayName()->getValue();                  // Print the extracted values to the console         printf("Date: %s | Device: %s | Clicks: %d | Criterion ID: %d | Display Name: %s\n",             $date,             $device,             $clicks,             $criterionId,             $displayName         );     } } catch (GoogleAdsException $googleAdsException) {     printf("Request with ID '%s' has failed.%sGoogle Ads failure details:%s",         $googleAdsException->getRequestId(),         PHP_EOL,         PHP_EOL     );     foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {         /** @var GoogleAdsError $error */         printf("\t%s: %s%s",             $error->getErrorCode()->getErrorCode(),             $error->getMessage(),             PHP_EOL         );     } } catch (ApiException $apiException) {     printf("ApiException was thrown with message '%s'.%s",         $apiException->getMessage(),         PHP_EOL     ); } ?> 

Here is the error message:

PHP Fatal error:  Uncaught Google\ApiCore\ApiException: {     "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https:\/\/developers.google.com\/identity\/sign-in\/web\/devconsole-project.",     "code": 16,     "status": "UNAUTHENTICATED",     "details": [         {             "@type": "type.googleapis.com\/google.ads.googleads.v13.errors.GoogleAdsFailure",             "errors": [                 {                     "errorCode": {                         "authenticationError": "NOT_ADS_USER"                     },                     "message": "User in the cookie is not a valid Ads user."                 }             ],             "requestId": "requestId"         }     ] }   thrown in /data_import/googleads_google-ads-php/vendor/google/gax/src/ApiException.php on line 267 

I attempted to try adding ->withImpersonatedEmail($impersonatedEmail) to the authentication request with an account on the same project that has access to the Google Ads accounts but that did not work.

What am I missing?

I'm having trouble in creating a WhatsApp Message template, using the WhatsApp Business API.

I already can send messages, delete template, etc.

Creating the message template is the only API implementation where I'm having some dificulties. This is the code that I'm using to create a template:


public static function CreateTemplate($templateName, $templateCat, $language, $components){     $businessaccountid = .....;     $token = ....;     $ch = curl_init();     $url = 'https://graph.facebook.com/v16.0/' . $businessaccountid . '/message_templates?allow_category_change=true&name=' . $templateName . '&category=' . $templateCat . '&language=' . $language . '&components=' . $components;     //echo($url);     //curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);     //curl_setopt($ch, CURLOPT_VERBOSE , TRUE);     curl_setopt($ch, CURLOPT_URL, $url);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     curl_setopt($ch, CURLOPT_POST, 1);     $headers = array();          $headers[] = 'Authorization: Bearer ' . $token ;     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);               $result = curl_exec($ch);          if ($result === false) {         $result = curl_error($ch) . " - ".curl_errno($ch);              }else{         $resultDecode = json_decode($result);         if($resultDecode!=null){             $result = $resultDecode;         }         return($result);     }     curl_close($ch);      } 


And this is the content of the $url variable that is being used:

"https://graph.facebook.com/v16.0/....../message_templates?allow_category_change=true&name=compra_terminada&category=MARKETING&language=pt_PT&components=[{"type":"BODY","text":"Obrigado por comprar na nossa loja. Assim que o objecto for expedido, irá receber no seu email o numero de rastreamento da encomenda."},{"type":"FOOTER","text":"A minha empresa"}]" 

And this is error that it's returning from curl_error and curl_errno:

HTTP/2 stream 0 was not closed cleanly: Unknown error code (err 5) - 92 

I've already tried to use CURL_HTTP_VERSION_1_1 but with no success. The curl_exec($ch) returns a generic html page from Facebook saying:

Sorry, something went wrong. We're working on it and we'll get it fixed as soon as we can. 

What do I need to change in my code to create a WhatsApp Template Message?

Good days, I am trying to install the library with the "pecl install grpc" command and it is returning the following error: "Fatal error: Array and string offset access syntax with curly braces is no longer supported in C:\xampp\php\pear\PEAR\Config.php on line 2095".

I don't know why but it gives a PHP related syntax error.

The PHP version I'm using is:

"PHP 8.2.0 (cli) (built: Dec 6 2022 15:31:23) (ZTS Visual C++ 2019 x64) Copyright (c) The PHP Group Zend Engine v4.2.0, Copyright (c) Zend Technologies"

And it is not only that file but many more with which it gives a syntax error.

Tried reinstalling PHP and Xampp

Any solution or idea on how to fix it or install it properly?

Thank you.