Skip to content

Commit

Permalink
* Пакет переведён на работу с Google Ads API v10.
Browse files Browse the repository at this point in the history
* В блок `gads_utils.R` добавлена функция `gads_make_request()`, теперь это основная функция генерации HTTP запроса, она используется в остальных функциях для отправки запросов.
* Исправил логическую ошибку в функции `gads_get_report()`, ранее функция формировала запрос, и только потом осуществляла проверку, может ли указанный ресурс запрашиваться с сегментами времени.
* Полностью переписана функция `gads_customer()`, ранее она была написана на основе метода get, [который в 10 версии API был упразднён](https://developers.google.com/google-ads/api/docs/release-notes#all_services), теперь функция использует метод `SearchStream `. Это обновление так же затронуло функцию `gads_get_accessible_customers()`, т.к. в неё использовалась `gads_customer()`.
  • Loading branch information
selesnow committed May 31, 2022
1 parent 0301550 commit 984e2fa
Show file tree
Hide file tree
Showing 15 changed files with 162 additions and 161 deletions.
3 changes: 1 addition & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: rgoogleads
Title: Loading Data from 'Google Ads API'
Version: 0.6.0
Version: 0.7.0
Authors@R:
c(person(given = "Alexey",
family = "Seleznev",
Expand Down Expand Up @@ -30,7 +30,6 @@ Imports: gargle (>= 1.2.0),
withr,
rlist,
rvest (>= 1.0.0),
magrittr,
memoise,
cachem,
rappdirs
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import(purrr)
import(gargle)
import(snakecase)
import(memoise)
import(cachem)
import(rappdirs)

# import from
importFrom(rlang,"%||%")
Expand Down
6 changes: 6 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# rgoogleads 0.7.0
* Пакет переведён на работу с Google Ads API v10.
* В блок `gads_utils.R` добавлена функция `gads_make_request()`, теперь это основная функция генерации HTTP запроса, она используется в остальных функциях для отправки запросов.
* Исправил логическую ошибку в функции `gads_get_report()`, ранее функция формировала запрос, и только потом осуществляла проверку, может ли указанный ресурс запрашиваться с сегментами времени.
* Полностью переписана функция `gads_customer()`, ранее она была написана на основе метода get, [который в 10 версии API был упразднён](https://developers.google.com/google-ads/api/docs/release-notes#all_services), теперь функция использует метод `SearchStream `. Это обновление так же затронуло функцию `gads_get_accessible_customers()`, т.к. в неё использовалась `gads_customer()`.

# rgoogleads 0.6.0
* В функцию `gads_get_report()` добавлен аргумент gaql_query, который позволяет передать функции готовый текст запроса, скопированный из [QueryBuilder](https://developers.google.com/google-ads/api/fields/v10/overview_query_builder).
* Новая функция `gads_get_keywords()` для запроса списка ключевых слов.
Expand Down
39 changes: 15 additions & 24 deletions R/gads_customer.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,23 @@ gads_customer <- function(
verbose = TRUE
) {

# delete - in customer id
customer_id <- str_replace_all(customer_id, '-', '')

# to env
gads_customer_id_to_env(customer_id)

# build query
out <- request_build(
method = "GET",
path = str_glue('{options("gads.api.version")}/customers/{customer_id}/'),
token = gads_token(),
base_url = getOption('gads.base.url')
# pars result
data <- gads_get_report(
resource = "customer",
fields = c("customer.id",
"customer.descriptive_name",
"customer.manager",
"customer.currency_code",
"customer.time_zone",
"customer.auto_tagging_enabled",
"customer.has_partners_badge",
"customer.test_account"),
customer_id = customer_id,
login_customer_id = customer_id,
verbose = verbose
)

# send request
ans <- request_retry(
out,
add_headers(`developer-token`= gads_developer_token())
)

# request id
rq_ids <- headers(ans)$`request-id`
rgoogleads$last_request_id <- rq_ids

# pars result
data <- response_process(ans, error_message = gads_check_errors2)
data <- rename_with(data, gads_fix_names_regexp, everything(), regexp = 'customer\\_')

# return the data
return(data)
Expand Down
29 changes: 4 additions & 25 deletions R/gads_get_accessible_customers.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,11 @@
gads_get_accessible_customers <- function()
{

# check token
gargle::token_tokeninfo(gads_token())

# send query
out <- request_build(
method = "GET",
path = str_glue('{options("gads.api.version")}/customers:listAccessibleCustomers'),
token = gads_token(),
base_url = getOption('gads.base.url')
)

# send request
ans <- request_retry(
out,
add_headers(`developer-token`= gads_developer_token())
)

# get result
rawres <- response_process(ans, error_message = gads_check_errors2)

rq_ids <- unique(ans$headers$`request-id`)
rgoogleads$last_request_id <- rq_ids

# check for error
gads_check_errors(out = rawres, request_id = rq_ids)
rawres <- gads_make_request(
http_method = "GET",
api_method = "customers:listAccessibleCustomers"
)

# processing result
unlist(rawres$resourceNames) %>%
Expand Down Expand Up @@ -68,7 +48,6 @@ gads_get_accessible_customers <- function()
res <- tibble(data = list.filter(res$result, length(.) > 1)) %>%
unnest_wider('data') %>%
select(!where(is.list)) %>%
select(-"resourceName") %>%
rename_with(getOption('gads.column.name.case.fun'))

# success msg
Expand Down
89 changes: 33 additions & 56 deletions R/gads_get_account_hierarchy.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,71 +20,48 @@ gads_get_account_hierarchy <- function(
login_customer_id = getOption('gads.login.customer.id')
) {

# check token
gargle::token_tokeninfo(gads_token())

# remove - from manager_customer id
manager_customer_id <- str_replace_all(manager_customer_id, '-', '')

# drafts
drafts <- ifelse(include_drafts, 'PARAMETERS include_drafts=true', '')

# build GAQL Query
body <- list(query =
str_glue('
SELECT
customer_client.applied_labels,
customer_client.client_customer,
customer_client.currency_code,
customer_client.descriptive_name,
customer_client.hidden,
customer_client.id,
customer_client.level,
customer_client.manager,
customer_client.test_account,
customer_client.time_zone,
customer.currency_code,
customer.descriptive_name,
customer.final_url_suffix,
customer.has_partners_badge,
customer.id,
customer.manager,
customer.optimization_score,
customer.optimization_score_weight,
customer.pay_per_conversion_eligibility_failure_reasons,
customer.test_account,
customer.time_zone,
customer.tracking_url_template
FROM customer_client
gaql_query <- gads_make_query(
resource = 'customer_client',
fields = c( 'customer_client.applied_labels',
'customer_client.client_customer',
'customer_client.currency_code',
'customer_client.descriptive_name',
'customer_client.hidden',
'customer_client.id',
'customer_client.level',
'customer_client.manager',
'customer_client.test_account',
'customer_client.time_zone',
'customer.currency_code',
'customer.descriptive_name',
'customer.final_url_suffix',
'customer.has_partners_badge',
'customer.id',
'customer.manager',
'customer.optimization_score',
'customer.optimization_score_weight',
'customer.pay_per_conversion_eligibility_failure_reasons',
'customer.test_account',
'customer.time_zone',
'customer.tracking_url_template'
),date_from = NULL, date_to = NULL, during = NULL,
parameters = ifelse(include_drafts, 'include_drafts=true', 'include_drafts=false')
)

{drafts}')) %>%
toJSON(auto_unbox = T, pretty = T)
body <- list(query = gaql_query) %>%
toJSON(auto_unbox = T, pretty = T)

# send query
# send query
out <- request_build(
method = "POST",
body = body,
path = str_glue('{options("gads.api.version")}/customers/{manager_customer_id}/googleAds:searchStream'),
token = gads_token(),
base_url = getOption('gads.base.url')
out <- gads_make_request(
http_method = "POST",
body = body,
api_method = str_glue('customers/{manager_customer_id}/googleAds:searchStream')
)

# send request
ans <- request_retry(
out,
encode = 'json',
add_headers(`developer-token`= gads_developer_token(),
`login-customer-id` = login_customer_id)
)

# read answer
out <- response_process(ans, error_message = gads_check_errors2)

# check for error
gads_check_errors(out,request_id = headers(ans)$`request-id`)

# parse answer
tibble(data = out) %>%
unnest_wider('data') %>%
Expand Down
20 changes: 10 additions & 10 deletions R/gads_get_report.R
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ gads_get_report <- function(
# test for selectble with date fields
selectable <- suppressMessages( gads_get_fields_cached(resource)$selectableWith )

if ( getOption('gads.show_gaql_query') ) cat("\n\nGAQL Query:\n\n", gaql_query)

# where block
if (! "segments.date" %in% selectable ) {
date_from <- NULL
date_to <- NULL
during <- NULL
cli_alert_warning('fields values of date_from, date_to and during was unset automatically, because it is not selectable with {resource}')
}

# query
# compose query if needed
if ( is.null(gaql_query) ) {
Expand All @@ -140,16 +150,6 @@ gads_get_report <- function(
)
}

if ( getOption('gads.show_gaql_query') ) cat("\n\nGAQL Query:\n\n", gaql_query)

# where block
if (! "segments.date" %in% selectable ) {
date_from <- NULL
date_to <- NULL
during <- NULL
cli_alert_warning('fields values of date_from, date_to and during was unset automatically, because it is not selectable with {resource}')
}

# check how many accounts
if ( length(customer_id) == 1 ) {

Expand Down
43 changes: 7 additions & 36 deletions R/gads_get_report_helper.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,42 +34,13 @@ gads_get_report_helper <- function(
# info
if (verbose) cli_alert_info('Send request')

# send query
out <- request_build(
method = "POST",
body = body,
path = str_glue('{options("gads.api.version")}/customers/{customer_id}/googleAds:searchStream'),
token = gads_token(),
base_url = getOption('gads.base.url')
)

# send request
ans <- request_retry(
out,
encode = 'json',
add_headers(`developer-token`= gads_developer_token(),
`login-customer-id` = login_customer_id)
)

# --------------
# get answer
if (verbose) cli_alert_info('Get answer query')
out <- response_process(ans, error_message = gads_check_errors2)

# requests_ids
if ( !is.null(ans$headers$`request-id`) ) {

rq_ids <- unique(ans$headers$`request-id`)
rgoogleads$last_request_id <- rq_ids
if (verbose) cli_alert_info(c("Your request ids: ", rq_ids))

} else {

rgoogleads$last_request_id <- unique(sapply(out, function(x) x$requestId))
rq_ids <- str_c(rgoogleads$last_request_id, collapse = ', ')
if (verbose) cli_alert_info(c("Your request ids: ", rq_ids))

}
out <- gads_make_request(
body = body,
api_method = str_glue("customers/{customer_id}/googleAds:searchStream"),
customer_id = customer_id,
login_customer_id = login_customer_id,
verbose = verbose
)

# check for errors
#gads_check_errors(out, customer_id, verbose, rq_ids)
Expand Down
57 changes: 56 additions & 1 deletion R/gads_utils.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# cache
gads_get_fields_cached <- memoise(gads_get_fields)

# make query
# make gaul query
gads_make_query <- function(
resource = 'campaign',
fields = c('campaign.id',
Expand Down Expand Up @@ -84,3 +84,58 @@ gads_make_query <- function(
return(gaql_query)

}


# make request
gads_make_request <- function(
http_method = "POST",
body = NULL,
api_version = options("gads.api.version"),
api_method = "googleAds:searchStream",
customer_id = getOption('gads.customer.id'),
login_customer_id = getOption('gads.login.customer.id'),
verbose = TRUE
) {

# send query
out <- request_build(
method = http_method,
body = body,
path = str_glue('{api_version}/{api_method}'),
token = gads_token(),
base_url = getOption('gads.base.url')
)

# send request
ans <- request_retry(
out,
encode = 'json',
add_headers(
`developer-token`= gads_developer_token(),
`login-customer-id` = login_customer_id
)
)

# --------------
# get answer
if (verbose) cli_alert_info('Get answer query')
out <- response_process(ans, error_message = gads_check_errors2)

# requests_ids
if ( !is.null(ans$headers$`request-id`) ) {

rq_ids <- unique(ans$headers$`request-id`)
rgoogleads$last_request_id <- rq_ids
if (verbose) cli_alert_info(c("Your request ids: ", rq_ids))

} else {

rgoogleads$last_request_id <- unique(sapply(out, function(x) x$requestId))
rq_ids <- str_c(rgoogleads$last_request_id, collapse = ', ')
if (verbose) cli_alert_info(c("Your request ids: ", rq_ids))

}

return(out)

}
2 changes: 1 addition & 1 deletion R/zzz.R
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
# options
op <- options()
op.gads <- list(gads.developer.token = developer_token,
gads.api.version = "v9",
gads.api.version = "v10",
gads.login.customer.id = login_customer_id,
gads.customer.id = customer_id,
gads.multi.account.verbos = FALSE,
Expand Down
Loading

0 comments on commit 984e2fa

Please sign in to comment.