Closed amitklahiri closed 4 years ago
Two options:
$googleAdsServiceClient->searchStream
but make sure to install all the requirements including the gRPC PHP extension. This is to make sure the client library can use gRPC as transport instead of REST because it is mandatory for streaming requests like searchStream
.$googleAdsServiceClient->search
which is a paginated request instead. I add a code snippet of how it could look like here:$response = $googleAdsServiceClient->search($customerId, $query, ['pageSize' => 1000]);
// Iterates over all rows in all pages and prints the requested field values for
// the campaign in each row.
foreach ($response->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
printf(
"Campaign with ID %d and name '%s' was found.%s",
$googleAdsRow->getCampaign()->getId()->getValue(),
$googleAdsRow->getCampaign()->getName()->getValue(),
PHP_EOL
);
}
Hi @PierrickVoulet .
Thank you for the reply.
Please consider the below facts that regarding my development environment.
I am developing on Windows 10.
I am using this library on Laravel 6 PHP framework.
I have installed all the require packages as mentioned in the packagist URL. https://packagist.org/packages/googleads/google-ads-php Supporting packages google/gax: ^1.3.0 google/protobuf: ^3.11.4 ulrichsg/getopt-php: ^3.2.2 monolog/monolog: ^1.23.0 || ^2.0
I am using the example available in this URL, after updated the code suitable to Laravel. https://github.com/googleads/google-ads-php/blob/master/examples/CampaignManagement/GetCampaignsByLabel.php
Here is my final code. Please have a look.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use Google_Client; use Google_Service_Analytics; use Google_Service_Drive; use DateTime; use App\Libraries;
use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V3\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\V3\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V3\Services\GoogleAdsRow; use Google\ApiCore\ApiException;
class GoogleAdsController extends Controller { private $clientId; private $code; private $scope; private $accessType; private $includeGrantedScopes; private $state; private $redirectUri; private $responseType; private $channel; private $url; private $key; private $client; private $analytics; private $viewId; private $results;
const CUSTOMER_ID = '0123456789';
public function __construct()
{
// Get all the configurations into the config object.
$config = (object) config('oauthconfig');
$googleads = (object) $config->googleads;
$this->clientId = $googleads->client_id;
$this->scope = $googleads->scope;
$this->accessType = $googleads->access_type;
$this->includeGrantedScopes = $googleads->include_granted_scopes;
$this->state = $googleads->state;
$this->redirectUri = $googleads->callback_url;
$this->responseType = $googleads->response_type;
$this->key = __DIR__ . '/key.json';
$this->client = $this->getGoogleClient();
$results = [];
}
public function getGoogleClient()
{
// Create and configure a new client object.
$this->client = new Google_Client();
$this->client->setApplicationName("phpanatics");
$this->client->setAuthConfig($this->key);
$this->client->setScopes(['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/adwords']);
return $this->client;
}
public function authenticate()
{
$code = session()->get('code');
$accessToken = $this->accessToken($code);
session()->put('access_token_googleads', $accessToken);
return redirect()->action('MediaGoogleAdsController@profile');
}
public function getAuthUrl()
{
$url = "https://accounts.google.com/o/oauth2/v2/auth?";
$url .= "response_type=" . $this->code;
$url = "&client_id=" . $this->clientId;
$url = "&redirect_uri=" . $this->redirectUri;
$url = "&state=" . $this->state;
$url = "&scope=" . $this->scope;
$url = "&access_type=" . $this->accessType;
$url = "&include_granted_scopes=" . $this->includeGrantedScopes;
return $url;
}
public function accessToken($code)
{
$client = new Google_Client();
$client->setAuthConfigFile( __DIR__ . '/secret_googleads.json');
$client->setRedirectUri('http://localhost:8000/googleads');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->authenticate($code);
$response = $client->getAccessToken();
$accessToken = $response['access_token'];
return $accessToken;
}
public function curl($url, $parameters, $content_type, $post = true)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
}
curl_setopt($ch, CURLOPT_POST, $post);
$headers = [];
$headers[] = "Content-Type: {$content_type}";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
return $result;
}
public function getResponse($url, $parameters, $content_type, $post = true)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
}
curl_setopt($ch, CURLOPT_POST, $post);
$headers = [];
$headers[] = "Content-Type: {$content_type}";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
return $result;
}
public function index()
{
$authUrl = $this->getAuthUrl();
return view('googleads/index', [
'auth' => $authUrl,
]);
}
public function profile()
{
$code = session()->get('code');
echo $code; exit;
if (session()->get('access_token_googleads') == null) {
$accessToken = $this->getAccessToken($code);
session()->put('access_token_googleads', $accessToken);
}
if (@session()->get('access_token_googleads') != null) {
// Either pass the required parameters for this example on the command line, or insert them into the constants above.
$options = (new ArgumentParser())->parseCommandArguments([
ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->withClientId('XXXXX')
->withClientSecret('XXXXX')
->withRefreshToken('XXXXX')
->build();
// Construct a Google Ads client configured from a properties file and the OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())
->withOAuth2Credential($oAuth2Credential)
->withDeveloperToken('XXXXX')
->withLoginCustomerId('0123456789')
->build();
try {
$this->runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
);
} catch (GoogleAdsException $googleAdsException) {
echo '<pre>';
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) {
echo '<pre>';
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
}
}
}
public function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all campaigns.
$query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
// Issues a search stream request.
/** @var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->search($customerId, $query);
// Iterates over all rows in all messages and prints the requested field values for
// the campaign in each row.
foreach ($stream->readAll() as $response) {
/** @var SearchGoogleAdsStreamResponse $response */
foreach ($response->getResults() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
printf(
"Campaign with ID %d and name '%s' was found.%s",
$googleAdsRow->getCampaign()->getId()->getValue(),
$googleAdsRow->getCampaign()->getName()->getValue(),
PHP_EOL
);
}
}
}
}
**Questions**
From the error, it is very clear that the method search() is a REST function, which cannot be used in this context. I will be obliged if you please reply my below queries.
1. I install the composer package of gRPC only. But do not configure it anywhere in the Laravel and the class I have attached in the code. Am I need to configure it anywhere?
2. Here is my composer configuration, "require" section.
"require": { "php": "^7.2.5", "edujugon/laravel-google-ads": "^2.1", "facebook/graph-sdk": "^5.7", "fideloper/proxy": "^4.2", "fruitcake/laravel-cors": "^1.0", "google/apiclient": "^2.4", "google/gax": "^1.3", "google/grpc-gcp": "^0.1.4", "google/protobuf": "^3.11", "googleads/google-ads-php": "^3.1", "googleads/googleads-php-lib": "^46.2", "grpc/grpc": "^1.27", "guzzlehttp/guzzle": "^6.3", "laravel/framework": "^7.0", "laravel/tinker": "^2.0", "laravel/ui": "^2.0", "phpdocumentor/reflection-docblock": "^5.1", "stripe/stripe-php": "^7.27", "ulrichsg/getopt-php": "^3.3", "xsuchy09/utm-cookie": "^2.0" },
Please help em to resolve the issue with Laravel framework ASAP.
Best Regards,
Amit
Sorry for the late reply, we are working on a Laravel code sample app and hope to publish it soon. You can already check the PR in case that helps #323 .
The complete working sample app developed with Laravel is now published. This should answer all your questions so I am closing this issue.
Hi.
Which version of the client library are you using? Latest version, after downloading using composer.
Which version of PHP are you using? I am using Laravel 7. Also using the artisan server to run the application.
Which operating system (Linux, Windows, ...) and version? Windows.
Actions taken
Expected result List of campaigns id and name.
Actual result I am using the below code snippets to display the campaign id and name list.
Getting the error in this line of code. $stream = $googleAdsServiceClient->search($customerId, $query);
Error is as below. Streaming calls are not supported while using the REST transport
Anything else we should know about your project / environment Please help me to find the solution of the problem. I am looking forward to your feedback and reply on an urgent basis.
Thanks.