علاقه مند به اشتراک گذاری بازخورد خود در مورد Google Ads API هستید؟ برای دعوت به شرکت در تحقیقات کاربر
ثبت نام کنید !
دارایی فرم سرب را اضافه کنید
با مجموعهها، منظم بمانید
ذخیره و دستهبندی محتوا براساس اولویتهای شما.
جاوا
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.assets;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v19.common.LeadFormAsset;
import com.google.ads.googleads.v19.common.LeadFormDeliveryMethod;
import com.google.ads.googleads.v19.common.LeadFormField;
import com.google.ads.googleads.v19.common.LeadFormSingleChoiceAnswers;
import com.google.ads.googleads.v19.common.WebhookDelivery;
import com.google.ads.googleads.v19.enums.AssetFieldTypeEnum.AssetFieldType;
import com.google.ads.googleads.v19.enums.LeadFormCallToActionTypeEnum.LeadFormCallToActionType;
import com.google.ads.googleads.v19.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType;
import com.google.ads.googleads.v19.enums.LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType;
import com.google.ads.googleads.v19.errors.GoogleAdsError;
import com.google.ads.googleads.v19.errors.GoogleAdsException;
import com.google.ads.googleads.v19.resources.Asset;
import com.google.ads.googleads.v19.resources.CampaignAsset;
import com.google.ads.googleads.v19.services.AssetOperation;
import com.google.ads.googleads.v19.services.AssetServiceClient;
import com.google.ads.googleads.v19.services.CampaignAssetOperation;
import com.google.ads.googleads.v19.services.CampaignAssetServiceClient;
import com.google.ads.googleads.v19.services.MutateAssetsResponse;
import com.google.ads.googleads.v19.services.MutateCampaignAssetsResponse;
import com.google.ads.googleads.v19.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.java to create a
* campaign.
*/
public class AddLeadFormAsset {
private static class AddLeadFormAssetParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private long campaignId;
}
public static void main(String[] args) {
AddLeadFormAssetParams params = new AddLeadFormAssetParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddLeadFormAsset().runExample(googleAdsClient, params.customerId, params.campaignId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// Creates a lead form asset.
String leadFormAssetResourceName = createLeadFormAsset(googleAdsClient, customerId);
// Creates a lead form asset for the campaign.
createLeadFormExtension(googleAdsClient, customerId, campaignId, leadFormAssetResourceName);
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @return the resource name of the newly created lead form asset.
*/
private static String createLeadFormAsset(GoogleAdsClient googleAdsClient, long customerId) {
// Creates the lead form asset.
Asset leadFormAsset =
Asset.newBuilder()
.setName("Interplanetary Cruise #" + getPrintableDateTime() + " Lead Form")
.setLeadFormAsset(
LeadFormAsset.newBuilder()
// Specify the details of the asset that the users will see.
.setCallToActionType(LeadFormCallToActionType.BOOK_NOW)
.setCallToActionDescription("Latest trip to Jupiter!")
// Define the form details.
.setBusinessName("Interplanetary Cruise")
.setHeadline("Trip to Jupiter")
.setDescription("Our latest trip to Jupiter is now open for booking.")
.setPrivacyPolicyUrl("http://example.com/privacy")
// Define the fields to be displayed to the user.
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.FULL_NAME)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.EMAIL)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PHONE_NUMBER)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PREFERRED_CONTACT_TIME)
.setSingleChoiceAnswers(
LeadFormSingleChoiceAnswers.newBuilder()
.addAnswers("Before 9 AM")
.addAnswers("Any time")
.addAnswers("After 5 PM")
.build())
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.TRAVEL_BUDGET)
.build())
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.java.
// .setBackgroundImageAsset("INSERT_IMAGE_ASSET_HERE")
// Optional: Define the response page after the user signs up on the form.
.setPostSubmitHeadline("Thanks for signing up!")
.setPostSubmitDescription(
"We will reach out to you shortly. Visit our website "
+ "to see past trip details.")
.setPostSubmitCallToActionType(LeadFormPostSubmitCallToActionType.VISIT_SITE)
// Optional: Display a custom disclosure that displays along with Google
// disclaimer on the form.
.setCustomDisclosure("Trip may get cancelled due to meteor shower.")
// Optional: Define a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
.addDeliveryMethods(
LeadFormDeliveryMethod.newBuilder()
.setWebhook(
WebhookDelivery.newBuilder()
.setAdvertiserWebhookUrl("http://example.com/webhook")
.setGoogleSecret("interplanetary google secret")
.setPayloadSchemaVersion(3L)
.build())
.build())
.build())
.addFinalUrls("http://example.com/jupiter")
.build();
// Creates an operation to add the asset.
AssetOperation operation = AssetOperation.newBuilder().setCreate(leadFormAsset).build();
// Issues a mutate request to add the asset and prints its information.
try (AssetServiceClient client =
googleAdsClient.getLatestVersion().createAssetServiceClient()) {
MutateAssetsResponse response =
client.mutateAssets(String.valueOf(customerId), ImmutableList.of(operation));
String resourceName = response.getResultsList().get(0).getResourceName();
System.out.printf("Created asset with resource name '%s'.%n", resourceName);
return resourceName;
}
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
* @param leadFormAssetResourceName the resource name of the lead form asset to be added.
*/
private static void createLeadFormExtension(
GoogleAdsClient googleAdsClient,
long customerId,
long campaignId,
String leadFormAssetResourceName) {
// Creates the campaign asset for the lead form.
CampaignAsset campaignAsset =
CampaignAsset.newBuilder()
.setAsset(leadFormAssetResourceName)
.setFieldType(AssetFieldType.LEAD_FORM)
.setCampaign(ResourceNames.campaign(customerId, campaignId))
.build();
// Creates an operation to add the campaign asset.
CampaignAssetOperation operation =
CampaignAssetOperation.newBuilder().setCreate(campaignAsset).build();
// Issues a mutate request to add the campaign asset and prints its information.
try (CampaignAssetServiceClient client =
googleAdsClient.getLatestVersion().createCampaignAssetServiceClient()) {
MutateCampaignAssetsResponse response =
client.mutateCampaignAssets(String.valueOf(customerId), ImmutableList.of(operation));
System.out.printf(
"Created campaign asset with resource name '%s' for campaign ID %d.%n",
response.getResultsList().get(0).getResourceName(), campaignId);
}
}
}
سی شارپ
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V19.Common;
using Google.Ads.GoogleAds.V19.Errors;
using Google.Ads.GoogleAds.V19.Resources;
using Google.Ads.GoogleAds.V19.Services;
using System;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormCallToActionTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormFieldUserInputTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormPostSubmitCallToActionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V19
{
/// <summary>
/// This code example creates a lead form asset for a campaign. Run
/// AddCampaigns.cs to create a campaign.
/// </summary>
public class AddLeadFormAsset : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddLeadFormAsset"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which lead form assets are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which lead form assets are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
AddLeadFormAsset codeExample = new AddLeadFormAsset();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a lead form for a campaign. " +
"Run AddCampaigns.cs to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form assets are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Create a lead form asset.
string leadFormAssetResourceName = CreateLeadFormAsset(client, customerId);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the lead form asset.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The lead form asset resource name.</returns>
private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V19.AssetService);
// Creates the lead form asset.
Asset leadFormAsset = new Asset()
{
Name = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
LeadFormAsset = new LeadFormAsset()
{
// Specify the details of the asset that the users will see.
CallToActionType = LeadFormCallToActionType.BookNow,
CallToActionDescription = "Latest trip to Jupiter!",
// Define the form details.
BusinessName = "Interplanetary Cruise",
Headline = "Trip to Jupiter",
Description = "Our latest trip to Jupiter is now open for booking.",
PrivacyPolicyUrl = "http://example.com/privacy",
// Define the fields to be displayed to the user.
Fields = {
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.FullName,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.Email,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PhoneNumber,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PreferredContactTime,
SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
{
Answers = { "Before 9 AM", "Any time", "After 5 PM" }
}
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.TravelBudget,
},
},
// Optional: You can also specify a background image asset. To upload an asset,
// see Misc/UploadImageAsset.cs. BackgroundImageAsset =
// "INSERT_IMAGE_ASSET_HERE",
// Optional: Define the response page after the user signs up on the form.
PostSubmitHeadline = "Thanks for signing up!",
PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
"to see past trip details.",
PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,
// Optional: Display a custom disclosure that displays along with the Google
// disclaimer on the form.
CustomDisclosure = "Trip may get cancelled due to meteor shower.",
// Optional: Define a delivery method for the form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
DeliveryMethods =
{
new LeadFormDeliveryMethod()
{
Webhook = new WebhookDelivery()
{
AdvertiserWebhookUrl = "http://example.com/webhook",
GoogleSecret = "interplanetary google secret",
PayloadSchemaVersion = 3L
}
}
},
},
FinalUrls = { "http://example.com/jupiter" }
};
// Creates the operation.
AssetOperation operation = new AssetOperation()
{
Create = leadFormAsset,
};
// Makes the API call.
MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
new[] { operation });
string leadFormAssetResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
"was created.");
return leadFormAssetResourceName;
}
}
}
PHP
<?php
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Ads\GoogleAds\Examples\Extensions;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V19\ResourceNames;
use Google\Ads\GoogleAds\V19\Common\LeadFormAsset;
use Google\Ads\GoogleAds\V19\Common\LeadFormDeliveryMethod;
use Google\Ads\GoogleAds\V19\Common\LeadFormField;
use Google\Ads\GoogleAds\V19\Common\LeadFormSingleChoiceAnswers;
use Google\Ads\GoogleAds\V19\Common\WebhookDelivery;
use Google\Ads\GoogleAds\V19\Enums\AssetFieldTypeEnum\AssetFieldType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormCallToActionTypeEnum\LeadFormCallToActionType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormFieldUserInputTypeEnum\LeadFormFieldUserInputType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormPostSubmitCallToActionTypeEnum\LeadFormPostSubmitCallToActionType;
use Google\Ads\GoogleAds\V19\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V19\Resources\Asset;
use Google\Ads\GoogleAds\V19\Resources\CampaignAsset;
use Google\Ads\GoogleAds\V19\Services\AssetOperation;
use Google\Ads\GoogleAds\V19\Services\CampaignAssetOperation;
use Google\Ads\GoogleAds\V19\Services\MutateAssetsRequest;
use Google\Ads\GoogleAds\V19\Services\MutateCampaignAssetsRequest;
use Google\ApiCore\ApiException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.php to create a
* campaign.
*/
class AddLeadFormAsset
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
public static function main()
{
// 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,
ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// Construct a Google Ads client configured from a properties file and the
// OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
try {
self::runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
$options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
);
} catch (GoogleAdsException $googleAdsException) {
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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId
) {
// Creates a lead form asset.
$leadFormAssetResourceName = self::createLeadFormAsset($googleAdsClient, $customerId);
// Creates a lead form asset for the campaign.
self::createLeadFormCampaignAsset(
$googleAdsClient,
$customerId,
$campaignId,
$leadFormAssetResourceName
);
}
/**
* Creates the lead form asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @return string the resource name of the newly created lead form asset
*/
private static function createLeadFormAsset(
GoogleAdsClient $googleAdsClient,
int $customerId
): string {
// Creates the lead form asset.
$leadFormAsset = new Asset([
'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime() . ' Lead Form',
'lead_form_asset' => new LeadFormAsset([
// Specifies the details of the asset that the users will see.
'call_to_action_type' => LeadFormCallToActionType::BOOK_NOW,
'call_to_action_description' => 'Latest trip to Jupiter!',
// Defines the form details.
'business_name' => 'Interplanetary Cruise',
'headline' => 'Trip to Jupiter',
'description' => 'Our latest trip to Jupiter is now open for booking.',
'privacy_policy_url' => 'http://example.com/privacy',
// Defines the fields to be displayed to the user.
'fields' => [
new LeadFormField(['input_type' => LeadFormFieldUserInputType::FULL_NAME]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::EMAIL]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::PHONE_NUMBER]),
new LeadFormField([
'input_type' => LeadFormFieldUserInputType::PREFERRED_CONTACT_TIME,
'single_choice_answers' => new LeadFormSingleChoiceAnswers([
'answers' => ['Before 9 AM', 'Any time', 'After 5 PM']
])
]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::TRAVEL_BUDGET])
],
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.php.
// 'background_image_asset' => 'INSERT_IMAGE_ASSET_RESOURCE_NAME_HERE',
// Optional: Defines the response page after the user signs up on the form.
'post_submit_headline' => 'Thanks for signing up!',
'post_submit_description' => 'We will reach out to you shortly. '
. 'Visit our website to see past trip details.',
'post_submit_call_to_action_type' => LeadFormPostSubmitCallToActionType::VISIT_SITE,
// Optional: Displays a custom disclosure that displays along with Google
// disclaimer on the form.
'custom_disclosure' => 'Trip may get cancelled due to meteor shower.',
// Optional: Defines a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
'delivery_methods' => [new LeadFormDeliveryMethod([
'webhook' => new WebhookDelivery([
'advertiser_webhook_url' => 'http://example.com/webhook',
'google_secret' => 'interplanetary google secret',
'payload_schema_version' => 3
])
])]
]),
'final_urls' => ['http://example.com/jupiter']
]);
// Creates an operation to add the asset.
$assetOperation = new AssetOperation();
$assetOperation->setCreate($leadFormAsset);
// Issues a mutate request to add the asset and prints its information.
$assetServiceClient = $googleAdsClient->getAssetServiceClient();
$response = $assetServiceClient->mutateAssets(
MutateAssetsRequest::build($customerId, [$assetOperation])
);
$assetResourceName = $response->getResults()[0]->getResourceName();
printf("Created an asset with resource name: '%s'.%s", $assetResourceName, PHP_EOL);
return $assetResourceName;
}
/**
* Creates the lead form campaign asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $campaignId the campaign ID to add the lead form asset
* @param string $leadFormAssetResourceName the resource name of the lead form asset to be added
*/
private static function createLeadFormCampaignAsset(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
string $leadFormAssetResourceName
) {
// Creates the campaign asset for the lead form.
$campaignAsset = new CampaignAsset([
'asset' => $leadFormAssetResourceName,
'field_type' => AssetFieldType::LEAD_FORM,
'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
]);
// Creates an operation to add the campaign asset.
$campaignAssetOperation = new CampaignAssetOperation();
$campaignAssetOperation->setCreate($campaignAsset);
// Issues a mutate request to add the campaign asset and prints its information.
$campaignAssetServiceClient = $googleAdsClient->getCampaignAssetServiceClient();
$response = $campaignAssetServiceClient->mutateCampaignAssets(
MutateCampaignAssetsRequest::build($customerId, [$campaignAssetOperation])
);
printf(
"Created a campaign asset with resource name '%s' for campaign ID %d.%s",
$response->getResults()[0]->getResourceName(),
$campaignId,
PHP_EOL
);
}
}
AddLeadFormAsset::main();
پایتون
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a lead form and a lead form extension for a campaign.
Run add_campaigns.py to create a campaign.
"""
import argparse
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, campaign_id):
"""Creates a lead form and lead form extension for the given campaign.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
lead_form_asset_resource_name = create_lead_form_asset(client, customer_id)
create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
)
def create_lead_form_asset(client, customer_id):
"""Creates a lead form asset using the given customer ID.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
Returns:
A str of the resource name for the newly created lead form asset.
"""
asset_service = client.get_service("AssetService")
asset_operation = client.get_type("AssetOperation")
asset = asset_operation.create
asset.name = f"Interplanetary Cruise #{uuid4()} Lead Form"
asset.final_urls.append("http://example.com/jupiter")
# Creates a new LeadFormAsset instance.
lead_form_asset = asset.lead_form_asset
# Specify the details of the extension that the users will see.
lead_form_asset.call_to_action_type = (
client.enums.LeadFormCallToActionTypeEnum.BOOK_NOW
)
lead_form_asset.call_to_action_description = "Latest trip to Jupiter!"
# Define the form details.
lead_form_asset.business_name = "Interplanetary Cruise"
lead_form_asset.headline = "Trip to Jupiter"
lead_form_asset.description = (
"Our latest trip to Jupiter is now open for booking."
)
lead_form_asset.privacy_policy_url = "http://example.com/privacy"
# Define the fields to be displayed to the user.
input_type_enum = client.enums.LeadFormFieldUserInputTypeEnum
lead_form_field_1 = client.get_type("LeadFormField")
lead_form_field_1.input_type = input_type_enum.FULL_NAME
lead_form_asset.fields.append(lead_form_field_1)
lead_form_field_2 = client.get_type("LeadFormField")
lead_form_field_2.input_type = input_type_enum.EMAIL
lead_form_asset.fields.append(lead_form_field_2)
lead_form_field_3 = client.get_type("LeadFormField")
lead_form_field_3.input_type = input_type_enum.PHONE_NUMBER
lead_form_asset.fields.append(lead_form_field_3)
lead_form_field_4 = client.get_type("LeadFormField")
lead_form_field_4.input_type = input_type_enum.PREFERRED_CONTACT_TIME
lead_form_field_4.single_choice_answers.answers.extend(
["Before 9 AM", "Anytime", "After 5 PM"]
)
lead_form_asset.fields.append(lead_form_field_4)
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image.py.
# lead_form_asset.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lead_form_asset.post_submit_headline = "Thanks for signing up!"
lead_form_asset.post_submit_description = (
"We will reach out to you shortly. Visit our website to see past trip "
"details."
)
lead_form_asset.post_submit_call_to_action_type = (
client.enums.LeadFormPostSubmitCallToActionTypeEnum.VISIT_SITE
)
# Optional: Display a custom disclosure that displays along with the Google
# disclaimer on the form.
lead_form_asset.custom_disclosure = (
"Trip may get cancelled due to meteor shower"
)
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
delivery_method = client.get_type("LeadFormDeliveryMethod")
delivery_method.webhook.advertiser_webhook_url = (
"http://example.com/webhook"
)
delivery_method.webhook.google_secret = "interplanetary google secret"
delivery_method.webhook.payload_schema_version = 3
lead_form_asset.delivery_methods.append(delivery_method)
asset_service = client.get_service("AssetService")
response = asset_service.mutate_assets(
customer_id=customer_id, operations=[asset_operation]
)
resource_name = response.results[0].resource_name
print(f"Asset with resource name {resource_name} was created.")
return resource_name
def create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
):
"""Creates the lead form campaign asset.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
campaign_service = client.get_service("CampaignService")
campaign_asset_service = client.get_service("CampaignAssetService")
campaign_asset_operation = client.get_type("CampaignAssetOperation")
campaign_asset = campaign_asset_operation.create
campaign_asset.asset = lead_form_asset_resource_name
campaign_asset.field_type = client.enums.AssetFieldTypeEnum.LEAD_FORM
campaign_asset.campaign = campaign_service.campaign_path(
customer_id, campaign_id
)
response = campaign_asset_service.mutate_campaign_assets(
customer_id=customer_id, operations=[campaign_asset_operation]
)
for result in response.results:
print(
"Created campaign asset with resource name "
f'"{result.resource_name}" for campaign with ID {campaign_id}'
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This code example creates a lead form and a lead form "
"asset for a campaign. Run add_campaigns.py to create a "
"campaign."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-i",
"--campaign_id",
type=str,
required=True,
help="The ID of a Campaign belonging to the given customer.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v19")
try:
main(googleads_client, args.customer_id, args.campaign_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
روبی
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Creates a lead form and a lead form asset for a campaign.
#
# Run add_campaigns.rb to create a campaign.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_lead_form_asset(customer_id, campaign_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
lead_form_asset = create_lead_form_asset(
client,
customer_id,
)
create_lead_form_campaign_asset(
client,
customer_id,
campaign_id,
lead_form_asset,
)
end
def create_lead_form_asset(client, customer_id)
operation = client.operation.create_resource.asset do |a|
a.name = "Interplanetary Cruise #{(Time.new.to_f * 1000).to_i} Lead Form"
a.final_urls << "http://example.com/jupiter"
a.lead_form_asset = client.resource.lead_form_asset do |lfa|
lfa.call_to_action_type = :BOOK_NOW
lfa.call_to_action_description = "Latest trip to Jupiter!"
lfa.business_name = "Interplanetary Cruise"
lfa.headline = "Trip to Jupiter"
lfa.description = "Our latest trip to Jupiter is now open for booking."
lfa.privacy_policy_url = "http://example.com/privacy"
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :FULL_NAME
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :EMAIL
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PHONE_NUMBER
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PREFERRED_CONTACT_TIME
lff.single_choice_answers = client.resource.lead_form_single_choice_answers do |sca|
sca.answers += ["Before 9 AM", "Anytime", "After 5 PM"]
end
end
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.rb.
# lfa.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lfa.post_submit_headline = "Thanks for signing up!"
lfa.post_submit_description = "We will reach out to you shortly. " \
"Visit our website to see past trip details."
lfa.post_submit_call_to_action_type = :VISIT_SITE
# Optional
# lfa.custom_disclosure = "Trip may get cancelled due to meteor shower."
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
lfa.delivery_methods << client.resource.lead_form_delivery_method do |lfdm|
lfdm.webhook = client.resource.webhook_delivery do |wd|
wd.advertiser_webhook_url = "http://example.com/webhook"
wd.google_secret = "interplanetary google secret"
wd.payload_schema_version = 3
end
end
end
end
response = client.service.asset.mutate_assets(
customer_id: customer_id,
operations: [operation],
)
asset_name = response.results.first.resource_name
puts "Asset with resource name #{asset_name} was created."
asset_name
end
def create_lead_form_campaign_asset(client, customer_id, campaign_id, lead_form_asset)
operation = client.operation.create_resource.campaign_asset do |ca|
ca.asset = lead_form_asset
ca.field_type = :LEAD_FORM
ca.campaign = client.path.campaign(customer_id, campaign_id)
end
response = client.service.campaign_asset.mutate_campaign_assets(
customer_id: customer_id,
operations: [operation],
)
puts "Created campaign asset #{response.results.first.resource_name} for " \
"campaign #{campaign_id}."
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
options[:campaign_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_lead_form_asset(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:campaign_id),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
پرل
#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example creates a lead form and a lead form asset for a campaign.
# Run add_campaigns.pl to create a campaign.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V19::Resources::CampaignAsset;
use Google::Ads::GoogleAds::V19::Resources::Asset;
use Google::Ads::GoogleAds::V19::Common::LeadFormAsset;
use Google::Ads::GoogleAds::V19::Common::LeadFormField;
use Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers;
use Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod;
use Google::Ads::GoogleAds::V19::Common::WebhookDelivery;
use Google::Ads::GoogleAds::V19::Enums::AssetFieldTypeEnum qw(LEAD_FORM);
use Google::Ads::GoogleAds::V19::Enums::LeadFormCallToActionTypeEnum
qw(BOOK_NOW);
use Google::Ads::GoogleAds::V19::Enums::LeadFormFieldUserInputTypeEnum
qw(FULL_NAME EMAIL PHONE_NUMBER PREFERRED_CONTACT_TIME TRAVEL_BUDGET);
use Google::Ads::GoogleAds::V19::Enums::LeadFormPostSubmitCallToActionTypeEnum
qw(VISIT_SITE);
use
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation;
use Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V19::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
sub add_lead_form_asset {
my ($api_client, $customer_id, $campaign_id) = @_;
# Create a lead form asset.
my $lead_form_asset_resource_name =
create_lead_form_asset($api_client, $customer_id);
# Create a lead form asset for the campaign.
create_lead_form_campaign_asset($api_client, $customer_id, $campaign_id,
$lead_form_asset_resource_name);
return 1;
}
# Creates the lead form campaign asset.
sub create_lead_form_campaign_asset {
my ($api_client, $customer_id, $campaign_id, $lead_form_asset_resource_name)
= @_;
# Create the campaign asset for the lead form.
my $campaign_asset =
Google::Ads::GoogleAds::V19::Resources::CampaignAsset->new({
asset => $lead_form_asset_resource_name,
fieldType => LEAD_FORM,
campaign => Google::Ads::GoogleAds::V19::Utils::ResourceNames::campaign(
$customer_id, $campaign_id
)});
my $campaign_asset_operation =
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation
->new({
create => $campaign_asset
});
my $campaign_assets_response = $api_client->CampaignAssetService()->mutate({
customerId => $customer_id,
operations => [$campaign_asset_operation]});
printf
"Created campaign asset with resource name = '%s' for campaign ID %d.\n",
$campaign_assets_response->{results}[0]{resourceName}, $campaign_id;
}
# Creates the lead form asset.
sub create_lead_form_asset {
my ($api_client, $customer_id) = @_;
# Create the lead form asset.
my $lead_form_asset = Google::Ads::GoogleAds::V19::Resources::Asset->new({
name => "Interplanetary Cruise Lead Form #" . uniqid(),
leadFormAsset => Google::Ads::GoogleAds::V19::Common::LeadFormAsset->new({
# Specify the details of lead form that the users will see.
callToActionType => BOOK_NOW,
callToActionDescription => "Latest trip to Jupiter!",
# Define the form details.
businessName => "Interplanetary Cruise",
headline => "Trip to Jupiter",
description => "Our latest trip to Jupiter is now open for booking.",
privacyPolicyUrl => "http://example.com/privacy",
# Define the fields to be displayed to the user.
fields => [
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => FULL_NAME
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => EMAIL
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PHONE_NUMBER
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PREFERRED_CONTACT_TIME,
singleChoiceAnswers =>
Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers
->new({
answers => ["Before 9 AM", "Any time", "After 5 PM"]})}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => TRAVEL_BUDGET
})
],
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.pl.
# backgroundImageAsset => "INSERT_IMAGE_ASSET_HERE",
# Optional: Define the response page after the user signs up on the form.
postSubmitHeadline => "Thanks for signing up!",
postSubmitDescription => "We will reach out to you shortly. " .
"Visit our website to see past trip details.",
postSubmitCallToActionType => VISIT_SITE,
# Optional: Display a custom disclosure that displays along with the
# Google disclaimer on the form.
customDisclosure => "Trip may get cancelled due to meteor shower.",
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for
# more details on how to define a webhook.
deliveryMethods => [
Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod->new({
webhook =>
Google::Ads::GoogleAds::V19::Common::WebhookDelivery->new({
advertiserWebhookUrl => "http://example.com/webhook",
googleSecret => "interplanetary google secret",
payloadSchemaVersion => 3
})})]}
),
finalUrls => ["http://example.com/jupiter"]});
# Create the operation.
my $asset_operation =
Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation->new({
create => $lead_form_asset
});
my $assets_response = $api_client->AssetService()->mutate({
customerId => $customer_id,
operations => [$asset_operation]});
my $lead_form_asset_resource_name =
$assets_response->{results}[0]{resourceName};
# Display the result.
printf "Asset with resource name = '%s' was created.\n",
$lead_form_asset_resource_name;
return $lead_form_asset_resource_name;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_id);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
if not check_params($customer_id, $campaign_id);
# Call the example.
add_lead_form_asset($api_client, $customer_id =~ s/-//gr, $campaign_id);
=pod
=head1 NAME
add_lead_form_asset
=head1 DESCRIPTION
This code example creates a lead form and a lead form asset for a campaign.
Run add_campaigns.pl to create a campaign.
=head1 SYNOPSIS
add_lead_form_asset.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-campaign_id ID of the campaign to which lead form assets are added.
=cut
،
جاوا
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.assets;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v19.common.LeadFormAsset;
import com.google.ads.googleads.v19.common.LeadFormDeliveryMethod;
import com.google.ads.googleads.v19.common.LeadFormField;
import com.google.ads.googleads.v19.common.LeadFormSingleChoiceAnswers;
import com.google.ads.googleads.v19.common.WebhookDelivery;
import com.google.ads.googleads.v19.enums.AssetFieldTypeEnum.AssetFieldType;
import com.google.ads.googleads.v19.enums.LeadFormCallToActionTypeEnum.LeadFormCallToActionType;
import com.google.ads.googleads.v19.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType;
import com.google.ads.googleads.v19.enums.LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType;
import com.google.ads.googleads.v19.errors.GoogleAdsError;
import com.google.ads.googleads.v19.errors.GoogleAdsException;
import com.google.ads.googleads.v19.resources.Asset;
import com.google.ads.googleads.v19.resources.CampaignAsset;
import com.google.ads.googleads.v19.services.AssetOperation;
import com.google.ads.googleads.v19.services.AssetServiceClient;
import com.google.ads.googleads.v19.services.CampaignAssetOperation;
import com.google.ads.googleads.v19.services.CampaignAssetServiceClient;
import com.google.ads.googleads.v19.services.MutateAssetsResponse;
import com.google.ads.googleads.v19.services.MutateCampaignAssetsResponse;
import com.google.ads.googleads.v19.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.java to create a
* campaign.
*/
public class AddLeadFormAsset {
private static class AddLeadFormAssetParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private long campaignId;
}
public static void main(String[] args) {
AddLeadFormAssetParams params = new AddLeadFormAssetParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddLeadFormAsset().runExample(googleAdsClient, params.customerId, params.campaignId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// Creates a lead form asset.
String leadFormAssetResourceName = createLeadFormAsset(googleAdsClient, customerId);
// Creates a lead form asset for the campaign.
createLeadFormExtension(googleAdsClient, customerId, campaignId, leadFormAssetResourceName);
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @return the resource name of the newly created lead form asset.
*/
private static String createLeadFormAsset(GoogleAdsClient googleAdsClient, long customerId) {
// Creates the lead form asset.
Asset leadFormAsset =
Asset.newBuilder()
.setName("Interplanetary Cruise #" + getPrintableDateTime() + " Lead Form")
.setLeadFormAsset(
LeadFormAsset.newBuilder()
// Specify the details of the asset that the users will see.
.setCallToActionType(LeadFormCallToActionType.BOOK_NOW)
.setCallToActionDescription("Latest trip to Jupiter!")
// Define the form details.
.setBusinessName("Interplanetary Cruise")
.setHeadline("Trip to Jupiter")
.setDescription("Our latest trip to Jupiter is now open for booking.")
.setPrivacyPolicyUrl("http://example.com/privacy")
// Define the fields to be displayed to the user.
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.FULL_NAME)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.EMAIL)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PHONE_NUMBER)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PREFERRED_CONTACT_TIME)
.setSingleChoiceAnswers(
LeadFormSingleChoiceAnswers.newBuilder()
.addAnswers("Before 9 AM")
.addAnswers("Any time")
.addAnswers("After 5 PM")
.build())
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.TRAVEL_BUDGET)
.build())
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.java.
// .setBackgroundImageAsset("INSERT_IMAGE_ASSET_HERE")
// Optional: Define the response page after the user signs up on the form.
.setPostSubmitHeadline("Thanks for signing up!")
.setPostSubmitDescription(
"We will reach out to you shortly. Visit our website "
+ "to see past trip details.")
.setPostSubmitCallToActionType(LeadFormPostSubmitCallToActionType.VISIT_SITE)
// Optional: Display a custom disclosure that displays along with Google
// disclaimer on the form.
.setCustomDisclosure("Trip may get cancelled due to meteor shower.")
// Optional: Define a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
.addDeliveryMethods(
LeadFormDeliveryMethod.newBuilder()
.setWebhook(
WebhookDelivery.newBuilder()
.setAdvertiserWebhookUrl("http://example.com/webhook")
.setGoogleSecret("interplanetary google secret")
.setPayloadSchemaVersion(3L)
.build())
.build())
.build())
.addFinalUrls("http://example.com/jupiter")
.build();
// Creates an operation to add the asset.
AssetOperation operation = AssetOperation.newBuilder().setCreate(leadFormAsset).build();
// Issues a mutate request to add the asset and prints its information.
try (AssetServiceClient client =
googleAdsClient.getLatestVersion().createAssetServiceClient()) {
MutateAssetsResponse response =
client.mutateAssets(String.valueOf(customerId), ImmutableList.of(operation));
String resourceName = response.getResultsList().get(0).getResourceName();
System.out.printf("Created asset with resource name '%s'.%n", resourceName);
return resourceName;
}
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
* @param leadFormAssetResourceName the resource name of the lead form asset to be added.
*/
private static void createLeadFormExtension(
GoogleAdsClient googleAdsClient,
long customerId,
long campaignId,
String leadFormAssetResourceName) {
// Creates the campaign asset for the lead form.
CampaignAsset campaignAsset =
CampaignAsset.newBuilder()
.setAsset(leadFormAssetResourceName)
.setFieldType(AssetFieldType.LEAD_FORM)
.setCampaign(ResourceNames.campaign(customerId, campaignId))
.build();
// Creates an operation to add the campaign asset.
CampaignAssetOperation operation =
CampaignAssetOperation.newBuilder().setCreate(campaignAsset).build();
// Issues a mutate request to add the campaign asset and prints its information.
try (CampaignAssetServiceClient client =
googleAdsClient.getLatestVersion().createCampaignAssetServiceClient()) {
MutateCampaignAssetsResponse response =
client.mutateCampaignAssets(String.valueOf(customerId), ImmutableList.of(operation));
System.out.printf(
"Created campaign asset with resource name '%s' for campaign ID %d.%n",
response.getResultsList().get(0).getResourceName(), campaignId);
}
}
}
سی شارپ
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V19.Common;
using Google.Ads.GoogleAds.V19.Errors;
using Google.Ads.GoogleAds.V19.Resources;
using Google.Ads.GoogleAds.V19.Services;
using System;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormCallToActionTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormFieldUserInputTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormPostSubmitCallToActionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V19
{
/// <summary>
/// This code example creates a lead form asset for a campaign. Run
/// AddCampaigns.cs to create a campaign.
/// </summary>
public class AddLeadFormAsset : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddLeadFormAsset"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which lead form assets are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which lead form assets are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
AddLeadFormAsset codeExample = new AddLeadFormAsset();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a lead form for a campaign. " +
"Run AddCampaigns.cs to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form assets are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Create a lead form asset.
string leadFormAssetResourceName = CreateLeadFormAsset(client, customerId);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the lead form asset.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The lead form asset resource name.</returns>
private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V19.AssetService);
// Creates the lead form asset.
Asset leadFormAsset = new Asset()
{
Name = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
LeadFormAsset = new LeadFormAsset()
{
// Specify the details of the asset that the users will see.
CallToActionType = LeadFormCallToActionType.BookNow,
CallToActionDescription = "Latest trip to Jupiter!",
// Define the form details.
BusinessName = "Interplanetary Cruise",
Headline = "Trip to Jupiter",
Description = "Our latest trip to Jupiter is now open for booking.",
PrivacyPolicyUrl = "http://example.com/privacy",
// Define the fields to be displayed to the user.
Fields = {
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.FullName,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.Email,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PhoneNumber,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PreferredContactTime,
SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
{
Answers = { "Before 9 AM", "Any time", "After 5 PM" }
}
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.TravelBudget,
},
},
// Optional: You can also specify a background image asset. To upload an asset,
// see Misc/UploadImageAsset.cs. BackgroundImageAsset =
// "INSERT_IMAGE_ASSET_HERE",
// Optional: Define the response page after the user signs up on the form.
PostSubmitHeadline = "Thanks for signing up!",
PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
"to see past trip details.",
PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,
// Optional: Display a custom disclosure that displays along with the Google
// disclaimer on the form.
CustomDisclosure = "Trip may get cancelled due to meteor shower.",
// Optional: Define a delivery method for the form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
DeliveryMethods =
{
new LeadFormDeliveryMethod()
{
Webhook = new WebhookDelivery()
{
AdvertiserWebhookUrl = "http://example.com/webhook",
GoogleSecret = "interplanetary google secret",
PayloadSchemaVersion = 3L
}
}
},
},
FinalUrls = { "http://example.com/jupiter" }
};
// Creates the operation.
AssetOperation operation = new AssetOperation()
{
Create = leadFormAsset,
};
// Makes the API call.
MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
new[] { operation });
string leadFormAssetResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
"was created.");
return leadFormAssetResourceName;
}
}
}
PHP
<?php
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Ads\GoogleAds\Examples\Extensions;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V19\ResourceNames;
use Google\Ads\GoogleAds\V19\Common\LeadFormAsset;
use Google\Ads\GoogleAds\V19\Common\LeadFormDeliveryMethod;
use Google\Ads\GoogleAds\V19\Common\LeadFormField;
use Google\Ads\GoogleAds\V19\Common\LeadFormSingleChoiceAnswers;
use Google\Ads\GoogleAds\V19\Common\WebhookDelivery;
use Google\Ads\GoogleAds\V19\Enums\AssetFieldTypeEnum\AssetFieldType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormCallToActionTypeEnum\LeadFormCallToActionType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormFieldUserInputTypeEnum\LeadFormFieldUserInputType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormPostSubmitCallToActionTypeEnum\LeadFormPostSubmitCallToActionType;
use Google\Ads\GoogleAds\V19\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V19\Resources\Asset;
use Google\Ads\GoogleAds\V19\Resources\CampaignAsset;
use Google\Ads\GoogleAds\V19\Services\AssetOperation;
use Google\Ads\GoogleAds\V19\Services\CampaignAssetOperation;
use Google\Ads\GoogleAds\V19\Services\MutateAssetsRequest;
use Google\Ads\GoogleAds\V19\Services\MutateCampaignAssetsRequest;
use Google\ApiCore\ApiException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.php to create a
* campaign.
*/
class AddLeadFormAsset
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
public static function main()
{
// 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,
ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// Construct a Google Ads client configured from a properties file and the
// OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
try {
self::runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
$options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
);
} catch (GoogleAdsException $googleAdsException) {
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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId
) {
// Creates a lead form asset.
$leadFormAssetResourceName = self::createLeadFormAsset($googleAdsClient, $customerId);
// Creates a lead form asset for the campaign.
self::createLeadFormCampaignAsset(
$googleAdsClient,
$customerId,
$campaignId,
$leadFormAssetResourceName
);
}
/**
* Creates the lead form asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @return string the resource name of the newly created lead form asset
*/
private static function createLeadFormAsset(
GoogleAdsClient $googleAdsClient,
int $customerId
): string {
// Creates the lead form asset.
$leadFormAsset = new Asset([
'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime() . ' Lead Form',
'lead_form_asset' => new LeadFormAsset([
// Specifies the details of the asset that the users will see.
'call_to_action_type' => LeadFormCallToActionType::BOOK_NOW,
'call_to_action_description' => 'Latest trip to Jupiter!',
// Defines the form details.
'business_name' => 'Interplanetary Cruise',
'headline' => 'Trip to Jupiter',
'description' => 'Our latest trip to Jupiter is now open for booking.',
'privacy_policy_url' => 'http://example.com/privacy',
// Defines the fields to be displayed to the user.
'fields' => [
new LeadFormField(['input_type' => LeadFormFieldUserInputType::FULL_NAME]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::EMAIL]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::PHONE_NUMBER]),
new LeadFormField([
'input_type' => LeadFormFieldUserInputType::PREFERRED_CONTACT_TIME,
'single_choice_answers' => new LeadFormSingleChoiceAnswers([
'answers' => ['Before 9 AM', 'Any time', 'After 5 PM']
])
]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::TRAVEL_BUDGET])
],
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.php.
// 'background_image_asset' => 'INSERT_IMAGE_ASSET_RESOURCE_NAME_HERE',
// Optional: Defines the response page after the user signs up on the form.
'post_submit_headline' => 'Thanks for signing up!',
'post_submit_description' => 'We will reach out to you shortly. '
. 'Visit our website to see past trip details.',
'post_submit_call_to_action_type' => LeadFormPostSubmitCallToActionType::VISIT_SITE,
// Optional: Displays a custom disclosure that displays along with Google
// disclaimer on the form.
'custom_disclosure' => 'Trip may get cancelled due to meteor shower.',
// Optional: Defines a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
'delivery_methods' => [new LeadFormDeliveryMethod([
'webhook' => new WebhookDelivery([
'advertiser_webhook_url' => 'http://example.com/webhook',
'google_secret' => 'interplanetary google secret',
'payload_schema_version' => 3
])
])]
]),
'final_urls' => ['http://example.com/jupiter']
]);
// Creates an operation to add the asset.
$assetOperation = new AssetOperation();
$assetOperation->setCreate($leadFormAsset);
// Issues a mutate request to add the asset and prints its information.
$assetServiceClient = $googleAdsClient->getAssetServiceClient();
$response = $assetServiceClient->mutateAssets(
MutateAssetsRequest::build($customerId, [$assetOperation])
);
$assetResourceName = $response->getResults()[0]->getResourceName();
printf("Created an asset with resource name: '%s'.%s", $assetResourceName, PHP_EOL);
return $assetResourceName;
}
/**
* Creates the lead form campaign asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $campaignId the campaign ID to add the lead form asset
* @param string $leadFormAssetResourceName the resource name of the lead form asset to be added
*/
private static function createLeadFormCampaignAsset(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
string $leadFormAssetResourceName
) {
// Creates the campaign asset for the lead form.
$campaignAsset = new CampaignAsset([
'asset' => $leadFormAssetResourceName,
'field_type' => AssetFieldType::LEAD_FORM,
'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
]);
// Creates an operation to add the campaign asset.
$campaignAssetOperation = new CampaignAssetOperation();
$campaignAssetOperation->setCreate($campaignAsset);
// Issues a mutate request to add the campaign asset and prints its information.
$campaignAssetServiceClient = $googleAdsClient->getCampaignAssetServiceClient();
$response = $campaignAssetServiceClient->mutateCampaignAssets(
MutateCampaignAssetsRequest::build($customerId, [$campaignAssetOperation])
);
printf(
"Created a campaign asset with resource name '%s' for campaign ID %d.%s",
$response->getResults()[0]->getResourceName(),
$campaignId,
PHP_EOL
);
}
}
AddLeadFormAsset::main();
پایتون
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a lead form and a lead form extension for a campaign.
Run add_campaigns.py to create a campaign.
"""
import argparse
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, campaign_id):
"""Creates a lead form and lead form extension for the given campaign.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
lead_form_asset_resource_name = create_lead_form_asset(client, customer_id)
create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
)
def create_lead_form_asset(client, customer_id):
"""Creates a lead form asset using the given customer ID.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
Returns:
A str of the resource name for the newly created lead form asset.
"""
asset_service = client.get_service("AssetService")
asset_operation = client.get_type("AssetOperation")
asset = asset_operation.create
asset.name = f"Interplanetary Cruise #{uuid4()} Lead Form"
asset.final_urls.append("http://example.com/jupiter")
# Creates a new LeadFormAsset instance.
lead_form_asset = asset.lead_form_asset
# Specify the details of the extension that the users will see.
lead_form_asset.call_to_action_type = (
client.enums.LeadFormCallToActionTypeEnum.BOOK_NOW
)
lead_form_asset.call_to_action_description = "Latest trip to Jupiter!"
# Define the form details.
lead_form_asset.business_name = "Interplanetary Cruise"
lead_form_asset.headline = "Trip to Jupiter"
lead_form_asset.description = (
"Our latest trip to Jupiter is now open for booking."
)
lead_form_asset.privacy_policy_url = "http://example.com/privacy"
# Define the fields to be displayed to the user.
input_type_enum = client.enums.LeadFormFieldUserInputTypeEnum
lead_form_field_1 = client.get_type("LeadFormField")
lead_form_field_1.input_type = input_type_enum.FULL_NAME
lead_form_asset.fields.append(lead_form_field_1)
lead_form_field_2 = client.get_type("LeadFormField")
lead_form_field_2.input_type = input_type_enum.EMAIL
lead_form_asset.fields.append(lead_form_field_2)
lead_form_field_3 = client.get_type("LeadFormField")
lead_form_field_3.input_type = input_type_enum.PHONE_NUMBER
lead_form_asset.fields.append(lead_form_field_3)
lead_form_field_4 = client.get_type("LeadFormField")
lead_form_field_4.input_type = input_type_enum.PREFERRED_CONTACT_TIME
lead_form_field_4.single_choice_answers.answers.extend(
["Before 9 AM", "Anytime", "After 5 PM"]
)
lead_form_asset.fields.append(lead_form_field_4)
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image.py.
# lead_form_asset.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lead_form_asset.post_submit_headline = "Thanks for signing up!"
lead_form_asset.post_submit_description = (
"We will reach out to you shortly. Visit our website to see past trip "
"details."
)
lead_form_asset.post_submit_call_to_action_type = (
client.enums.LeadFormPostSubmitCallToActionTypeEnum.VISIT_SITE
)
# Optional: Display a custom disclosure that displays along with the Google
# disclaimer on the form.
lead_form_asset.custom_disclosure = (
"Trip may get cancelled due to meteor shower"
)
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
delivery_method = client.get_type("LeadFormDeliveryMethod")
delivery_method.webhook.advertiser_webhook_url = (
"http://example.com/webhook"
)
delivery_method.webhook.google_secret = "interplanetary google secret"
delivery_method.webhook.payload_schema_version = 3
lead_form_asset.delivery_methods.append(delivery_method)
asset_service = client.get_service("AssetService")
response = asset_service.mutate_assets(
customer_id=customer_id, operations=[asset_operation]
)
resource_name = response.results[0].resource_name
print(f"Asset with resource name {resource_name} was created.")
return resource_name
def create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
):
"""Creates the lead form campaign asset.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
campaign_service = client.get_service("CampaignService")
campaign_asset_service = client.get_service("CampaignAssetService")
campaign_asset_operation = client.get_type("CampaignAssetOperation")
campaign_asset = campaign_asset_operation.create
campaign_asset.asset = lead_form_asset_resource_name
campaign_asset.field_type = client.enums.AssetFieldTypeEnum.LEAD_FORM
campaign_asset.campaign = campaign_service.campaign_path(
customer_id, campaign_id
)
response = campaign_asset_service.mutate_campaign_assets(
customer_id=customer_id, operations=[campaign_asset_operation]
)
for result in response.results:
print(
"Created campaign asset with resource name "
f'"{result.resource_name}" for campaign with ID {campaign_id}'
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This code example creates a lead form and a lead form "
"asset for a campaign. Run add_campaigns.py to create a "
"campaign."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-i",
"--campaign_id",
type=str,
required=True,
help="The ID of a Campaign belonging to the given customer.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v19")
try:
main(googleads_client, args.customer_id, args.campaign_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
روبی
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Creates a lead form and a lead form asset for a campaign.
#
# Run add_campaigns.rb to create a campaign.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_lead_form_asset(customer_id, campaign_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
lead_form_asset = create_lead_form_asset(
client,
customer_id,
)
create_lead_form_campaign_asset(
client,
customer_id,
campaign_id,
lead_form_asset,
)
end
def create_lead_form_asset(client, customer_id)
operation = client.operation.create_resource.asset do |a|
a.name = "Interplanetary Cruise #{(Time.new.to_f * 1000).to_i} Lead Form"
a.final_urls << "http://example.com/jupiter"
a.lead_form_asset = client.resource.lead_form_asset do |lfa|
lfa.call_to_action_type = :BOOK_NOW
lfa.call_to_action_description = "Latest trip to Jupiter!"
lfa.business_name = "Interplanetary Cruise"
lfa.headline = "Trip to Jupiter"
lfa.description = "Our latest trip to Jupiter is now open for booking."
lfa.privacy_policy_url = "http://example.com/privacy"
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :FULL_NAME
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :EMAIL
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PHONE_NUMBER
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PREFERRED_CONTACT_TIME
lff.single_choice_answers = client.resource.lead_form_single_choice_answers do |sca|
sca.answers += ["Before 9 AM", "Anytime", "After 5 PM"]
end
end
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.rb.
# lfa.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lfa.post_submit_headline = "Thanks for signing up!"
lfa.post_submit_description = "We will reach out to you shortly. " \
"Visit our website to see past trip details."
lfa.post_submit_call_to_action_type = :VISIT_SITE
# Optional
# lfa.custom_disclosure = "Trip may get cancelled due to meteor shower."
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
lfa.delivery_methods << client.resource.lead_form_delivery_method do |lfdm|
lfdm.webhook = client.resource.webhook_delivery do |wd|
wd.advertiser_webhook_url = "http://example.com/webhook"
wd.google_secret = "interplanetary google secret"
wd.payload_schema_version = 3
end
end
end
end
response = client.service.asset.mutate_assets(
customer_id: customer_id,
operations: [operation],
)
asset_name = response.results.first.resource_name
puts "Asset with resource name #{asset_name} was created."
asset_name
end
def create_lead_form_campaign_asset(client, customer_id, campaign_id, lead_form_asset)
operation = client.operation.create_resource.campaign_asset do |ca|
ca.asset = lead_form_asset
ca.field_type = :LEAD_FORM
ca.campaign = client.path.campaign(customer_id, campaign_id)
end
response = client.service.campaign_asset.mutate_campaign_assets(
customer_id: customer_id,
operations: [operation],
)
puts "Created campaign asset #{response.results.first.resource_name} for " \
"campaign #{campaign_id}."
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
options[:campaign_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_lead_form_asset(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:campaign_id),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
پرل
#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example creates a lead form and a lead form asset for a campaign.
# Run add_campaigns.pl to create a campaign.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V19::Resources::CampaignAsset;
use Google::Ads::GoogleAds::V19::Resources::Asset;
use Google::Ads::GoogleAds::V19::Common::LeadFormAsset;
use Google::Ads::GoogleAds::V19::Common::LeadFormField;
use Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers;
use Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod;
use Google::Ads::GoogleAds::V19::Common::WebhookDelivery;
use Google::Ads::GoogleAds::V19::Enums::AssetFieldTypeEnum qw(LEAD_FORM);
use Google::Ads::GoogleAds::V19::Enums::LeadFormCallToActionTypeEnum
qw(BOOK_NOW);
use Google::Ads::GoogleAds::V19::Enums::LeadFormFieldUserInputTypeEnum
qw(FULL_NAME EMAIL PHONE_NUMBER PREFERRED_CONTACT_TIME TRAVEL_BUDGET);
use Google::Ads::GoogleAds::V19::Enums::LeadFormPostSubmitCallToActionTypeEnum
qw(VISIT_SITE);
use
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation;
use Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V19::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
sub add_lead_form_asset {
my ($api_client, $customer_id, $campaign_id) = @_;
# Create a lead form asset.
my $lead_form_asset_resource_name =
create_lead_form_asset($api_client, $customer_id);
# Create a lead form asset for the campaign.
create_lead_form_campaign_asset($api_client, $customer_id, $campaign_id,
$lead_form_asset_resource_name);
return 1;
}
# Creates the lead form campaign asset.
sub create_lead_form_campaign_asset {
my ($api_client, $customer_id, $campaign_id, $lead_form_asset_resource_name)
= @_;
# Create the campaign asset for the lead form.
my $campaign_asset =
Google::Ads::GoogleAds::V19::Resources::CampaignAsset->new({
asset => $lead_form_asset_resource_name,
fieldType => LEAD_FORM,
campaign => Google::Ads::GoogleAds::V19::Utils::ResourceNames::campaign(
$customer_id, $campaign_id
)});
my $campaign_asset_operation =
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation
->new({
create => $campaign_asset
});
my $campaign_assets_response = $api_client->CampaignAssetService()->mutate({
customerId => $customer_id,
operations => [$campaign_asset_operation]});
printf
"Created campaign asset with resource name = '%s' for campaign ID %d.\n",
$campaign_assets_response->{results}[0]{resourceName}, $campaign_id;
}
# Creates the lead form asset.
sub create_lead_form_asset {
my ($api_client, $customer_id) = @_;
# Create the lead form asset.
my $lead_form_asset = Google::Ads::GoogleAds::V19::Resources::Asset->new({
name => "Interplanetary Cruise Lead Form #" . uniqid(),
leadFormAsset => Google::Ads::GoogleAds::V19::Common::LeadFormAsset->new({
# Specify the details of lead form that the users will see.
callToActionType => BOOK_NOW,
callToActionDescription => "Latest trip to Jupiter!",
# Define the form details.
businessName => "Interplanetary Cruise",
headline => "Trip to Jupiter",
description => "Our latest trip to Jupiter is now open for booking.",
privacyPolicyUrl => "http://example.com/privacy",
# Define the fields to be displayed to the user.
fields => [
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => FULL_NAME
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => EMAIL
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PHONE_NUMBER
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PREFERRED_CONTACT_TIME,
singleChoiceAnswers =>
Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers
->new({
answers => ["Before 9 AM", "Any time", "After 5 PM"]})}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => TRAVEL_BUDGET
})
],
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.pl.
# backgroundImageAsset => "INSERT_IMAGE_ASSET_HERE",
# Optional: Define the response page after the user signs up on the form.
postSubmitHeadline => "Thanks for signing up!",
postSubmitDescription => "We will reach out to you shortly. " .
"Visit our website to see past trip details.",
postSubmitCallToActionType => VISIT_SITE,
# Optional: Display a custom disclosure that displays along with the
# Google disclaimer on the form.
customDisclosure => "Trip may get cancelled due to meteor shower.",
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for
# more details on how to define a webhook.
deliveryMethods => [
Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod->new({
webhook =>
Google::Ads::GoogleAds::V19::Common::WebhookDelivery->new({
advertiserWebhookUrl => "http://example.com/webhook",
googleSecret => "interplanetary google secret",
payloadSchemaVersion => 3
})})]}
),
finalUrls => ["http://example.com/jupiter"]});
# Create the operation.
my $asset_operation =
Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation->new({
create => $lead_form_asset
});
my $assets_response = $api_client->AssetService()->mutate({
customerId => $customer_id,
operations => [$asset_operation]});
my $lead_form_asset_resource_name =
$assets_response->{results}[0]{resourceName};
# Display the result.
printf "Asset with resource name = '%s' was created.\n",
$lead_form_asset_resource_name;
return $lead_form_asset_resource_name;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_id);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
if not check_params($customer_id, $campaign_id);
# Call the example.
add_lead_form_asset($api_client, $customer_id =~ s/-//gr, $campaign_id);
=pod
=head1 NAME
add_lead_form_asset
=head1 DESCRIPTION
This code example creates a lead form and a lead form asset for a campaign.
Run add_campaigns.pl to create a campaign.
=head1 SYNOPSIS
add_lead_form_asset.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-campaign_id ID of the campaign to which lead form assets are added.
=cut
،
جاوا
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.assets;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v19.common.LeadFormAsset;
import com.google.ads.googleads.v19.common.LeadFormDeliveryMethod;
import com.google.ads.googleads.v19.common.LeadFormField;
import com.google.ads.googleads.v19.common.LeadFormSingleChoiceAnswers;
import com.google.ads.googleads.v19.common.WebhookDelivery;
import com.google.ads.googleads.v19.enums.AssetFieldTypeEnum.AssetFieldType;
import com.google.ads.googleads.v19.enums.LeadFormCallToActionTypeEnum.LeadFormCallToActionType;
import com.google.ads.googleads.v19.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType;
import com.google.ads.googleads.v19.enums.LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType;
import com.google.ads.googleads.v19.errors.GoogleAdsError;
import com.google.ads.googleads.v19.errors.GoogleAdsException;
import com.google.ads.googleads.v19.resources.Asset;
import com.google.ads.googleads.v19.resources.CampaignAsset;
import com.google.ads.googleads.v19.services.AssetOperation;
import com.google.ads.googleads.v19.services.AssetServiceClient;
import com.google.ads.googleads.v19.services.CampaignAssetOperation;
import com.google.ads.googleads.v19.services.CampaignAssetServiceClient;
import com.google.ads.googleads.v19.services.MutateAssetsResponse;
import com.google.ads.googleads.v19.services.MutateCampaignAssetsResponse;
import com.google.ads.googleads.v19.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.java to create a
* campaign.
*/
public class AddLeadFormAsset {
private static class AddLeadFormAssetParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private long campaignId;
}
public static void main(String[] args) {
AddLeadFormAssetParams params = new AddLeadFormAssetParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddLeadFormAsset().runExample(googleAdsClient, params.customerId, params.campaignId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// Creates a lead form asset.
String leadFormAssetResourceName = createLeadFormAsset(googleAdsClient, customerId);
// Creates a lead form asset for the campaign.
createLeadFormExtension(googleAdsClient, customerId, campaignId, leadFormAssetResourceName);
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @return the resource name of the newly created lead form asset.
*/
private static String createLeadFormAsset(GoogleAdsClient googleAdsClient, long customerId) {
// Creates the lead form asset.
Asset leadFormAsset =
Asset.newBuilder()
.setName("Interplanetary Cruise #" + getPrintableDateTime() + " Lead Form")
.setLeadFormAsset(
LeadFormAsset.newBuilder()
// Specify the details of the asset that the users will see.
.setCallToActionType(LeadFormCallToActionType.BOOK_NOW)
.setCallToActionDescription("Latest trip to Jupiter!")
// Define the form details.
.setBusinessName("Interplanetary Cruise")
.setHeadline("Trip to Jupiter")
.setDescription("Our latest trip to Jupiter is now open for booking.")
.setPrivacyPolicyUrl("http://example.com/privacy")
// Define the fields to be displayed to the user.
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.FULL_NAME)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.EMAIL)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PHONE_NUMBER)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PREFERRED_CONTACT_TIME)
.setSingleChoiceAnswers(
LeadFormSingleChoiceAnswers.newBuilder()
.addAnswers("Before 9 AM")
.addAnswers("Any time")
.addAnswers("After 5 PM")
.build())
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.TRAVEL_BUDGET)
.build())
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.java.
// .setBackgroundImageAsset("INSERT_IMAGE_ASSET_HERE")
// Optional: Define the response page after the user signs up on the form.
.setPostSubmitHeadline("Thanks for signing up!")
.setPostSubmitDescription(
"We will reach out to you shortly. Visit our website "
+ "to see past trip details.")
.setPostSubmitCallToActionType(LeadFormPostSubmitCallToActionType.VISIT_SITE)
// Optional: Display a custom disclosure that displays along with Google
// disclaimer on the form.
.setCustomDisclosure("Trip may get cancelled due to meteor shower.")
// Optional: Define a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
.addDeliveryMethods(
LeadFormDeliveryMethod.newBuilder()
.setWebhook(
WebhookDelivery.newBuilder()
.setAdvertiserWebhookUrl("http://example.com/webhook")
.setGoogleSecret("interplanetary google secret")
.setPayloadSchemaVersion(3L)
.build())
.build())
.build())
.addFinalUrls("http://example.com/jupiter")
.build();
// Creates an operation to add the asset.
AssetOperation operation = AssetOperation.newBuilder().setCreate(leadFormAsset).build();
// Issues a mutate request to add the asset and prints its information.
try (AssetServiceClient client =
googleAdsClient.getLatestVersion().createAssetServiceClient()) {
MutateAssetsResponse response =
client.mutateAssets(String.valueOf(customerId), ImmutableList.of(operation));
String resourceName = response.getResultsList().get(0).getResourceName();
System.out.printf("Created asset with resource name '%s'.%n", resourceName);
return resourceName;
}
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
* @param leadFormAssetResourceName the resource name of the lead form asset to be added.
*/
private static void createLeadFormExtension(
GoogleAdsClient googleAdsClient,
long customerId,
long campaignId,
String leadFormAssetResourceName) {
// Creates the campaign asset for the lead form.
CampaignAsset campaignAsset =
CampaignAsset.newBuilder()
.setAsset(leadFormAssetResourceName)
.setFieldType(AssetFieldType.LEAD_FORM)
.setCampaign(ResourceNames.campaign(customerId, campaignId))
.build();
// Creates an operation to add the campaign asset.
CampaignAssetOperation operation =
CampaignAssetOperation.newBuilder().setCreate(campaignAsset).build();
// Issues a mutate request to add the campaign asset and prints its information.
try (CampaignAssetServiceClient client =
googleAdsClient.getLatestVersion().createCampaignAssetServiceClient()) {
MutateCampaignAssetsResponse response =
client.mutateCampaignAssets(String.valueOf(customerId), ImmutableList.of(operation));
System.out.printf(
"Created campaign asset with resource name '%s' for campaign ID %d.%n",
response.getResultsList().get(0).getResourceName(), campaignId);
}
}
}
سی شارپ
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V19.Common;
using Google.Ads.GoogleAds.V19.Errors;
using Google.Ads.GoogleAds.V19.Resources;
using Google.Ads.GoogleAds.V19.Services;
using System;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormCallToActionTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormFieldUserInputTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormPostSubmitCallToActionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V19
{
/// <summary>
/// This code example creates a lead form asset for a campaign. Run
/// AddCampaigns.cs to create a campaign.
/// </summary>
public class AddLeadFormAsset : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddLeadFormAsset"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which lead form assets are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which lead form assets are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
AddLeadFormAsset codeExample = new AddLeadFormAsset();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a lead form for a campaign. " +
"Run AddCampaigns.cs to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form assets are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Create a lead form asset.
string leadFormAssetResourceName = CreateLeadFormAsset(client, customerId);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the lead form asset.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The lead form asset resource name.</returns>
private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V19.AssetService);
// Creates the lead form asset.
Asset leadFormAsset = new Asset()
{
Name = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
LeadFormAsset = new LeadFormAsset()
{
// Specify the details of the asset that the users will see.
CallToActionType = LeadFormCallToActionType.BookNow,
CallToActionDescription = "Latest trip to Jupiter!",
// Define the form details.
BusinessName = "Interplanetary Cruise",
Headline = "Trip to Jupiter",
Description = "Our latest trip to Jupiter is now open for booking.",
PrivacyPolicyUrl = "http://example.com/privacy",
// Define the fields to be displayed to the user.
Fields = {
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.FullName,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.Email,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PhoneNumber,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PreferredContactTime,
SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
{
Answers = { "Before 9 AM", "Any time", "After 5 PM" }
}
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.TravelBudget,
},
},
// Optional: You can also specify a background image asset. To upload an asset,
// see Misc/UploadImageAsset.cs. BackgroundImageAsset =
// "INSERT_IMAGE_ASSET_HERE",
// Optional: Define the response page after the user signs up on the form.
PostSubmitHeadline = "Thanks for signing up!",
PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
"to see past trip details.",
PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,
// Optional: Display a custom disclosure that displays along with the Google
// disclaimer on the form.
CustomDisclosure = "Trip may get cancelled due to meteor shower.",
// Optional: Define a delivery method for the form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
DeliveryMethods =
{
new LeadFormDeliveryMethod()
{
Webhook = new WebhookDelivery()
{
AdvertiserWebhookUrl = "http://example.com/webhook",
GoogleSecret = "interplanetary google secret",
PayloadSchemaVersion = 3L
}
}
},
},
FinalUrls = { "http://example.com/jupiter" }
};
// Creates the operation.
AssetOperation operation = new AssetOperation()
{
Create = leadFormAsset,
};
// Makes the API call.
MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
new[] { operation });
string leadFormAssetResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
"was created.");
return leadFormAssetResourceName;
}
}
}
PHP
<?php
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Ads\GoogleAds\Examples\Extensions;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V19\ResourceNames;
use Google\Ads\GoogleAds\V19\Common\LeadFormAsset;
use Google\Ads\GoogleAds\V19\Common\LeadFormDeliveryMethod;
use Google\Ads\GoogleAds\V19\Common\LeadFormField;
use Google\Ads\GoogleAds\V19\Common\LeadFormSingleChoiceAnswers;
use Google\Ads\GoogleAds\V19\Common\WebhookDelivery;
use Google\Ads\GoogleAds\V19\Enums\AssetFieldTypeEnum\AssetFieldType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormCallToActionTypeEnum\LeadFormCallToActionType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormFieldUserInputTypeEnum\LeadFormFieldUserInputType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormPostSubmitCallToActionTypeEnum\LeadFormPostSubmitCallToActionType;
use Google\Ads\GoogleAds\V19\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V19\Resources\Asset;
use Google\Ads\GoogleAds\V19\Resources\CampaignAsset;
use Google\Ads\GoogleAds\V19\Services\AssetOperation;
use Google\Ads\GoogleAds\V19\Services\CampaignAssetOperation;
use Google\Ads\GoogleAds\V19\Services\MutateAssetsRequest;
use Google\Ads\GoogleAds\V19\Services\MutateCampaignAssetsRequest;
use Google\ApiCore\ApiException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.php to create a
* campaign.
*/
class AddLeadFormAsset
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
public static function main()
{
// 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,
ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// Construct a Google Ads client configured from a properties file and the
// OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
try {
self::runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
$options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
);
} catch (GoogleAdsException $googleAdsException) {
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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId
) {
// Creates a lead form asset.
$leadFormAssetResourceName = self::createLeadFormAsset($googleAdsClient, $customerId);
// Creates a lead form asset for the campaign.
self::createLeadFormCampaignAsset(
$googleAdsClient,
$customerId,
$campaignId,
$leadFormAssetResourceName
);
}
/**
* Creates the lead form asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @return string the resource name of the newly created lead form asset
*/
private static function createLeadFormAsset(
GoogleAdsClient $googleAdsClient,
int $customerId
): string {
// Creates the lead form asset.
$leadFormAsset = new Asset([
'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime() . ' Lead Form',
'lead_form_asset' => new LeadFormAsset([
// Specifies the details of the asset that the users will see.
'call_to_action_type' => LeadFormCallToActionType::BOOK_NOW,
'call_to_action_description' => 'Latest trip to Jupiter!',
// Defines the form details.
'business_name' => 'Interplanetary Cruise',
'headline' => 'Trip to Jupiter',
'description' => 'Our latest trip to Jupiter is now open for booking.',
'privacy_policy_url' => 'http://example.com/privacy',
// Defines the fields to be displayed to the user.
'fields' => [
new LeadFormField(['input_type' => LeadFormFieldUserInputType::FULL_NAME]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::EMAIL]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::PHONE_NUMBER]),
new LeadFormField([
'input_type' => LeadFormFieldUserInputType::PREFERRED_CONTACT_TIME,
'single_choice_answers' => new LeadFormSingleChoiceAnswers([
'answers' => ['Before 9 AM', 'Any time', 'After 5 PM']
])
]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::TRAVEL_BUDGET])
],
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.php.
// 'background_image_asset' => 'INSERT_IMAGE_ASSET_RESOURCE_NAME_HERE',
// Optional: Defines the response page after the user signs up on the form.
'post_submit_headline' => 'Thanks for signing up!',
'post_submit_description' => 'We will reach out to you shortly. '
. 'Visit our website to see past trip details.',
'post_submit_call_to_action_type' => LeadFormPostSubmitCallToActionType::VISIT_SITE,
// Optional: Displays a custom disclosure that displays along with Google
// disclaimer on the form.
'custom_disclosure' => 'Trip may get cancelled due to meteor shower.',
// Optional: Defines a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
'delivery_methods' => [new LeadFormDeliveryMethod([
'webhook' => new WebhookDelivery([
'advertiser_webhook_url' => 'http://example.com/webhook',
'google_secret' => 'interplanetary google secret',
'payload_schema_version' => 3
])
])]
]),
'final_urls' => ['http://example.com/jupiter']
]);
// Creates an operation to add the asset.
$assetOperation = new AssetOperation();
$assetOperation->setCreate($leadFormAsset);
// Issues a mutate request to add the asset and prints its information.
$assetServiceClient = $googleAdsClient->getAssetServiceClient();
$response = $assetServiceClient->mutateAssets(
MutateAssetsRequest::build($customerId, [$assetOperation])
);
$assetResourceName = $response->getResults()[0]->getResourceName();
printf("Created an asset with resource name: '%s'.%s", $assetResourceName, PHP_EOL);
return $assetResourceName;
}
/**
* Creates the lead form campaign asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $campaignId the campaign ID to add the lead form asset
* @param string $leadFormAssetResourceName the resource name of the lead form asset to be added
*/
private static function createLeadFormCampaignAsset(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
string $leadFormAssetResourceName
) {
// Creates the campaign asset for the lead form.
$campaignAsset = new CampaignAsset([
'asset' => $leadFormAssetResourceName,
'field_type' => AssetFieldType::LEAD_FORM,
'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
]);
// Creates an operation to add the campaign asset.
$campaignAssetOperation = new CampaignAssetOperation();
$campaignAssetOperation->setCreate($campaignAsset);
// Issues a mutate request to add the campaign asset and prints its information.
$campaignAssetServiceClient = $googleAdsClient->getCampaignAssetServiceClient();
$response = $campaignAssetServiceClient->mutateCampaignAssets(
MutateCampaignAssetsRequest::build($customerId, [$campaignAssetOperation])
);
printf(
"Created a campaign asset with resource name '%s' for campaign ID %d.%s",
$response->getResults()[0]->getResourceName(),
$campaignId,
PHP_EOL
);
}
}
AddLeadFormAsset::main();
پایتون
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a lead form and a lead form extension for a campaign.
Run add_campaigns.py to create a campaign.
"""
import argparse
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, campaign_id):
"""Creates a lead form and lead form extension for the given campaign.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
lead_form_asset_resource_name = create_lead_form_asset(client, customer_id)
create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
)
def create_lead_form_asset(client, customer_id):
"""Creates a lead form asset using the given customer ID.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
Returns:
A str of the resource name for the newly created lead form asset.
"""
asset_service = client.get_service("AssetService")
asset_operation = client.get_type("AssetOperation")
asset = asset_operation.create
asset.name = f"Interplanetary Cruise #{uuid4()} Lead Form"
asset.final_urls.append("http://example.com/jupiter")
# Creates a new LeadFormAsset instance.
lead_form_asset = asset.lead_form_asset
# Specify the details of the extension that the users will see.
lead_form_asset.call_to_action_type = (
client.enums.LeadFormCallToActionTypeEnum.BOOK_NOW
)
lead_form_asset.call_to_action_description = "Latest trip to Jupiter!"
# Define the form details.
lead_form_asset.business_name = "Interplanetary Cruise"
lead_form_asset.headline = "Trip to Jupiter"
lead_form_asset.description = (
"Our latest trip to Jupiter is now open for booking."
)
lead_form_asset.privacy_policy_url = "http://example.com/privacy"
# Define the fields to be displayed to the user.
input_type_enum = client.enums.LeadFormFieldUserInputTypeEnum
lead_form_field_1 = client.get_type("LeadFormField")
lead_form_field_1.input_type = input_type_enum.FULL_NAME
lead_form_asset.fields.append(lead_form_field_1)
lead_form_field_2 = client.get_type("LeadFormField")
lead_form_field_2.input_type = input_type_enum.EMAIL
lead_form_asset.fields.append(lead_form_field_2)
lead_form_field_3 = client.get_type("LeadFormField")
lead_form_field_3.input_type = input_type_enum.PHONE_NUMBER
lead_form_asset.fields.append(lead_form_field_3)
lead_form_field_4 = client.get_type("LeadFormField")
lead_form_field_4.input_type = input_type_enum.PREFERRED_CONTACT_TIME
lead_form_field_4.single_choice_answers.answers.extend(
["Before 9 AM", "Anytime", "After 5 PM"]
)
lead_form_asset.fields.append(lead_form_field_4)
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image.py.
# lead_form_asset.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lead_form_asset.post_submit_headline = "Thanks for signing up!"
lead_form_asset.post_submit_description = (
"We will reach out to you shortly. Visit our website to see past trip "
"details."
)
lead_form_asset.post_submit_call_to_action_type = (
client.enums.LeadFormPostSubmitCallToActionTypeEnum.VISIT_SITE
)
# Optional: Display a custom disclosure that displays along with the Google
# disclaimer on the form.
lead_form_asset.custom_disclosure = (
"Trip may get cancelled due to meteor shower"
)
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
delivery_method = client.get_type("LeadFormDeliveryMethod")
delivery_method.webhook.advertiser_webhook_url = (
"http://example.com/webhook"
)
delivery_method.webhook.google_secret = "interplanetary google secret"
delivery_method.webhook.payload_schema_version = 3
lead_form_asset.delivery_methods.append(delivery_method)
asset_service = client.get_service("AssetService")
response = asset_service.mutate_assets(
customer_id=customer_id, operations=[asset_operation]
)
resource_name = response.results[0].resource_name
print(f"Asset with resource name {resource_name} was created.")
return resource_name
def create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
):
"""Creates the lead form campaign asset.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
campaign_service = client.get_service("CampaignService")
campaign_asset_service = client.get_service("CampaignAssetService")
campaign_asset_operation = client.get_type("CampaignAssetOperation")
campaign_asset = campaign_asset_operation.create
campaign_asset.asset = lead_form_asset_resource_name
campaign_asset.field_type = client.enums.AssetFieldTypeEnum.LEAD_FORM
campaign_asset.campaign = campaign_service.campaign_path(
customer_id, campaign_id
)
response = campaign_asset_service.mutate_campaign_assets(
customer_id=customer_id, operations=[campaign_asset_operation]
)
for result in response.results:
print(
"Created campaign asset with resource name "
f'"{result.resource_name}" for campaign with ID {campaign_id}'
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This code example creates a lead form and a lead form "
"asset for a campaign. Run add_campaigns.py to create a "
"campaign."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-i",
"--campaign_id",
type=str,
required=True,
help="The ID of a Campaign belonging to the given customer.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v19")
try:
main(googleads_client, args.customer_id, args.campaign_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
روبی
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Creates a lead form and a lead form asset for a campaign.
#
# Run add_campaigns.rb to create a campaign.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_lead_form_asset(customer_id, campaign_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
lead_form_asset = create_lead_form_asset(
client,
customer_id,
)
create_lead_form_campaign_asset(
client,
customer_id,
campaign_id,
lead_form_asset,
)
end
def create_lead_form_asset(client, customer_id)
operation = client.operation.create_resource.asset do |a|
a.name = "Interplanetary Cruise #{(Time.new.to_f * 1000).to_i} Lead Form"
a.final_urls << "http://example.com/jupiter"
a.lead_form_asset = client.resource.lead_form_asset do |lfa|
lfa.call_to_action_type = :BOOK_NOW
lfa.call_to_action_description = "Latest trip to Jupiter!"
lfa.business_name = "Interplanetary Cruise"
lfa.headline = "Trip to Jupiter"
lfa.description = "Our latest trip to Jupiter is now open for booking."
lfa.privacy_policy_url = "http://example.com/privacy"
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :FULL_NAME
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :EMAIL
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PHONE_NUMBER
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PREFERRED_CONTACT_TIME
lff.single_choice_answers = client.resource.lead_form_single_choice_answers do |sca|
sca.answers += ["Before 9 AM", "Anytime", "After 5 PM"]
end
end
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.rb.
# lfa.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lfa.post_submit_headline = "Thanks for signing up!"
lfa.post_submit_description = "We will reach out to you shortly. " \
"Visit our website to see past trip details."
lfa.post_submit_call_to_action_type = :VISIT_SITE
# Optional
# lfa.custom_disclosure = "Trip may get cancelled due to meteor shower."
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
lfa.delivery_methods << client.resource.lead_form_delivery_method do |lfdm|
lfdm.webhook = client.resource.webhook_delivery do |wd|
wd.advertiser_webhook_url = "http://example.com/webhook"
wd.google_secret = "interplanetary google secret"
wd.payload_schema_version = 3
end
end
end
end
response = client.service.asset.mutate_assets(
customer_id: customer_id,
operations: [operation],
)
asset_name = response.results.first.resource_name
puts "Asset with resource name #{asset_name} was created."
asset_name
end
def create_lead_form_campaign_asset(client, customer_id, campaign_id, lead_form_asset)
operation = client.operation.create_resource.campaign_asset do |ca|
ca.asset = lead_form_asset
ca.field_type = :LEAD_FORM
ca.campaign = client.path.campaign(customer_id, campaign_id)
end
response = client.service.campaign_asset.mutate_campaign_assets(
customer_id: customer_id,
operations: [operation],
)
puts "Created campaign asset #{response.results.first.resource_name} for " \
"campaign #{campaign_id}."
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
options[:campaign_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_lead_form_asset(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:campaign_id),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
پرل
#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example creates a lead form and a lead form asset for a campaign.
# Run add_campaigns.pl to create a campaign.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V19::Resources::CampaignAsset;
use Google::Ads::GoogleAds::V19::Resources::Asset;
use Google::Ads::GoogleAds::V19::Common::LeadFormAsset;
use Google::Ads::GoogleAds::V19::Common::LeadFormField;
use Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers;
use Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod;
use Google::Ads::GoogleAds::V19::Common::WebhookDelivery;
use Google::Ads::GoogleAds::V19::Enums::AssetFieldTypeEnum qw(LEAD_FORM);
use Google::Ads::GoogleAds::V19::Enums::LeadFormCallToActionTypeEnum
qw(BOOK_NOW);
use Google::Ads::GoogleAds::V19::Enums::LeadFormFieldUserInputTypeEnum
qw(FULL_NAME EMAIL PHONE_NUMBER PREFERRED_CONTACT_TIME TRAVEL_BUDGET);
use Google::Ads::GoogleAds::V19::Enums::LeadFormPostSubmitCallToActionTypeEnum
qw(VISIT_SITE);
use
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation;
use Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V19::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
sub add_lead_form_asset {
my ($api_client, $customer_id, $campaign_id) = @_;
# Create a lead form asset.
my $lead_form_asset_resource_name =
create_lead_form_asset($api_client, $customer_id);
# Create a lead form asset for the campaign.
create_lead_form_campaign_asset($api_client, $customer_id, $campaign_id,
$lead_form_asset_resource_name);
return 1;
}
# Creates the lead form campaign asset.
sub create_lead_form_campaign_asset {
my ($api_client, $customer_id, $campaign_id, $lead_form_asset_resource_name)
= @_;
# Create the campaign asset for the lead form.
my $campaign_asset =
Google::Ads::GoogleAds::V19::Resources::CampaignAsset->new({
asset => $lead_form_asset_resource_name,
fieldType => LEAD_FORM,
campaign => Google::Ads::GoogleAds::V19::Utils::ResourceNames::campaign(
$customer_id, $campaign_id
)});
my $campaign_asset_operation =
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation
->new({
create => $campaign_asset
});
my $campaign_assets_response = $api_client->CampaignAssetService()->mutate({
customerId => $customer_id,
operations => [$campaign_asset_operation]});
printf
"Created campaign asset with resource name = '%s' for campaign ID %d.\n",
$campaign_assets_response->{results}[0]{resourceName}, $campaign_id;
}
# Creates the lead form asset.
sub create_lead_form_asset {
my ($api_client, $customer_id) = @_;
# Create the lead form asset.
my $lead_form_asset = Google::Ads::GoogleAds::V19::Resources::Asset->new({
name => "Interplanetary Cruise Lead Form #" . uniqid(),
leadFormAsset => Google::Ads::GoogleAds::V19::Common::LeadFormAsset->new({
# Specify the details of lead form that the users will see.
callToActionType => BOOK_NOW,
callToActionDescription => "Latest trip to Jupiter!",
# Define the form details.
businessName => "Interplanetary Cruise",
headline => "Trip to Jupiter",
description => "Our latest trip to Jupiter is now open for booking.",
privacyPolicyUrl => "http://example.com/privacy",
# Define the fields to be displayed to the user.
fields => [
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => FULL_NAME
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => EMAIL
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PHONE_NUMBER
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PREFERRED_CONTACT_TIME,
singleChoiceAnswers =>
Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers
->new({
answers => ["Before 9 AM", "Any time", "After 5 PM"]})}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => TRAVEL_BUDGET
})
],
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.pl.
# backgroundImageAsset => "INSERT_IMAGE_ASSET_HERE",
# Optional: Define the response page after the user signs up on the form.
postSubmitHeadline => "Thanks for signing up!",
postSubmitDescription => "We will reach out to you shortly. " .
"Visit our website to see past trip details.",
postSubmitCallToActionType => VISIT_SITE,
# Optional: Display a custom disclosure that displays along with the
# Google disclaimer on the form.
customDisclosure => "Trip may get cancelled due to meteor shower.",
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for
# more details on how to define a webhook.
deliveryMethods => [
Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod->new({
webhook =>
Google::Ads::GoogleAds::V19::Common::WebhookDelivery->new({
advertiserWebhookUrl => "http://example.com/webhook",
googleSecret => "interplanetary google secret",
payloadSchemaVersion => 3
})})]}
),
finalUrls => ["http://example.com/jupiter"]});
# Create the operation.
my $asset_operation =
Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation->new({
create => $lead_form_asset
});
my $assets_response = $api_client->AssetService()->mutate({
customerId => $customer_id,
operations => [$asset_operation]});
my $lead_form_asset_resource_name =
$assets_response->{results}[0]{resourceName};
# Display the result.
printf "Asset with resource name = '%s' was created.\n",
$lead_form_asset_resource_name;
return $lead_form_asset_resource_name;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_id);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
if not check_params($customer_id, $campaign_id);
# Call the example.
add_lead_form_asset($api_client, $customer_id =~ s/-//gr, $campaign_id);
=pod
=head1 NAME
add_lead_form_asset
=head1 DESCRIPTION
This code example creates a lead form and a lead form asset for a campaign.
Run add_campaigns.pl to create a campaign.
=head1 SYNOPSIS
add_lead_form_asset.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-campaign_id ID of the campaign to which lead form assets are added.
=cut
،
جاوا
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.assets;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v19.common.LeadFormAsset;
import com.google.ads.googleads.v19.common.LeadFormDeliveryMethod;
import com.google.ads.googleads.v19.common.LeadFormField;
import com.google.ads.googleads.v19.common.LeadFormSingleChoiceAnswers;
import com.google.ads.googleads.v19.common.WebhookDelivery;
import com.google.ads.googleads.v19.enums.AssetFieldTypeEnum.AssetFieldType;
import com.google.ads.googleads.v19.enums.LeadFormCallToActionTypeEnum.LeadFormCallToActionType;
import com.google.ads.googleads.v19.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType;
import com.google.ads.googleads.v19.enums.LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType;
import com.google.ads.googleads.v19.errors.GoogleAdsError;
import com.google.ads.googleads.v19.errors.GoogleAdsException;
import com.google.ads.googleads.v19.resources.Asset;
import com.google.ads.googleads.v19.resources.CampaignAsset;
import com.google.ads.googleads.v19.services.AssetOperation;
import com.google.ads.googleads.v19.services.AssetServiceClient;
import com.google.ads.googleads.v19.services.CampaignAssetOperation;
import com.google.ads.googleads.v19.services.CampaignAssetServiceClient;
import com.google.ads.googleads.v19.services.MutateAssetsResponse;
import com.google.ads.googleads.v19.services.MutateCampaignAssetsResponse;
import com.google.ads.googleads.v19.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.java to create a
* campaign.
*/
public class AddLeadFormAsset {
private static class AddLeadFormAssetParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private long campaignId;
}
public static void main(String[] args) {
AddLeadFormAssetParams params = new AddLeadFormAssetParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddLeadFormAsset().runExample(googleAdsClient, params.customerId, params.campaignId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// Creates a lead form asset.
String leadFormAssetResourceName = createLeadFormAsset(googleAdsClient, customerId);
// Creates a lead form asset for the campaign.
createLeadFormExtension(googleAdsClient, customerId, campaignId, leadFormAssetResourceName);
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @return the resource name of the newly created lead form asset.
*/
private static String createLeadFormAsset(GoogleAdsClient googleAdsClient, long customerId) {
// Creates the lead form asset.
Asset leadFormAsset =
Asset.newBuilder()
.setName("Interplanetary Cruise #" + getPrintableDateTime() + " Lead Form")
.setLeadFormAsset(
LeadFormAsset.newBuilder()
// Specify the details of the asset that the users will see.
.setCallToActionType(LeadFormCallToActionType.BOOK_NOW)
.setCallToActionDescription("Latest trip to Jupiter!")
// Define the form details.
.setBusinessName("Interplanetary Cruise")
.setHeadline("Trip to Jupiter")
.setDescription("Our latest trip to Jupiter is now open for booking.")
.setPrivacyPolicyUrl("http://example.com/privacy")
// Define the fields to be displayed to the user.
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.FULL_NAME)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.EMAIL)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PHONE_NUMBER)
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.PREFERRED_CONTACT_TIME)
.setSingleChoiceAnswers(
LeadFormSingleChoiceAnswers.newBuilder()
.addAnswers("Before 9 AM")
.addAnswers("Any time")
.addAnswers("After 5 PM")
.build())
.build())
.addFields(
LeadFormField.newBuilder()
.setInputType(LeadFormFieldUserInputType.TRAVEL_BUDGET)
.build())
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.java.
// .setBackgroundImageAsset("INSERT_IMAGE_ASSET_HERE")
// Optional: Define the response page after the user signs up on the form.
.setPostSubmitHeadline("Thanks for signing up!")
.setPostSubmitDescription(
"We will reach out to you shortly. Visit our website "
+ "to see past trip details.")
.setPostSubmitCallToActionType(LeadFormPostSubmitCallToActionType.VISIT_SITE)
// Optional: Display a custom disclosure that displays along with Google
// disclaimer on the form.
.setCustomDisclosure("Trip may get cancelled due to meteor shower.")
// Optional: Define a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
.addDeliveryMethods(
LeadFormDeliveryMethod.newBuilder()
.setWebhook(
WebhookDelivery.newBuilder()
.setAdvertiserWebhookUrl("http://example.com/webhook")
.setGoogleSecret("interplanetary google secret")
.setPayloadSchemaVersion(3L)
.build())
.build())
.build())
.addFinalUrls("http://example.com/jupiter")
.build();
// Creates an operation to add the asset.
AssetOperation operation = AssetOperation.newBuilder().setCreate(leadFormAsset).build();
// Issues a mutate request to add the asset and prints its information.
try (AssetServiceClient client =
googleAdsClient.getLatestVersion().createAssetServiceClient()) {
MutateAssetsResponse response =
client.mutateAssets(String.valueOf(customerId), ImmutableList.of(operation));
String resourceName = response.getResultsList().get(0).getResourceName();
System.out.printf("Created asset with resource name '%s'.%n", resourceName);
return resourceName;
}
}
/**
* Creates the lead form asset.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for which to add the lead form asset.
* @param campaignId the campaign ID for which to add the lead form asset.
* @param leadFormAssetResourceName the resource name of the lead form asset to be added.
*/
private static void createLeadFormExtension(
GoogleAdsClient googleAdsClient,
long customerId,
long campaignId,
String leadFormAssetResourceName) {
// Creates the campaign asset for the lead form.
CampaignAsset campaignAsset =
CampaignAsset.newBuilder()
.setAsset(leadFormAssetResourceName)
.setFieldType(AssetFieldType.LEAD_FORM)
.setCampaign(ResourceNames.campaign(customerId, campaignId))
.build();
// Creates an operation to add the campaign asset.
CampaignAssetOperation operation =
CampaignAssetOperation.newBuilder().setCreate(campaignAsset).build();
// Issues a mutate request to add the campaign asset and prints its information.
try (CampaignAssetServiceClient client =
googleAdsClient.getLatestVersion().createCampaignAssetServiceClient()) {
MutateCampaignAssetsResponse response =
client.mutateCampaignAssets(String.valueOf(customerId), ImmutableList.of(operation));
System.out.printf(
"Created campaign asset with resource name '%s' for campaign ID %d.%n",
response.getResultsList().get(0).getResourceName(), campaignId);
}
}
}
سی شارپ
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V19.Common;
using Google.Ads.GoogleAds.V19.Errors;
using Google.Ads.GoogleAds.V19.Resources;
using Google.Ads.GoogleAds.V19.Services;
using System;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormCallToActionTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormFieldUserInputTypeEnum.Types;
using static Google.Ads.GoogleAds.V19.Enums.LeadFormPostSubmitCallToActionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V19
{
/// <summary>
/// This code example creates a lead form asset for a campaign. Run
/// AddCampaigns.cs to create a campaign.
/// </summary>
public class AddLeadFormAsset : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddLeadFormAsset"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which lead form assets are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which lead form assets are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
AddLeadFormAsset codeExample = new AddLeadFormAsset();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a lead form for a campaign. " +
"Run AddCampaigns.cs to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">
/// ID of the campaign to which lead form assets are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Create a lead form asset.
string leadFormAssetResourceName = CreateLeadFormAsset(client, customerId);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the lead form asset.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The lead form asset resource name.</returns>
private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V19.AssetService);
// Creates the lead form asset.
Asset leadFormAsset = new Asset()
{
Name = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
LeadFormAsset = new LeadFormAsset()
{
// Specify the details of the asset that the users will see.
CallToActionType = LeadFormCallToActionType.BookNow,
CallToActionDescription = "Latest trip to Jupiter!",
// Define the form details.
BusinessName = "Interplanetary Cruise",
Headline = "Trip to Jupiter",
Description = "Our latest trip to Jupiter is now open for booking.",
PrivacyPolicyUrl = "http://example.com/privacy",
// Define the fields to be displayed to the user.
Fields = {
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.FullName,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.Email,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PhoneNumber,
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.PreferredContactTime,
SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
{
Answers = { "Before 9 AM", "Any time", "After 5 PM" }
}
},
new LeadFormField()
{
InputType = LeadFormFieldUserInputType.TravelBudget,
},
},
// Optional: You can also specify a background image asset. To upload an asset,
// see Misc/UploadImageAsset.cs. BackgroundImageAsset =
// "INSERT_IMAGE_ASSET_HERE",
// Optional: Define the response page after the user signs up on the form.
PostSubmitHeadline = "Thanks for signing up!",
PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
"to see past trip details.",
PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,
// Optional: Display a custom disclosure that displays along with the Google
// disclaimer on the form.
CustomDisclosure = "Trip may get cancelled due to meteor shower.",
// Optional: Define a delivery method for the form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
DeliveryMethods =
{
new LeadFormDeliveryMethod()
{
Webhook = new WebhookDelivery()
{
AdvertiserWebhookUrl = "http://example.com/webhook",
GoogleSecret = "interplanetary google secret",
PayloadSchemaVersion = 3L
}
}
},
},
FinalUrls = { "http://example.com/jupiter" }
};
// Creates the operation.
AssetOperation operation = new AssetOperation()
{
Create = leadFormAsset,
};
// Makes the API call.
MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
new[] { operation });
string leadFormAssetResourceName = response.Results[0].ResourceName;
// Displays the result.
Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
"was created.");
return leadFormAssetResourceName;
}
}
}
PHP
<?php
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Ads\GoogleAds\Examples\Extensions;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V19\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V19\ResourceNames;
use Google\Ads\GoogleAds\V19\Common\LeadFormAsset;
use Google\Ads\GoogleAds\V19\Common\LeadFormDeliveryMethod;
use Google\Ads\GoogleAds\V19\Common\LeadFormField;
use Google\Ads\GoogleAds\V19\Common\LeadFormSingleChoiceAnswers;
use Google\Ads\GoogleAds\V19\Common\WebhookDelivery;
use Google\Ads\GoogleAds\V19\Enums\AssetFieldTypeEnum\AssetFieldType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormCallToActionTypeEnum\LeadFormCallToActionType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormFieldUserInputTypeEnum\LeadFormFieldUserInputType;
use Google\Ads\GoogleAds\V19\Enums\LeadFormPostSubmitCallToActionTypeEnum\LeadFormPostSubmitCallToActionType;
use Google\Ads\GoogleAds\V19\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V19\Resources\Asset;
use Google\Ads\GoogleAds\V19\Resources\CampaignAsset;
use Google\Ads\GoogleAds\V19\Services\AssetOperation;
use Google\Ads\GoogleAds\V19\Services\CampaignAssetOperation;
use Google\Ads\GoogleAds\V19\Services\MutateAssetsRequest;
use Google\Ads\GoogleAds\V19\Services\MutateCampaignAssetsRequest;
use Google\ApiCore\ApiException;
/**
* Creates a lead form and a lead form asset for a campaign. Run AddCampaigns.php to create a
* campaign.
*/
class AddLeadFormAsset
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
public static function main()
{
// 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,
ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// Construct a Google Ads client configured from a properties file and the
// OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
try {
self::runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
$options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
);
} catch (GoogleAdsException $googleAdsException) {
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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId
) {
// Creates a lead form asset.
$leadFormAssetResourceName = self::createLeadFormAsset($googleAdsClient, $customerId);
// Creates a lead form asset for the campaign.
self::createLeadFormCampaignAsset(
$googleAdsClient,
$customerId,
$campaignId,
$leadFormAssetResourceName
);
}
/**
* Creates the lead form asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @return string the resource name of the newly created lead form asset
*/
private static function createLeadFormAsset(
GoogleAdsClient $googleAdsClient,
int $customerId
): string {
// Creates the lead form asset.
$leadFormAsset = new Asset([
'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime() . ' Lead Form',
'lead_form_asset' => new LeadFormAsset([
// Specifies the details of the asset that the users will see.
'call_to_action_type' => LeadFormCallToActionType::BOOK_NOW,
'call_to_action_description' => 'Latest trip to Jupiter!',
// Defines the form details.
'business_name' => 'Interplanetary Cruise',
'headline' => 'Trip to Jupiter',
'description' => 'Our latest trip to Jupiter is now open for booking.',
'privacy_policy_url' => 'http://example.com/privacy',
// Defines the fields to be displayed to the user.
'fields' => [
new LeadFormField(['input_type' => LeadFormFieldUserInputType::FULL_NAME]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::EMAIL]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::PHONE_NUMBER]),
new LeadFormField([
'input_type' => LeadFormFieldUserInputType::PREFERRED_CONTACT_TIME,
'single_choice_answers' => new LeadFormSingleChoiceAnswers([
'answers' => ['Before 9 AM', 'Any time', 'After 5 PM']
])
]),
new LeadFormField(['input_type' => LeadFormFieldUserInputType::TRAVEL_BUDGET])
],
// Optional: You can also specify a background image asset.
// To upload an asset, see Misc/UploadImageAsset.php.
// 'background_image_asset' => 'INSERT_IMAGE_ASSET_RESOURCE_NAME_HERE',
// Optional: Defines the response page after the user signs up on the form.
'post_submit_headline' => 'Thanks for signing up!',
'post_submit_description' => 'We will reach out to you shortly. '
. 'Visit our website to see past trip details.',
'post_submit_call_to_action_type' => LeadFormPostSubmitCallToActionType::VISIT_SITE,
// Optional: Displays a custom disclosure that displays along with Google
// disclaimer on the form.
'custom_disclosure' => 'Trip may get cancelled due to meteor shower.',
// Optional: Defines a delivery method for form response. See
// https://developers.google.com/google-ads/webhook/docs/overview for more
// details on how to define a webhook.
'delivery_methods' => [new LeadFormDeliveryMethod([
'webhook' => new WebhookDelivery([
'advertiser_webhook_url' => 'http://example.com/webhook',
'google_secret' => 'interplanetary google secret',
'payload_schema_version' => 3
])
])]
]),
'final_urls' => ['http://example.com/jupiter']
]);
// Creates an operation to add the asset.
$assetOperation = new AssetOperation();
$assetOperation->setCreate($leadFormAsset);
// Issues a mutate request to add the asset and prints its information.
$assetServiceClient = $googleAdsClient->getAssetServiceClient();
$response = $assetServiceClient->mutateAssets(
MutateAssetsRequest::build($customerId, [$assetOperation])
);
$assetResourceName = $response->getResults()[0]->getResourceName();
printf("Created an asset with resource name: '%s'.%s", $assetResourceName, PHP_EOL);
return $assetResourceName;
}
/**
* Creates the lead form campaign asset.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $campaignId the campaign ID to add the lead form asset
* @param string $leadFormAssetResourceName the resource name of the lead form asset to be added
*/
private static function createLeadFormCampaignAsset(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
string $leadFormAssetResourceName
) {
// Creates the campaign asset for the lead form.
$campaignAsset = new CampaignAsset([
'asset' => $leadFormAssetResourceName,
'field_type' => AssetFieldType::LEAD_FORM,
'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
]);
// Creates an operation to add the campaign asset.
$campaignAssetOperation = new CampaignAssetOperation();
$campaignAssetOperation->setCreate($campaignAsset);
// Issues a mutate request to add the campaign asset and prints its information.
$campaignAssetServiceClient = $googleAdsClient->getCampaignAssetServiceClient();
$response = $campaignAssetServiceClient->mutateCampaignAssets(
MutateCampaignAssetsRequest::build($customerId, [$campaignAssetOperation])
);
printf(
"Created a campaign asset with resource name '%s' for campaign ID %d.%s",
$response->getResults()[0]->getResourceName(),
$campaignId,
PHP_EOL
);
}
}
AddLeadFormAsset::main();
پایتون
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a lead form and a lead form extension for a campaign.
Run add_campaigns.py to create a campaign.
"""
import argparse
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, campaign_id):
"""Creates a lead form and lead form extension for the given campaign.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
lead_form_asset_resource_name = create_lead_form_asset(client, customer_id)
create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
)
def create_lead_form_asset(client, customer_id):
"""Creates a lead form asset using the given customer ID.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
Returns:
A str of the resource name for the newly created lead form asset.
"""
asset_service = client.get_service("AssetService")
asset_operation = client.get_type("AssetOperation")
asset = asset_operation.create
asset.name = f"Interplanetary Cruise #{uuid4()} Lead Form"
asset.final_urls.append("http://example.com/jupiter")
# Creates a new LeadFormAsset instance.
lead_form_asset = asset.lead_form_asset
# Specify the details of the extension that the users will see.
lead_form_asset.call_to_action_type = (
client.enums.LeadFormCallToActionTypeEnum.BOOK_NOW
)
lead_form_asset.call_to_action_description = "Latest trip to Jupiter!"
# Define the form details.
lead_form_asset.business_name = "Interplanetary Cruise"
lead_form_asset.headline = "Trip to Jupiter"
lead_form_asset.description = (
"Our latest trip to Jupiter is now open for booking."
)
lead_form_asset.privacy_policy_url = "http://example.com/privacy"
# Define the fields to be displayed to the user.
input_type_enum = client.enums.LeadFormFieldUserInputTypeEnum
lead_form_field_1 = client.get_type("LeadFormField")
lead_form_field_1.input_type = input_type_enum.FULL_NAME
lead_form_asset.fields.append(lead_form_field_1)
lead_form_field_2 = client.get_type("LeadFormField")
lead_form_field_2.input_type = input_type_enum.EMAIL
lead_form_asset.fields.append(lead_form_field_2)
lead_form_field_3 = client.get_type("LeadFormField")
lead_form_field_3.input_type = input_type_enum.PHONE_NUMBER
lead_form_asset.fields.append(lead_form_field_3)
lead_form_field_4 = client.get_type("LeadFormField")
lead_form_field_4.input_type = input_type_enum.PREFERRED_CONTACT_TIME
lead_form_field_4.single_choice_answers.answers.extend(
["Before 9 AM", "Anytime", "After 5 PM"]
)
lead_form_asset.fields.append(lead_form_field_4)
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image.py.
# lead_form_asset.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lead_form_asset.post_submit_headline = "Thanks for signing up!"
lead_form_asset.post_submit_description = (
"We will reach out to you shortly. Visit our website to see past trip "
"details."
)
lead_form_asset.post_submit_call_to_action_type = (
client.enums.LeadFormPostSubmitCallToActionTypeEnum.VISIT_SITE
)
# Optional: Display a custom disclosure that displays along with the Google
# disclaimer on the form.
lead_form_asset.custom_disclosure = (
"Trip may get cancelled due to meteor shower"
)
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
delivery_method = client.get_type("LeadFormDeliveryMethod")
delivery_method.webhook.advertiser_webhook_url = (
"http://example.com/webhook"
)
delivery_method.webhook.google_secret = "interplanetary google secret"
delivery_method.webhook.payload_schema_version = 3
lead_form_asset.delivery_methods.append(delivery_method)
asset_service = client.get_service("AssetService")
response = asset_service.mutate_assets(
customer_id=customer_id, operations=[asset_operation]
)
resource_name = response.results[0].resource_name
print(f"Asset with resource name {resource_name} was created.")
return resource_name
def create_lead_form_campaign_asset(
client, customer_id, campaign_id, lead_form_asset_resource_name
):
"""Creates the lead form campaign asset.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The Google Ads customer ID.
campaign_id: The ID for a Campaign belonging to the given customer.
"""
campaign_service = client.get_service("CampaignService")
campaign_asset_service = client.get_service("CampaignAssetService")
campaign_asset_operation = client.get_type("CampaignAssetOperation")
campaign_asset = campaign_asset_operation.create
campaign_asset.asset = lead_form_asset_resource_name
campaign_asset.field_type = client.enums.AssetFieldTypeEnum.LEAD_FORM
campaign_asset.campaign = campaign_service.campaign_path(
customer_id, campaign_id
)
response = campaign_asset_service.mutate_campaign_assets(
customer_id=customer_id, operations=[campaign_asset_operation]
)
for result in response.results:
print(
"Created campaign asset with resource name "
f'"{result.resource_name}" for campaign with ID {campaign_id}'
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This code example creates a lead form and a lead form "
"asset for a campaign. Run add_campaigns.py to create a "
"campaign."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-i",
"--campaign_id",
type=str,
required=True,
help="The ID of a Campaign belonging to the given customer.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v19")
try:
main(googleads_client, args.customer_id, args.campaign_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
روبی
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Creates a lead form and a lead form asset for a campaign.
#
# Run add_campaigns.rb to create a campaign.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_lead_form_asset(customer_id, campaign_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
lead_form_asset = create_lead_form_asset(
client,
customer_id,
)
create_lead_form_campaign_asset(
client,
customer_id,
campaign_id,
lead_form_asset,
)
end
def create_lead_form_asset(client, customer_id)
operation = client.operation.create_resource.asset do |a|
a.name = "Interplanetary Cruise #{(Time.new.to_f * 1000).to_i} Lead Form"
a.final_urls << "http://example.com/jupiter"
a.lead_form_asset = client.resource.lead_form_asset do |lfa|
lfa.call_to_action_type = :BOOK_NOW
lfa.call_to_action_description = "Latest trip to Jupiter!"
lfa.business_name = "Interplanetary Cruise"
lfa.headline = "Trip to Jupiter"
lfa.description = "Our latest trip to Jupiter is now open for booking."
lfa.privacy_policy_url = "http://example.com/privacy"
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :FULL_NAME
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :EMAIL
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PHONE_NUMBER
end
lfa.fields << client.resource.lead_form_field do |lff|
lff.input_type = :PREFERRED_CONTACT_TIME
lff.single_choice_answers = client.resource.lead_form_single_choice_answers do |sca|
sca.answers += ["Before 9 AM", "Anytime", "After 5 PM"]
end
end
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.rb.
# lfa.background_image_asset = "INSERT_IMAGE_ASSET_HERE"
# Optional: Define the response page after the user signs up on the form.
lfa.post_submit_headline = "Thanks for signing up!"
lfa.post_submit_description = "We will reach out to you shortly. " \
"Visit our website to see past trip details."
lfa.post_submit_call_to_action_type = :VISIT_SITE
# Optional
# lfa.custom_disclosure = "Trip may get cancelled due to meteor shower."
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for more
# details on how to define a webhook.
lfa.delivery_methods << client.resource.lead_form_delivery_method do |lfdm|
lfdm.webhook = client.resource.webhook_delivery do |wd|
wd.advertiser_webhook_url = "http://example.com/webhook"
wd.google_secret = "interplanetary google secret"
wd.payload_schema_version = 3
end
end
end
end
response = client.service.asset.mutate_assets(
customer_id: customer_id,
operations: [operation],
)
asset_name = response.results.first.resource_name
puts "Asset with resource name #{asset_name} was created."
asset_name
end
def create_lead_form_campaign_asset(client, customer_id, campaign_id, lead_form_asset)
operation = client.operation.create_resource.campaign_asset do |ca|
ca.asset = lead_form_asset
ca.field_type = :LEAD_FORM
ca.campaign = client.path.campaign(customer_id, campaign_id)
end
response = client.service.campaign_asset.mutate_campaign_assets(
customer_id: customer_id,
operations: [operation],
)
puts "Created campaign asset #{response.results.first.resource_name} for " \
"campaign #{campaign_id}."
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
options[:campaign_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_lead_form_asset(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:campaign_id),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
پرل
#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example creates a lead form and a lead form asset for a campaign.
# Run add_campaigns.pl to create a campaign.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V19::Resources::CampaignAsset;
use Google::Ads::GoogleAds::V19::Resources::Asset;
use Google::Ads::GoogleAds::V19::Common::LeadFormAsset;
use Google::Ads::GoogleAds::V19::Common::LeadFormField;
use Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers;
use Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod;
use Google::Ads::GoogleAds::V19::Common::WebhookDelivery;
use Google::Ads::GoogleAds::V19::Enums::AssetFieldTypeEnum qw(LEAD_FORM);
use Google::Ads::GoogleAds::V19::Enums::LeadFormCallToActionTypeEnum
qw(BOOK_NOW);
use Google::Ads::GoogleAds::V19::Enums::LeadFormFieldUserInputTypeEnum
qw(FULL_NAME EMAIL PHONE_NUMBER PREFERRED_CONTACT_TIME TRAVEL_BUDGET);
use Google::Ads::GoogleAds::V19::Enums::LeadFormPostSubmitCallToActionTypeEnum
qw(VISIT_SITE);
use
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation;
use Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V19::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
sub add_lead_form_asset {
my ($api_client, $customer_id, $campaign_id) = @_;
# Create a lead form asset.
my $lead_form_asset_resource_name =
create_lead_form_asset($api_client, $customer_id);
# Create a lead form asset for the campaign.
create_lead_form_campaign_asset($api_client, $customer_id, $campaign_id,
$lead_form_asset_resource_name);
return 1;
}
# Creates the lead form campaign asset.
sub create_lead_form_campaign_asset {
my ($api_client, $customer_id, $campaign_id, $lead_form_asset_resource_name)
= @_;
# Create the campaign asset for the lead form.
my $campaign_asset =
Google::Ads::GoogleAds::V19::Resources::CampaignAsset->new({
asset => $lead_form_asset_resource_name,
fieldType => LEAD_FORM,
campaign => Google::Ads::GoogleAds::V19::Utils::ResourceNames::campaign(
$customer_id, $campaign_id
)});
my $campaign_asset_operation =
Google::Ads::GoogleAds::V19::Services::CampaignAssetService::CampaignAssetOperation
->new({
create => $campaign_asset
});
my $campaign_assets_response = $api_client->CampaignAssetService()->mutate({
customerId => $customer_id,
operations => [$campaign_asset_operation]});
printf
"Created campaign asset with resource name = '%s' for campaign ID %d.\n",
$campaign_assets_response->{results}[0]{resourceName}, $campaign_id;
}
# Creates the lead form asset.
sub create_lead_form_asset {
my ($api_client, $customer_id) = @_;
# Create the lead form asset.
my $lead_form_asset = Google::Ads::GoogleAds::V19::Resources::Asset->new({
name => "Interplanetary Cruise Lead Form #" . uniqid(),
leadFormAsset => Google::Ads::GoogleAds::V19::Common::LeadFormAsset->new({
# Specify the details of lead form that the users will see.
callToActionType => BOOK_NOW,
callToActionDescription => "Latest trip to Jupiter!",
# Define the form details.
businessName => "Interplanetary Cruise",
headline => "Trip to Jupiter",
description => "Our latest trip to Jupiter is now open for booking.",
privacyPolicyUrl => "http://example.com/privacy",
# Define the fields to be displayed to the user.
fields => [
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => FULL_NAME
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => EMAIL
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PHONE_NUMBER
}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => PREFERRED_CONTACT_TIME,
singleChoiceAnswers =>
Google::Ads::GoogleAds::V19::Common::LeadFormSingleChoiceAnswers
->new({
answers => ["Before 9 AM", "Any time", "After 5 PM"]})}
),
Google::Ads::GoogleAds::V19::Common::LeadFormField->new({
inputType => TRAVEL_BUDGET
})
],
# Optional: You can also specify a background image asset.
# To upload an asset, see misc/upload_image_asset.pl.
# backgroundImageAsset => "INSERT_IMAGE_ASSET_HERE",
# Optional: Define the response page after the user signs up on the form.
postSubmitHeadline => "Thanks for signing up!",
postSubmitDescription => "We will reach out to you shortly. " .
"Visit our website to see past trip details.",
postSubmitCallToActionType => VISIT_SITE,
# Optional: Display a custom disclosure that displays along with the
# Google disclaimer on the form.
customDisclosure => "Trip may get cancelled due to meteor shower.",
# Optional: Define a delivery method for the form response. See
# https://developers.google.com/google-ads/webhook/docs/overview for
# more details on how to define a webhook.
deliveryMethods => [
Google::Ads::GoogleAds::V19::Common::LeadFormDeliveryMethod->new({
webhook =>
Google::Ads::GoogleAds::V19::Common::WebhookDelivery->new({
advertiserWebhookUrl => "http://example.com/webhook",
googleSecret => "interplanetary google secret",
payloadSchemaVersion => 3
})})]}
),
finalUrls => ["http://example.com/jupiter"]});
# Create the operation.
my $asset_operation =
Google::Ads::GoogleAds::V19::Services::AssetService::AssetOperation->new({
create => $lead_form_asset
});
my $assets_response = $api_client->AssetService()->mutate({
customerId => $customer_id,
operations => [$asset_operation]});
my $lead_form_asset_resource_name =
$assets_response->{results}[0]{resourceName};
# Display the result.
printf "Asset with resource name = '%s' was created.\n",
$lead_form_asset_resource_name;
return $lead_form_asset_resource_name;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_id);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
if not check_params($customer_id, $campaign_id);
# Call the example.
add_lead_form_asset($api_client, $customer_id =~ s/-//gr, $campaign_id);
=pod
=head1 NAME
add_lead_form_asset
=head1 DESCRIPTION
This code example creates a lead form and a lead form asset for a campaign.
Run add_campaigns.pl to create a campaign.
=head1 SYNOPSIS
add_lead_form_asset.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-campaign_id ID of the campaign to which lead form assets are added.
=cut
جز در مواردی که غیر از این ذکر شده باشد،محتوای این صفحه تحت مجوز Creative Commons Attribution 4.0 License است. نمونه کدها نیز دارای مجوز Apache 2.0 License است. برای اطلاع از جزئیات، به خطمشیهای سایت Google Developers مراجعه کنید. جاوا علامت تجاری ثبتشده Oracle و/یا شرکتهای وابسته به آن است.
تاریخ آخرین بهروزرسانی 2025-03-14 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-03-14 بهوقت ساعت هماهنگ جهانی."],[[["These code examples demonstrate creating a lead form asset within the Google Ads platform, including setting the call-to-action, business details, form fields, and post-submission experiences."],["The code connects the newly created lead form asset to a specific Google Ads campaign using a campaign asset object, associating the lead form to the desired campaign for targeting."],["Multiple programming languages like Java, C#, PHP, Python, Ruby, and Perl are demonstrated for creating a lead form asset and the scripts leverage the Google Ads API to interact with Google Ads."],["Each code example supports different methods of customization to set up the lead forms, including optional features like custom disclosures, background images, and webhook delivery methods."],["Error handling is incorporated within the code in order to manage potential issues when interacting with the Google Ads API, ensuring that errors are caught and reported appropriately."]]],[]]