#' Get or store an access token
#'
#' \code{get_access_token} gets an access token for the API. To obtain the
#' client ID and client secret, you need to create a Yelp app. This is free, and
#' takes about 10 minutes. Go to
#' \url{https://www.yelp.com/developers/documentation/v3/authentication} for
#' instructions.
#' \code{store_access_token} stores the access token as an environment variable.
#' @param client_id A string giving the Client ID.
#' @param client_secret A string giving the client secret.
#' @param access_token A string generated by \code{get_access_token}.
#' @return \code{get_access_token} returns 128 character string giving the
#' access token.
#' \code{store_access_token} is invoked for the side-effect of storing the
#' access token in an environment variable.
#' @references \url{https://www.yelp.com/developers/documentation/v3/authentication}
#' @examples
#' \dontrun{
#' (access_token <- get_access_token())
#' store_access_token(access_token)
#' }
#' @importFrom assertive.types assert_is_a_string
#' @importFrom httr POST
#' @importFrom httr stop_for_status
#' @importFrom httr content
#' @export
get_access_token <- function(client_id, client_secret) {
assert_is_a_string(client_id)
if(client_id == "") {
stop("You need to provide a client ID.")
}
assert_is_a_string(client_secret)
if(client_secret == "") {
stop("You need to provide a client secret.")
}
response <- POST(
"https://api.yelp.com/oauth2/token",
query = list(
grant_type = "client_credentials",
client_id = client_id,
client_secret = client_secret
),
encode = "json"
)
stop_for_status(response)
token <- content(response, as = "parsed")
token$access_token
}
#' @rdname get_access_token
#' @export
store_access_token <- function(access_token) {
Sys.setenv(YELP_ACCESS_TOKEN = access_token)
}
#' @importFrom assertive.types is_a_string
#' @noRd
assert_has_access_token <- function(access_token) {
if(is.na(access_token)) {
stop("No Yelp API access token was found. See ?get_access_token.")
}
if(!is_a_string(access_token)) {
stop("The Yelp API access token is not a string. See ?get_access_token.")
}
if(nchar(access_token) != 128L) {
stop("The Yelp API access token does not contain 128 characters. See ?get_access_token.")
}
invisible(access_token)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.