UploadOfflineConversion.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. /**
  3. * Copyright 2019 Google LLC
  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. * https://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 App\Services;
  18. use App\Facade\TableName;
  19. use GetOpt\GetOpt;
  20. use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
  21. use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
  22. use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
  23. use Google\Ads\GoogleAds\Lib\V14\GoogleAdsClient;
  24. use Google\Ads\GoogleAds\Lib\V14\GoogleAdsClientBuilder;
  25. use Google\Ads\GoogleAds\Lib\V14\GoogleAdsException;
  26. use Google\Ads\GoogleAds\Util\V14\ResourceNames;
  27. use Google\Ads\GoogleAds\V14\Errors\GoogleAdsError;
  28. use Google\Ads\GoogleAds\V14\Services\ClickConversion;
  29. use Google\Ads\GoogleAds\V14\Services\ClickConversionResult;
  30. use Google\Ads\GoogleAds\V14\Services\CustomVariable;
  31. use Google\Ads\GoogleAds\V14\Services\UploadClickConversionsRequest;
  32. use Google\Ads\GoogleAds\V14\Services\UploadClickConversionsResponse;
  33. use Google\ApiCore\ApiException;
  34. use Illuminate\Support\Facades\DB;
  35. /**
  36. * This code example imports offline conversion values for specific clicks to your account.
  37. * To get Google Click ID for a click, use the "click_view" resource:
  38. * https://developers.google.com/google-ads/api/fields/latest/click_view.
  39. * To set up a conversion action, run the AddConversionAction.php example.
  40. */
  41. class UploadOfflineConversion
  42. {
  43. public static function reg(int $UserID, array $params)
  44. {
  45. $userinfo=DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
  46. ->where('UserID', $UserID)->select("Channel","CustomID","LastLogonPackage")->first();
  47. $Channel = $userinfo->Channel;
  48. $package = $userinfo->LastLogonPackage;
  49. $adConfig=config('googleAd')[$package]??config('googleAd')[$Channel];
  50. if(!isset($adConfig))return;
  51. self::runbefore($adConfig['customerId'],$adConfig['reg'],1,$params['gclid'],$params['gbraid'],$params['wbraid']);
  52. }
  53. public static function pay(int $Channel, array $params,$payamt,string $package)
  54. {
  55. $adConfig=config('googleAd')[$package]??config('googleAd')[$Channel];
  56. if(!isset($adConfig))return;
  57. self::runbefore($adConfig['customerId'],$adConfig['pay'],$payamt,$params['gclid'],$params['gbraid'],$params['wbraid']);
  58. }
  59. public static function d0(int $Channel, array $params,string $package)
  60. {
  61. $adConfig=config('googleAd')[$package]??config('googleAd')[$Channel];
  62. if(!isset($adConfig))return;
  63. self::runbefore($adConfig['customerId'],$adConfig['d0'],1,$params['gclid'],$params['gbraid'],$params['wbraid']);
  64. }
  65. public static function d1(int $Channel, array $params,string $package)
  66. {
  67. $adConfig=config('googleAd')[$package]??config('googleAd')[$Channel];
  68. if(!isset($adConfig))return;
  69. self::runbefore($adConfig['customerId'],$adConfig['d1'],1,$params['gclid'],$params['gbraid'],$params['wbraid']);
  70. }
  71. private static function runbefore(int $customerId,
  72. int $conversionActionId,
  73. float $conversionValue,
  74. ?string $gclid,
  75. ?string $gbraid,
  76. ?string $wbraid
  77. )
  78. {
  79. if($gbraid=='{gbraid}')$gbraid=null;
  80. if($wbraid=='{wbraid}')$wbraid=null;
  81. // Generate a refreshable OAuth2 credential for authentication.
  82. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
  83. // Construct a Google Ads client configured from a properties file and the
  84. // OAuth2 credentials above.
  85. $googleAdsClient = (new GoogleAdsClientBuilder())
  86. ->fromFile()
  87. ->withOAuth2Credential($oAuth2Credential)
  88. // We set this value to true to show how to use GAPIC v2 source code. You can remove the
  89. // below line if you wish to use the old-style source code. Note that in that case, you
  90. // probably need to modify some parts of the code below to make it work.
  91. // For more information, see
  92. // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
  93. ->usingGapicV2Source(true)
  94. ->build();
  95. try {
  96. self::upload(
  97. $googleAdsClient,
  98. $customerId,
  99. $conversionActionId,
  100. $gclid,
  101. $gbraid,
  102. $wbraid,
  103. date("yyyy-mm-dd hh:mm:ss") . "-03:00",
  104. $conversionValue,
  105. null,
  106. null
  107. );
  108. } catch (GoogleAdsException $googleAdsException) {
  109. Util::WriteLog("googleAd", sprintf(
  110. "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
  111. $googleAdsException->getRequestId(),
  112. PHP_EOL,
  113. PHP_EOL
  114. ));
  115. foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
  116. /** @var GoogleAdsError $error */
  117. Util::WriteLog("googleAd", sprintf(
  118. "\t%s: %s%s",
  119. $error->getErrorCode()->getErrorCode(),
  120. $error->getMessage(),
  121. PHP_EOL
  122. ));
  123. }
  124. exit(1);
  125. } catch (ApiException $apiException) {
  126. Util::WriteLog("googleAd", sprintf(
  127. "ApiException was thrown with message '%s'.%s",
  128. $apiException->getMessage(),
  129. PHP_EOL
  130. ));
  131. exit(1);
  132. }
  133. }
  134. /**
  135. * Runs the example.
  136. *
  137. * @param GoogleAdsClient $googleAdsClient the Google Ads API client
  138. * @param int $customerId the customer ID
  139. * @param int $conversionActionId the ID of the conversion action to upload to
  140. * @param string|null $gclid the GCLID for the conversion (should be newer than the number of
  141. * days set on the conversion window of the conversion action). If set, GBRAID and WBRAID
  142. * must be null
  143. * @param string|null $gbraid The GBRAID identifier for an iOS app conversion. If set, GCLID and
  144. * WBRAID must be null
  145. * @param string|null $wbraid The WBRAID identifier for an iOS web conversion. If set, GCLID and
  146. * GBRAID must be null
  147. * @param string $conversionDateTime the date and time of the conversion (should be after the
  148. * click time). The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g.
  149. * “2019-01-01 12:32:45-08:00”
  150. * @param float $conversionValue the value of the conversion
  151. * @param string|null $conversionCustomVariableId the ID of the conversion custom variable to
  152. * associate with the upload
  153. * @param string|null $conversionCustomVariableValue the value of the conversion custom
  154. * variable to associate with the upload
  155. */
  156. // [START upload_offline_conversion]
  157. private static function upload(
  158. GoogleAdsClient $googleAdsClient,
  159. int $customerId,
  160. int $conversionActionId,
  161. ?string $gclid,
  162. ?string $gbraid,
  163. ?string $wbraid,
  164. string $conversionDateTime,
  165. float $conversionValue,
  166. ?string $conversionCustomVariableId,
  167. ?string $conversionCustomVariableValue
  168. )
  169. {
  170. // Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required.
  171. // See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details.
  172. $nonNullFields = array_filter(
  173. [$gclid, $gbraid, $wbraid],
  174. function ($field) {
  175. return !is_null($field);
  176. }
  177. );
  178. if (count($nonNullFields) !== 1) {
  179. throw new \UnexpectedValueException(
  180. sprintf(
  181. "Exactly 1 of gclid, gbraid or wbraid is required, but %d ID values were "
  182. . "provided",
  183. count($nonNullFields)
  184. )
  185. );
  186. }
  187. // Creates a click conversion by specifying currency as USD.
  188. $clickConversion = new ClickConversion([
  189. 'conversion_action' =>
  190. ResourceNames::forConversionAction($customerId, $conversionActionId),
  191. 'conversion_value' => $conversionValue,
  192. 'conversion_date_time' => $conversionDateTime,
  193. 'currency_code' => 'USD'
  194. ]);
  195. // Sets the single specified ID field.
  196. if (!is_null($gclid)) {
  197. $clickConversion->setGclid($gclid);
  198. } elseif (!is_null($gbraid)) {
  199. $clickConversion->setGbraid($gbraid);
  200. } else {
  201. $clickConversion->setWbraid($wbraid);
  202. }
  203. if (!is_null($conversionCustomVariableId) && !is_null($conversionCustomVariableValue)) {
  204. $clickConversion->setCustomVariables([new CustomVariable([
  205. 'conversion_custom_variable' => ResourceNames::forConversionCustomVariable(
  206. $customerId,
  207. $conversionCustomVariableId
  208. ),
  209. 'value' => $conversionCustomVariableValue
  210. ])]);
  211. }
  212. // Issues a request to upload the click conversion.
  213. $conversionUploadServiceClient = $googleAdsClient->getConversionUploadServiceClient();
  214. /** @var UploadClickConversionsResponse $response */
  215. $response = $conversionUploadServiceClient->uploadClickConversions(
  216. UploadClickConversionsRequest::build($customerId, [$clickConversion], true)
  217. );
  218. // Prints the status message if any partial failure error is returned.
  219. // Note: The details of each partial failure error are not printed here, you can refer to
  220. // the example HandlePartialFailure.php to learn more.
  221. if ($response->hasPartialFailureError()) {
  222. Util::WriteLog("googleAd", sprintf(
  223. "Partial failures occurred: '%s'.%s",
  224. $response->getPartialFailureError()->getMessage(),
  225. PHP_EOL
  226. ));
  227. } else {
  228. // Prints the result if exists.
  229. /** @var ClickConversionResult $uploadedClickConversion */
  230. $uploadedClickConversion = $response->getResults()[0];
  231. Util::WriteLog("googleAd", sprintf(
  232. "Uploaded click conversion that occurred at '%s' from Google Click ID '%s' " .
  233. "to '%s'.%s",
  234. $uploadedClickConversion->getConversionDateTime(),
  235. $uploadedClickConversion->getGclid(),
  236. $uploadedClickConversion->getConversionAction(),
  237. PHP_EOL
  238. ));
  239. }
  240. }
  241. // [END upload_offline_conversion]
  242. }