PageRenderTime 79ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/AdWords/v201705/Extensions/AddGoogleMyBusinessLocationExtensions.php

https://bitbucket.org/dealerinspire/googleads-php-lib
PHP | 223 lines | 123 code | 29 blank | 71 comment | 4 complexity | e8134528004bc35f06bf1db33ff3cddb MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. /**
  3. * Copyright 2017 Google Inc. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\AdsApi\Examples\AdWords\v201705\Extensions;
  18. require __DIR__ . '/../../../../vendor/autoload.php';
  19. use Google\AdsApi\AdWords\AdWordsServices;
  20. use Google\AdsApi\AdWords\AdWordsSession;
  21. use Google\AdsApi\AdWords\AdWordsSessionBuilder;
  22. use Google\AdsApi\AdWords\v201705\cm\ApiException;
  23. use Google\AdsApi\AdWords\v201705\cm\ConstantOperand;
  24. use Google\AdsApi\AdWords\v201705\cm\ConstantOperandConstantType;
  25. use Google\AdsApi\AdWords\v201705\cm\CustomerFeed;
  26. use Google\AdsApi\AdWords\v201705\cm\CustomerFeedOperation;
  27. use Google\AdsApi\AdWords\v201705\cm\CustomerFeedService;
  28. use Google\AdsApi\AdWords\v201705\cm\Feed;
  29. use Google\AdsApi\AdWords\v201705\cm\MatchingFunction;
  30. use Google\AdsApi\AdWords\v201705\cm\FeedOrigin;
  31. use Google\AdsApi\AdWords\v201705\cm\FeedOperation;
  32. use Google\AdsApi\AdWords\v201705\cm\FeedService;
  33. use Google\AdsApi\AdWords\v201705\cm\FunctionOperator;
  34. use Google\AdsApi\AdWords\v201705\cm\OAuthInfo;
  35. use Google\AdsApi\AdWords\v201705\cm\Operator;
  36. use Google\AdsApi\AdWords\v201705\cm\PlacesLocationFeedData;
  37. use Google\AdsApi\Common\OAuth2TokenBuilder;
  38. /**
  39. * This example adds a feed that syncs feed items from a Google
  40. * My Business (GMB) account and associates the feed with a customer.
  41. */
  42. class AddGoogleMyBusinessLocationExtensions {
  43. // The placeholder type for location extensions.
  44. // See the Placeholder reference page for a list of all the placeholder types
  45. // and fields.
  46. // https://developers.google.com/adwords/api/docs/appendix/placeholders
  47. const PLACEHOLDER_LOCATION = 7;
  48. // The maximum number of CustomerFeed ADD operation attempts to make before
  49. // throwing an exception.
  50. const MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10;
  51. // The email address of either an owner or a manager of the GMB account.
  52. const GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS';
  53. // If the gmbEmailAddress above is for a GMB manager instead of the GMB
  54. // account owner, then set businessAccountIdentifier to the +Page ID of a
  55. // location for which the manager has access. See the location extensions
  56. // guide at https://developers.google.com/adwords/api/docs/guides/feed-services-locations
  57. // for details.
  58. const BUSINESS_ACCOUNT_IDENTIFIER = null;
  59. public static function runExample(
  60. AdWordsServices $adWordsServices,
  61. AdWordsSession $session,
  62. $gmbEmailAddress,
  63. $gmbAccessToken,
  64. $gmbBusinessAccountId
  65. ) {
  66. $feedService = $adWordsServices->get($session, FeedService::class);
  67. // Create a feed that will sync to the Google My Business account specified
  68. // by $gmbEmailAddress. Do not add FeedAttributes to this object, as AdWords
  69. // will add them automatically because this will be a system generated feed.
  70. $gmbFeed = new Feed();
  71. $gmbFeed->setName('Google My Business feed #' . uniqid());
  72. $feedData = new PlacesLocationFeedData();
  73. $feedData->setEmailAddress($gmbEmailAddress);
  74. $feedData->setBusinessAccountIdentifier($gmbBusinessAccountId);
  75. // Optional: specify labels to filter Google My Business listings. If
  76. // specified, only listings that have any of the labels set are
  77. // synchronized into FeedItems.
  78. $feedData->setLabelFilters(['Stores in New York City']);
  79. $oAuthInfo = new OAuthInfo();
  80. $oAuthInfo->setHttpMethod('GET');
  81. $oAuthInfo->setHttpRequestUrl('https://www.googleapis.com/auth/adwords');
  82. $oAuthInfo->setHttpAuthorizationHeader(
  83. sprintf('Bearer %s', $gmbAccessToken));
  84. $feedData->setOAuthInfo($oAuthInfo);
  85. $gmbFeed->setSystemFeedGenerationData($feedData);
  86. // Since this feed's feed items will be managed by AdWords,
  87. // you must set its origin to ADWORDS.
  88. $gmbFeed->setOrigin(FeedOrigin::ADWORDS);
  89. // Create a feed operation and add it to the list.
  90. $operation = new FeedOperation();
  91. $operation->setOperator(Operator::ADD);
  92. $operation->setOperand($gmbFeed);
  93. $operations = [$operation];
  94. // Add the feed on the server. Since it is a system generated feed, AdWords
  95. // will automatically:
  96. // 1. Set up the FeedAttributes on the feed.
  97. // 2. Set up a FeedMapping that associates the FeedAttributes of the feed
  98. // with the placeholder fields of the LOCATION placeholder type.
  99. $addedFeed = $feedService->mutate($operations)->getValue()[0];
  100. printf("Added GMB feed with ID %d\n", $addedFeed->getId());
  101. $customerFeedService =
  102. $adWordsServices->get($session, CustomerFeedService::class);
  103. // Add a CustomerFeed that associates the feed with this customer for
  104. // the LOCATION placeholder type.
  105. $customerFeed = new CustomerFeed();
  106. $customerFeed->setFeedId($addedFeed->getId());
  107. $customerFeed->setPlaceholderTypes([self::PLACEHOLDER_LOCATION]);
  108. // Create a matching function that will always evaluate to true.
  109. $customerMatchingFunction = new MatchingFunction();
  110. $constOperand = new ConstantOperand();
  111. $constOperand->setType(ConstantOperandConstantType::BOOLEAN);
  112. $constOperand->setBooleanValue(true);
  113. $customerMatchingFunction->setLhsOperand([$constOperand]);
  114. $customerMatchingFunction->setOperator(FunctionOperator::IDENTITY);
  115. $customerFeed->setMatchingFunction($customerMatchingFunction);
  116. // Create a customer feed operation and add it to the list.
  117. $operation = new CustomerFeedOperation();
  118. $operation->setOperand($customerFeed);
  119. $operation->setOperator(Operator::ADD);
  120. $operations = [$operation];
  121. // After the completion of the Feed ADD operation above the added feed will
  122. // not be available for usage in a CustomerFeed until the sync between the
  123. // AdWords and GMB accounts completes. The loop below will retry adding
  124. // the CustomerFeed up to ten times with an exponential back-off policy.
  125. $addedCustomerFeed = null;
  126. $numberOfAttempts = 0;
  127. do {
  128. $numberOfAttempts++;
  129. try {
  130. $addedCustomerFeed =
  131. $customerFeedService->mutate($operations)->getValue()[0];
  132. printf("Attempt #%d to add the CustomerFeed was successful\n",
  133. $numberOfAttempts);
  134. } catch (ApiException $e) {
  135. // Wait using exponential backoff policy
  136. $sleepSeconds = 5 * pow(2, $numberOfAttempts);
  137. printf(
  138. "Attempt #%d to add the CustomerFeed was not successful. "
  139. . "Waiting %d seconds before trying again.\n",
  140. $numberOfAttempts,
  141. $sleepSeconds
  142. );
  143. sleep($sleepSeconds);
  144. }
  145. } while ($numberOfAttempts < self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS
  146. && $addedCustomerFeed === null);
  147. if ($addedCustomerFeed === null) {
  148. throw new Exception('Could not create the CustomerFeed after '
  149. . self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS . ' attempts. Please retry '
  150. . 'the CustomerFeed ADD operation later.');
  151. }
  152. printf(
  153. "Added CustomerFeed for feed ID %d and placeholder type %d\n",
  154. $addedCustomerFeed->getFeedId(),
  155. $addedCustomerFeed->getPlaceholderTypes()[0]
  156. );
  157. // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at the
  158. // Campaign level. This will be similar to the CampaignFeed in the
  159. // AddSitelinks example, except you can also filter based on the business
  160. // name and category of each FeedItem by using a FeedAttributeOperand in
  161. // your matching function.
  162. // OPTIONAL: Create an AdGroupFeed for even more fine grained control over
  163. // which feed items are used at the AdGroup level.
  164. }
  165. public static function main() {
  166. // Generate a refreshable OAuth2 credential for authentication.
  167. $oAuth2Credential = (new OAuth2TokenBuilder())
  168. ->fromFile()
  169. ->build();
  170. // If the GMB_EMAIL_ADDRESS is the same user you used to generate your
  171. // AdWords API refresh token, leave the assignment below unchanged.
  172. // Otherwise, to obtain an access token for your GMB account, run the
  173. // Auth/GetRefreshToken example. Make sure you are logged in as the same
  174. // user as GMB_EMAIL_ADDRESS above when you follow the link provided by the
  175. // example then call fetchAuthToken on the generated oAuth2 object and copy
  176. // and paste its 'access_token' value into the assignment below.
  177. $gmbAccessToken = $oAuth2Credential->fetchAuthToken()['access_token'];
  178. // Construct an API session configured from a properties file and the OAuth2
  179. // credentials above.
  180. $session = (new AdWordsSessionBuilder())
  181. ->fromFile()
  182. ->withOAuth2Credential($oAuth2Credential)
  183. ->build();
  184. self::runExample(
  185. new AdWordsServices(),
  186. $session,
  187. self::GMB_EMAIL_ADDRESS,
  188. $gmbAccessToken,
  189. (self::BUSINESS_ACCOUNT_IDENTIFIER === null) ? null
  190. : intval(self::BUSINESS_ACCOUNT_IDENTIFIER)
  191. );
  192. }
  193. }
  194. AddGoogleMyBusinessLocationExtensions::main();