GoogleReviews
Class GoogleReviews.
Source Source
File: mortgage-google-review/inc/GoogleReviews.php
class GoogleReviews {
/**
* Get Google reviews.
*
* @access public
* @since 1.0.0
*
* @param array|string $atts shortcode attributes
*
* @return array {
* Reviews.
* @type array reviewer {
* Reviewer.
* @type string 'name' The person's full name
* @type string 'link' The link of reviews page
* @type string 'image' The person's profile picture url
* @type string 'rating' Rating
* @type string 'text' Review text included in the review
* @type string 'date' When the reviewer rated this object
* }
* }
*/
public function get_reviews($atts){
if(isset(get_option('mortgage_google_widget')['api']) && 'map' === get_option('mortgage_google_widget')['api']){
$place_id = get_option('mortgage_google_widget')['place_id'] ?? "";
$api_key = get_option('mortgage_google_widget')['api_key'] ?? "";
if(empty($place_id) && empty($api_key)) return array();
$url = 'https://maps.googleapis.com/maps/api/place/details/json?reference='.$place_id.'&key='.$api_key;
$reviews = $this->request($url,1);
$reviews = isset($reviews['result']['reviews']) ? $reviews['result']['reviews'] : array();
$reviews = $this->prepare_reviews($reviews);
return $reviews;
} elseif(isset(get_option('mortgage_google_widget')['api']) && 'business' === get_option('mortgage_google_widget')['api']){
//@to-do check data from API and add count
$access_token = json_decode($this->get_access_token(),1)['access_token'];
$count = isset($atts['count']) && !empty($atts['count']) ? $atts['count'] : (isset(get_option('mortgage_google_widget')['count']) ? get_option('mortgage_google_widget')['count'] : 3);
$account = $this->get_account_id();
$location = $this->get_location_id();
$url = 'https://mybusiness.googleapis.com/v4/accounts/'.$account.'/locations/'.$location.'/reviews';
$header = array(
"Authorization" => 'Bearer '.$access_token,
'content-type' => 'application/json'
);
$reviews = $this->request($url,1, $header);
$reviews = isset($reviews['reviews']) ? $reviews['reviews'] : array();
$reviews = $this->prepare_reviews($reviews);
return $reviews;
} else {
return array();
}
}
/**
* Request.
*
* @access protected
* @since 1.0.0
*
* @param string $url URL
* @param bool|null $associative [optional] When true, returned objects will be converted into associative arrays.
*
* @return mixed $response The body of the response. Empty string if no body or incorrect parameter given.
*/
protected function request(string $url, $associative = false, $header = '' ){
$response = get_transient(md5($url));
if(!$response) {
$header = ! empty( $header ) ? $header : array( 'Content-Type' => 'application/json' );
$response = wp_remote_get( $url, array(
"headers" => $header
)
);
$response = wp_remote_retrieve_body( $response );
$response = json_decode( $response, $associative );
set_transient(md5($url), $response, DAY_IN_SECONDS);
}
return $response;
}
/**
* Prepare reviews to display.
* @access protected
* @since 1.0.0
* @see https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews
* @param array $reviews {
*
* Array of reviews.
*
* @type string 'author_name' The name of the reviewer
* @type string 'author_url' The URL of the reviewer
* @type string 'language' language
* @type string 'profile_photo_url' The reviewer photo URL
* @type int 'rating' The star rating of the review.
* @type string 'relative_time_description' The relative time when the review was written
* @type string 'text' Text of review
* @type int 'time' The timestamp for when the review was written
* }
*
* @return array {
* Reviews.
* @type array reviewer {
* Reviewer.
* @type string 'name' The person's full name
* @type string 'link' The link of reviews page
* @type string 'image' The person's profile picture url
* @type string 'rating' Rating
* @type string 'text' Review text included in the review
* @type string 'date' When the reviewer rated this object
* }
* }
*
*/
protected function prepare_reviews($reviews){
$google_review = array();
if(!isset(get_option('mortgage_google_widget')['api'])) return $google_review;
if('map' === get_option('mortgage_google_widget')['api']){
foreach ($reviews as $review) {
$google_review[] = array(
"name" => sanitize_text_field($review['author_name']),
"link" => isset(get_option('mortgage_google_widget')['place_id']) ? esc_url_raw('https://search.google.com/local/reviews?placeid='.get_option('mortgage_google_widget')['place_id']) : '',
"image" => esc_url_raw($review['profile_photo_url']),
"rating" => sanitize_text_field($review['rating']),
"text" => sanitize_text_field($review['text']),
"date" => date_i18n('j F Y H:i:s',sanitize_text_field($review['time'])),
);
}
}
if('business' === get_option('mortgage_google_widget')['api']){
foreach ($reviews as $review) {
$google_review[] = array(
"name" => sanitize_text_field($review['reviewer']['displayName']),
"link" => esc_url_raw('https://search.google.com/local/reviews?placeid='.get_option('mortgage_google_widget')['place_id']),
"image" => esc_url_raw($review['reviewer']['profilePhotoUrl']),
"rating" => sanitize_text_field($review['starRating']),
"text" => sanitize_text_field($review['comment']),
"date" => date_i18n('j F Y H:i:s',sanitize_text_field($review['createTime'])),
);
}
}
return $google_review;
}
/**
* Get client ID.
*
* @access private
* @since 1.0.0
*
* @return mixed client ID
*/
private function get_client_id() {
$client_id = get_option( 'mortgage_google_widget' )['client_id'] ?? '';
return $client_id;
}
/**
* Get client secret.
*
* @access private
* @since 1.0.0
*
* @return mixed client secret
*/
private function get_client_secret() {
$client_secret = get_option( 'mortgage_google_widget' )['client_secret'] ?? '';
return $client_secret;
}
/**
* Get refresh token.
*
* @access private
* @since 1.0.0
*
* @return mixed refresh token
*/
private function get_refresh_token() {
$google_refresh_token = get_option( 'mortgage_google_widget_refresh_token' );
return $google_refresh_token;
}
/**
* Get google access token.
*
* @access private
* @since 1.0.0
*
* @return string|void access token
*/
private function get_access_token() {
$google_access_token = get_option( 'mortgage_google_widget_access_token' );
return $google_access_token;
}
/**
* Get account ID.
*
* @access private
* @since 1.0.0
*
* @return string|void access token
*/
private function get_account_id() {
$account_id = get_option( 'mortgage_google_widget' )['account'] ?? '';
return $account_id;
}
/**
* Get location ID.
*
* @access private
* @since 1.0.0
*
* @return string|void access token
*/
private function get_location_id() {
$location_id = get_option( 'mortgage_google_widget' )['location'] ?? '';
return $location_id;
}
/**
* @to-do Check get accounts and display int settings
* Set My business API accounts.
*
* @access public
* @since 1.0.0
*
* @return bool True if the value was updated, false otherwise.
*/
public function set_accounts(){
$client = $this->get_client();
$my_business = new \Google_Service_MyBusinessAccountManagement($client);
$account_list = false;//$my_business->accounts->listAccounts();
$accounts = array();
if($account_list){
foreach ($account_list as $account){
$accounts[] = array(
$account->name => $account->accountName,
);
}
}
$google_option = get_option('mortgage_google_widget');
$google_option['account'] = $accounts;
return update_option('mortgage_google_widget',$google_option);
}
/**
* @to-do Check get locations and display int settings
* Set My business API locations.
*
* @access public
* @since 1.0.0
*
* @return bool True if the value was updated, false otherwise.
*/
public function set_locations(){
$client = $this->get_client();
$my_business = new \Google_Service_MyBusinessAccountManagement($client);
$location_list = $my_business->locations;
$locations = array();
foreach ($location_list as $location){
$locations[] = array(
$location->name => $location->locationName,
);
}
$google_option = get_option('mortgage_google_widget');
$google_option['location'] = $locations;
return update_option('mortgage_google_widget',$google_option);
}
/**
* Set google access token.
*
* @access private
* @since 1.0.0
*
* @param array $token access token.
*
* @return string|void access token
*/
private function set_access_token( $token ) {
$token = wp_json_encode($token);
$google_access_token = update_option( 'mortgage_google_widget_access_token', $token );
return $google_access_token;
}
/**
* Callback function revoke token.
*
* @access public
* @since 1.0.0
*/
public function revoke_token() {
$client = $this->get_client();
$client->revokeToken(get_option('mortgage_google_widget_access_token'));
update_option( 'mortgage_google_widget_refresh_token', "");
update_option( 'mortgage_google_widget_access_token', "" );
wp_die();
}
/**
* Get redirect URI.
*
* @access private
* @since 1.0.0
*
* @return string|void redirect uri
*/
private function get_redirect_uri() {
$redirect_url = get_option( 'mortgage_google_widget' )['redirect_uri'] ?? '';
return $redirect_url;
}
/**
* Get google client.
*
* Get refresh token.
* Get access token.
*
* @access public
* @since 1.0.0
*
* @return Google_Client|string
*/
public function get_client() {
$client_id = $this->get_client_id();
$client_secert = $this->get_client_secret();
$redirect_uri = $this->get_redirect_uri();
$client = new Google_Client(['api_format_v2' => true]);
$client->setScopes( "https://www.googleapis.com/auth/plus.business.manage" );
$client->setScopes( "https://www.googleapis.com/auth/business.manage" );
$client->setClientId( $client_id );
$client->setClientSecret( $client_secert );
$client->setRedirectUri( $redirect_uri );
$client->setAccessType( 'offline' );
//$client->setApprovalPrompt( 'force' );
// Load previously authorized credentials from a file.
$auth_token = $this->get_refresh_token();
if ( empty( $auth_token ) ) {
$auth_url = $client->createAuthUrl();
return $auth_url;
}
$accessToken = $this->get_access_token();
if ( !empty( $accessToken ) ) {
$accessToken = json_decode($accessToken, true);
} else {
if ( empty( $auth_token ) ) {
$auth_url = $client->createAuthUrl();
return $auth_url;
}
else{
$authCode = trim($auth_token);
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
$this->set_access_token($accessToken);
}
}
$client->setAccessToken( $accessToken );
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
// save refresh token to some variable
$refreshTokenSaved = $client->getRefreshToken();
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// pass access token to some variable
$accessTokenUpdated = $client->getAccessToken();
// append refresh token
$accessTokenUpdated['refresh_token'] = $refreshTokenSaved;
//Set the new acces token
$accessToken = $refreshTokenSaved;
$this->set_access_token(wp_json_encode( $accessTokenUpdated ));
$accessToken = json_decode( wp_json_encode( $accessTokenUpdated ), true);
$client->setAccessToken($accessToken);
}
return $client;
}
/**
* Decode state.
* Decodes Data from $state query arg and adds them to $_REQUEST. This must happen
* before admin-ajax.php checks for the 'action' value
* @access public
* @since 1.0.0
*/
public function decode_state() {
if ( ! is_admin() || ! is_user_logged_in() ) {
return;
}
if ( ! isset( $_REQUEST['page'] ) || ! is_string( $_REQUEST['page'] ) ) {
return;
}
if( isset( $_GET['page'] ) && 'mortgage_google_widget' === $_GET['page']) {
$this->get_refresh_code();
}
}
/**
* Get refresh code from GET params.
*
* @access public
* @since 1.0.0
*
* @return string
*/
public function get_refresh_code() {
$token_value = $this->get_refresh_token();
$code = '';
if ( isset( $_GET['code'] ) && ! empty( $_GET['code'] ) ) {
$code = sanitize_text_field($_GET['code']);
update_option('mortgage_google_widget_refresh_token',sanitize_text_field($_GET['code']));
wp_redirect( get_admin_url() . 'admin.php?page=mortgage_google_widget' );
}
$value = $token_value ? $token_value : $code;
return $value;
}
}
Methods Methods
- decode_state — Decode state.
- get_access_token — Get google access token.
- get_account_id — Get account ID.
- get_client — Get google client.
- get_client_id — Get client ID.
- get_client_secret — Get client secret.
- get_location_id — Get location ID.
- get_redirect_uri — Get redirect URI.
- get_refresh_code — Get refresh code from GET params.
- get_refresh_token — Get refresh token.
- get_reviews — Get Google reviews.
- prepare_reviews — Prepare reviews to display.
- request — Request.
- revoke_token — Callback function revoke token.
- set_access_token — Set google access token.
- set_accounts
- set_locations
Changelog Changelog
| Version | Description |
|---|---|
| 1.0.0 | Introduced. |