Posts tagged with php

As per my question, I want to filter the campaign's metrics based on the date range filter read the below code:

 /**  * Runs the example.  *  * @param GoogleAdsClient $googleAdsClient the Google Ads API client  * @param int $customerId the customer ID  */ public static function getGoogleAdCampaigns(GoogleAdsClient $googleAdsClient, int $customerId){     $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();     // Creates a query that retrieves all campaigns.     $query = "SELECT campaign.id, campaign.name,campaign.status, metrics.impressions, metrics.clicks, metrics.conversions, metrics.ctr, metrics.average_cpc, metrics.cost_micros, campaign.start_date, campaign.end_date FROM campaign WHERE campaign.status = 'ENABLED'";     // Issues a search stream request.     /** @var GoogleAdsServerStreamDecorator $stream */     $stream = $googleAdsServiceClient->searchStream(         SearchGoogleAdsStreamRequest::build($customerId, $query)     );     // Iterates over all rows in all messages and prints the requested field values for     // the campaign in each row.     // Initialize an array to hold campaign data    $campaigns = [];    // Iterates over all rows in all messages and collects the requested field values for    // the campaign in each row.    foreach ($stream->iterateAllElements() as $googleAdsRow) {        /** @var GoogleAdsRow $googleAdsRow */        $campaigns[] = [            'id' => $googleAdsRow->getCampaign()->getId(),            'name' => $googleAdsRow->getCampaign()->getName(),            'start_date' => $googleAdsRow->getCampaign()->getStartDate(),            'end_date' => $googleAdsRow->getCampaign()->getEndDate(),            'status' => $googleAdsRow->getCampaign()->getStatus(),            'impressions' => $googleAdsRow->getMetrics()->getImpressions(),            'clicks' => $googleAdsRow->getMetrics()->getClicks(),            'conversions' => $googleAdsRow->getMetrics()->getConversions(),            'ctr' => $googleAdsRow->getMetrics()->getCtr(),            'average_cpc' => $googleAdsRow->getMetrics()->getAverageCpc(),            'cost_micros' => $googleAdsRow->getMetrics()->getCostMicros(),        ];    }    // print_r($stream->iterateAllElements());    // Return the collected campaign data array     echo json_encode($campaigns);     exit(); } 

Suppose I want to get last week's clicks, impressions last week's cost, etc.

Reference : https://groups.google.com/g/adwords-api/c/H-6qp8v-k-o?pli=1

My Google OAuth refresh token expires after one hour, even though both my OAuth and Google Ads API applications are verified and approved.

  • Both OAuth and Google Ads API apps are verified and approved.
  • Created a new client_credentials.json file after approval.
  • Using the provided Laravel example for the PHP Google Ads API.
  • Added the developer token with basic access and populated clientId and clientSecret in the google_ads_php.ini file.

For the refresh token i used command ~/go/bin/oauth2l fetch --credentials CLIENT_SECRET.json --scope adwords to obtain a refresh token. And added this token to google_ads_php.ini too.

Despite these steps, I consistently encounter a "token has been expired or revoked" error after 60 minutes.

HI im trying to create live stream RTMS url with product_items enum list. Please give me solution how i can add the products , note the product id already created in facebook and it's facebook product id, also try to assign array of enum like ['productId1','productId2'] but still not working here the code

        try {             $response = $this->fbLatest->post("/" . $this->pageID . "/live_videos", [                 'access_token' => $this->accessToken,                 'status' => 'LIVE_NOW',                 'title' => 'testtsss',                 'description' => 'asdsadasdadasdadadad',                 'product_items' =>                  [                         array(                             'id' => "25252395334406077",                             'retailer_id' => "25252395334406077",                             'product_id' => "25252395334406077",                             'position' => array(                                 'x' => 0.1,                                 'y' => 0.1                             ),                             'start_time_offset_ms' => 0,                             'end_time_offset_ms' => 60000                         ),                 ]             ]);             $graphNode = $response->getGraphNode();             $stream_url = $graphNode->getField('stream_url');             $streamID = $graphNode->getField('id');             dd($graphNode , $stream_url);         } catch (\Facebook\Exceptions\FacebookResponseException $e) {             dd($e);             echo 'Graph returned an error: ' . $e->getMessage();         } catch (\Facebook\Exceptions\FacebookSDKException $e) {             dd($e);             echo 'Facebook SDK returned an error: ' . $e->getMessage();         } 

here the error:

Please help with this.

I have the following code executing when a user logs in to facebook:

FB.Event.subscribe('auth.authResponseChange', checkLoginState); 

Here is the code to analayse:

    function checkLoginState(response) {         if (response.authResponse) {             // User is signed-in Facebook.             const unsubscribe = onAuthStateChanged(auth, (firebaseUser) => {                 unsubscribe();                 // Check if we are already signed-in Firebase with the correct user.                 if (!isUserEqual(response.authResponse, firebaseUser)) {                     // Build Firebase credential with the Facebook auth token.                     const credential = FacebookAuthProvider.credential(                         response.authResponse.accessToken);                     // Sign in with the credential from the Facebook user.                     let x = signInWithCredential(auth, credential)                         .catch((error) => {                             // Handle Errors here.                             const errorCode = error.code;                             const errorMessage = error.message;                             // The email of the user's account used.                             const email = error.customData.email;                             // The AuthCredential type that was used.                             const credential = FacebookAuthProvider.credentialFromError(error);                             alert("Login failed. Please try again.");                         });                     x.then((userCredential) => {                         // Signed in                         const user = userCredential.user;                         // login(response.authResponse.accessToken, firebasetoken???);                     });                 } else {                     // User is already signed-in Firebase with the correct user.                     console.log(response);                     // login(response.authResponse.accessToken, firebasetoken???);                 }             });         } else {             // User is signed-out of Facebook.             signOut(auth);         }     } 

I'm unsure how to pass the FIREBASE login token to verify in the backend (with kreait):

        $auth = (new Factory)             ->withServiceAccount($_ENV["PATH"].$_ENV['config']['storage']['firebase']['firebase']['file'] ?? 'firebase-service-account.json')             ->createAuth();         // verify token         $verifiedIdToken = $auth->verifyIdToken($token);         $uid = $verifiedIdToken->getClaim('sub'); // throws an InvalidToken when invalid 

Kreait docs: https://github.com/kreait/firebase-php

Any help is appreciated.

I've set up an OAuth2 web project as well as a Service Account. Both IDs have been added with domain-wide delegation with the adwords scope in my Google Workspace.

I have a Google Ads Manager account with a Developer Key (it's in test mode, if that matters?). The email I'm trying to authenticate with for either method is an Admin in the domain and on the relevant Ads Manager and Ads accounts.

No matter what I do, I get the following error.

{     "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.v16.errors.GoogleAdsFailure",             "errors": [                 {                     "errorCode": {                         "authenticationError": "OAUTH_TOKEN_HEADER_INVALID"                     },                     "message": "Oauth token HTTP header is malformed."                 }             ],             "requestId": "9QCN5RO9mRkmS1ULtDAKMA"         }     ] } 

If I try to use the service account email as the impersonateEmail parameter, I get a NOT_ADS_USER. I've invited it to the Ads Manager account, but am not sure how to accept that invite. I think it would result in the same OAUTH_TOKEN_HEADER_INVALID, anyways.

This is within a Laravel project.

$oauth2 = (new OAuth2TokenBuilder())                 ->withClientId(config('google.client_id'))                 ->withClientSecret(config('google.client_secret'))                 ->withRefreshToken(config('googleads.refresh_token'))                 ->build(); 
$oauth2 = (new OAuth2TokenBuilder())                 ->withJsonKeyFilePath(realpath(config('google.service.file')))                 ->withScopes('https://www.googleapis.com/auth/adwords')                 ->withImpersonatedEmail(config('googleads.impersonated_email'))                 ->build(); 

What's strange is that, using either OAuth2Token instance, I can run fetchAuthToken(), and I see that the object gets its access_token. I can also see in Google\ApiCore\CredentialsWrapper::getAuthorizationHeaderCallback that it is added as the authorization Bearer token.

Here's how my GoogleAdsClient is built:

$this->client = (new GoogleAdsClientBuilder())                 ->withOAuth2Credential($oauth2)                 ->withDeveloperToken(config('google.developer_key'))                 ->usingGapicV2Source(true)                 ->build(); 

And here's the request that fails with the OAUTH_TOKEN_HEADER_INVALID:

$requestArgs = [             // Set the language resource using the provided language ID.             'language' => $this->getLanguageConstant(),             'customer_id' => $this->getCustomerId(),             // Add the resource name of each location ID to the request. - currently an empty array             'geo_target_constants' => $this->getGeoTargetConstants(),             // Set the network. To restrict to only Google Search, change the parameter below to             'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH,         ] + $requestOptionalArgs;         $response = $ideaClient->generateKeywordIdeas(             new GenerateKeywordIdeasRequest($requestArgs)         ); 

I've been going in circles on this for over a day. Thank you in advance!