An error occurred while uploading adjustments.

41 views
Skip to first unread message

Kazumasa Sato

unread,
Apr 11, 2024, 10:55:05 PM4/11/24
to Google Ads API and AdWords API Forum
An error occurred while uploading adjustments.
I am asking this question because I would like to resolve the error.
I tried to upload the adjustment by referring to the article at the URL below.

https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments?hl=ja

When I tried to upload, the following error message was output.
Error Message: 'The conversion action specified in the adjustment request cannot be found. Make sure it's available in this account., at conversion_adjustments[0].conversion_action'.

Environment
 TimeZone: Asia/Tokyo
 Language:PHP 8.0.30
 Framework:Laravel 8.75
 Google Ads API : V15
 RDB : Mysql 8.0.34

The actual code is as follows.

-------------------- START --------------------

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use GetOpt\GetOpt;
use Google\ApiCore\ApiException;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\V15\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V15\Services\UploadClickConversionsResponse;

use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V15\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V15\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Util\V15\ResourceNames;
use Google\Ads\GoogleAds\V15\Services\ClickConversion;
use Google\Ads\GoogleAds\V15\Services\ClickConversionResult;
use Google\Ads\GoogleAds\V15\Services\ConversionAdjustment;
use Google\Ads\GoogleAds\V15\Services\ConversionAdjustmentResult;
use Google\Ads\GoogleAds\V15\Services\GclidDateTimePair;
use Google\Ads\GoogleAds\V15\Services\RestatementValue;
use Google\Ads\GoogleAds\V15\Enums\ConversionAdjustmentTypeEnum\ConversionAdjustmentType;
use Google\Ads\GoogleAds\V15\Services\CustomVariable;

use App\Models\Evaluation;
use App\Models\ReferSite;
use App\Models\ConversionAction;

use App\Services\ChatWorkService;

class GoogleCooperationCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:googleCooperation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Google API Collaboration';

    /**
     * MCC Account ID
     *
     * @var [type]
     */
    protected $customer_id = null;
    protected $alert_message_header = null;
    protected $alert_messages = [];
    protected $execute_count = 0;
    protected $success_count = 0;
    protected $new_count = 0;
    protected $adjust_count = 0;


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->customer_id = config('app.google.customer_id');
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $now_date = Carbon::now()->format("Y-m-d H:i:s");
        $dial_ids = ReferSite::where('start_date', '<=', $now_date)
                    ->where('end_date', '>=', $now_date)
                    ->pluck('dial_id')
                    ->toArray();
        $dial_ids = array_unique($dial_ids);

        $from_date = Carbon::now()->format("Y-m-d") . " 00:00:00";
        $dist_date = Carbon::now()->format("Y-m-d") . " 23:59:59";
        $ini_file = $this->project_root . '/google_ads_php.ini';

        $oAuth2Credential = (new OAuth2TokenBuilder())
            ->fromFile($ini_file)
            ->build();

        $this->google_ads_client = (new GoogleAdsClientBuilder())
            ->fromFile($ini_file)
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            foreach($dial_ids as $dial_id) {
$this->alert_message_header = "";
$this->alert_messages = [];
$this->execute_count = 0;
$this->success_count = 0;
$this->new_count = 0;
$this->adjust_count = 0;
                $refer_site = ReferSite::where('dial_id', '=', $dial_id)->first();
                $this->alert_message_header = "GOOGLE {$refer_site->site_name}[ID:{$refer_site->dial_id}]";

                $new_evaluation_ids = Evaluation::where('dial_id', '=', $dial_id)
                                        ->where('import_count', '=', 0)
                                        ->whereIn('source', ['google_ads', 'google_adwords', 'google_p_max'])
                                        ->pluck("id")->toArray(); //  期間指定はいらない?
                $adjustment_evaluation_ids_org = Evaluation::where('dial_id', '=', $dial_id)
                                                    ->where('import_count', '>', 0)
                                                    ->where('value', '>', 0)
                                                    ->whereIn('source', ['google_ads', 'google_adwords', 'google_p_max'])
                                                    ->whereBetween('updated_at', [$from_date, $dist_date])
                                                    ->pluck("id")->toArray();

                $adjustment_evaluation_ids = [];

                foreach($adjustment_evaluation_ids_org as $adjustment_evaluation_id) {
                    if(!in_array($adjustment_evaluation_id, $new_evaluation_ids)) $adjustment_evaluation_ids[] = $adjustment_evaluation_id;
                }

                $new_evaluations = Evaluation::whereIn('id', $new_evaluation_ids)->get();
                $adjustment_evaluations = Evaluation::whereIn('id', $adjustment_evaluation_ids)->get();

                if(count($new_evaluations) > 0) {
                    $this->upload($new_evaluations, "new");
                }
                if(count($adjustment_evaluations) > 0) {
                    $this->upload($adjustment_evaluations, "adjustment");
                }
                $this->sendAlert();
            }
        } catch (\Throwable $th) {
            \Log::debug("GoogleCooperationCommand::handle() Error:" . $th->getMessage());
        }

        return 0;
    }

    /**
     * Collaboration API
     *
     * @param [type] $evaluations
     * @param [type] $type
     * @return void
     */
    public function upload($evaluations, $type)
    {
        try {
            if(count($evaluations) == 0) return;

            foreach($evaluations as $evaluation) {
$this->execute_count++;
                //  調整日時
                $dt = new Carbon($evaluation->updated_at);
                $adjustment_date = $dt->format("Y-m-d H:i:s+09:00");
                //  コンバーションアクションID取得
                $conversion_action_id = $this->getConversionActionId($evaluation);
                $dt = new Carbon($evaluation->conversion_date);
                $conversion_date = $dt->format("Y-m-d H:i:s+09:00");

                switch ($evaluation->clid_name) {
                    case 'gclid':
                        switch ($type) {
                            case 'new':
                                $this->datumImportNew(
                                    $conversion_action_id,
                                    $evaluation->clid,
                                    null,
                                    null,
                                    null,
                                    $conversion_date,
                                    $evaluation->value,
                                    null,
                                    $evaluation->value
                                );
                                break;
                            case 'adjustment':
                            default:
                                $this->datumImportAdjust(
                                    $conversion_action_id,
                                    $evaluation->clid,
                                    'RESTATEMENT',
                                    $conversion_date,
                                    $adjustment_date,
                                    $evaluation->value
                                );
                                break;
                        }
                        break;
                    case 'gbraid':
                        switch ($type) {
                            case 'new':
                                $this->datumImportNew(
                                    $conversion_action_id,
                                    null,
                                    $evaluation->clid,
                                    null,
                                    null,
                                    $conversion_date,
                                    $evaluation->value,
                                    null,
                                    $evaluation->value
                                );
                                break;
                            case 'adjustment':
                            default:
                                $this->datumImportAdjust(
                                    $conversion_action_id,
                                    $evaluation->clid,
                                    'RESTATEMENT',
                                    $conversion_date,
                                    $adjustment_date,
                                    $evaluation->value
                                );
                                break;
                        }
                        break;
                    case 'wbraid':
                    default:
                        switch ($type) {
                            case 'new':
                                $this->datumImportNew(
                                    $conversion_action_id,
                                    $evaluation->clid,
                                    null,
                                    null,
                                    null,
                                    $conversion_date,
                                    $evaluation->value,
                                    null,
                                    $evaluation->value
                                );
                                break;
                            case 'adjustment':
                            default:
                                $this->datumImportAdjust(
                                    $conversion_action_id,
                                    $evaluation->clid,
                                    'RESTATEMENT',
                                    $conversion_date,
                                    $adjustment_date,
                                    $evaluation->value
                                );
                                break;
                        }
                        break;
                }
                $evaluation->import_count++;
                $evaluation->save();
            }
            return;
        } catch (\Throwable $th) {
            \Log::debug("GoogleCooperationCommand::upload() Error:" . $th->getMessage());
            throw $th;
            return;
        }
    }

    /**
     * Conversion Adjustment
     *
     * @param integer $conversion_action_id
     * @param string $gclid
     * @param string $adjustment_type
     * @param string $conversion_date_time
     * @param string $adjustment_date_time
     * @param float $restatement_value
     * @return void
     */
    public function datumImportAdjust(
        int $conversion_action_id,
        string $gclid,
        string $adjustment_type,
        string $conversion_date_time,
        string $adjustment_date_time,
        float $restatement_value
    ) {
        ini_set('memory_limit', '1024M');
        $debug_mesage = "";
        try {
            $conversionadjustment_type = ConversionAdjustmentType::value($adjustment_type);

            // Associates conversion adjustments with the existing conversion action.
            // The GCLID should have been uploaded before with a conversion.
            $conversionAdjustment = new ConversionAdjustment([
                'conversion_action'      => ResourceNames::forConversionAction($this->customer_id, $conversion_action_id),
                'adjustment_type'        => $conversionadjustment_type,
                'gclid_date_time_pair'   => new GclidDateTimePair([
                    'gclid'                  => $gclid,
                    'conversion_date_time'   => $conversion_date_time
                ]),
                'adjustment_date_time'   => $adjustment_date_time
            ]);

            // Sets adjusted value for adjustment type RESTATEMENT.
            if (
                $restatement_value !== null
                && $conversionadjustment_type === ConversionAdjustmentType::RESTATEMENT
            ) {
                $conversionAdjustment->setRestatementValue(new RestatementValue([
                    'adjusted_value' => $restatement_value
                ]));
            }

            // Issues a request to upload the conversion adjustment.
            $conversionAdjustmentUploadServiceClient = $this->google_ads_client->getConversionAdjustmentUploadServiceClient();

            $response = $conversionAdjustmentUploadServiceClient->uploadConversionAdjustments($this->customer_id, [$conversionAdjustment], true, []);

            // Prints the status message if any partial failure error is returned.
            // Note: The details of each partial failure error are not printed here, you can refer to
            // the example HandlePartialFailure.php to learn more.
            if ($response->hasPartialFailureError()) {
                $debug_mesage = sprintf(
                    "A partial failure has occurred: '%s'.%s",
                    $response->getPartialFailureError()->getMessage(),
                    PHP_EOL
                );
                $this->alert_messages[] = $debug_mesage;
            } else {
                // Prints the result if exists.
                /** @var ConversionAdjustmentResult $uploadedConversionAdjustment */
                $uploadedConversionAdjustment = $response->getResults()[0];
                $debug_mesage = sprintf(
                    "Conversion adjustments uploaded  [%s] Google Click ID '%s'.%s",
                    $uploadedConversionAdjustment->getConversionAction(),
                    $uploadedConversionAdjustment->getGclidDateTimePair()->getGclid(),
                    PHP_EOL
                );
$this->success_count++;
$this->adjust_count++;
            }
        } catch (\Throwable $th) {
            \Log::debug("GoogleCooperationCommand::datumImportAdjust() Error:" . $th->getMessage());
$this->alert_messages[] = $th->getMessage() . "\n";
            throw $th;
        }
    }

    /**
     * sendAlert()
     *
     * @return void
     */
    public function sendAlert()
    {
        try {
if($this->execute_count > 0){
$chatGroupId = config('app.alert_group_id');

$users = [
['id' => xxxxxxx, 'name' => 'User1'],
['id' => xxxxxxx, 'name' => 'User2'],
['id' => xxxxxxx, 'name' => 'User3'],
];

$chat_body = "";
foreach($users as $user){
$chat_body .= "[To:{$user['id']}]{$user['name']}さん\n";
}

$chat_body .= $this->alert_message_header . "\n";
$chat_body .= "合計:" . $this->success_count . " / " . $this->execute_count . " 件\n";
$chat_body .= "新規:" . $this->new_count . " 件\n";
$chat_body .= "調整:" . $this->adjust_count . " 件\n";
if(count($this->alert_messages) > 0){
$chat_body .= "[hr][code]";
$chat_body .= implode("", $this->alert_messages);
$chat_body .= "[/code]";
}

$chat_body = "[info]{$chat_body}[/info]";

$chat_result = ChatWorkService::sendMessageChat($chatGroupId, $chat_body);
if(empty($chat_result)){
$success = true;
};
}
        } catch (\Throwable $th) {
            \Log::debug("GoogleCooperationCommand::sendAlert() Error:" . $th->getMessage());
            throw $th;
        }
    }
}
-------------------- END --------------------

Google Ads API Forum Advisor

unread,
Apr 16, 2024, 4:17:45 AM4/16/24
to shinseo...@gmail.com, adwor...@googlegroups.com
Hi,

Thank you for reaching out to the Google Ads API support team.

By reviewing your query, I understand that you encountered an error message "The conversion action specified in the adjustment request cannot be found." when uploading adjustments. Attempting to upload an adjustment using a different account results in a NO_CONVERSION_ACTION_FOUND error. This error also occurs if the conversion action of the adjustment is not enabled. Could you confirm whether you have followed Requirements while adjusting conversions in the API.

First, determine if the account is using cross-account conversion tracking by comparing the customer.conversion_tracking_setting.google_ads_conversion_customer to the customer.resource_name.
SELECT

  customer.conversion_tracking_setting.conversion_tracking_id,

  customer.conversion_tracking_setting.conversion_tracking_status,

  customer.conversion_tracking_setting.cross_account_conversion_tracking_id,

 customer.conversion_tracking_setting.google_ads_conversion_customer

FROM customer
You may need to check the account reflected in google_ads_conversion_customer that manages conversions for the account. That said, you may need to upload to the correct account to avoid said error.

Please note that the provided information is not sufficient to investigate the issue further, provide us with the complete API logs (request and response with request-id and request header) generated at your end so that we can better assist you.

If you are using a client library and haven't enabled the logging yet, I would request you to enable logging for the specific client library that you are using. You can refer to the guide PHP to enable logging at your end. For REST interface requests, you can enable logging via the curl command by using the -i flag.

You can send the details via Reply privately to the author option, or direct private reply to this email.

 
This message is in relation to case "ref:!00D1U01174p.!5004Q02tP3T4:ref" (ADR-00230877)

Thanks,
 
Google Logo Google Ads API Team


Reply all
Reply to author
Forward
0 new messages