<?php
use zcrmsdk\crm\setup\restclient\ZCRMRestClient;
use zcrmsdk\oauth\ZohoOAuth;
/**
* Returns credentials for accessing the database
* This is only really necessary because of how my local environment works
*
* @since {{VERSION}}
* @return array Database Credentials
*/
function pws_zoho_get_database_credentials() {
$host = DB_HOST;
$port = ini_get( 'mysqli.default_port' );
// Fix for my Docker Environment. Likely won't ever impact any real servers
if ( strpos( DB_HOST, ':' ) ) {
$parts = explode( ':', DB_HOST );
$host = $parts[0];
$port = $parts[1];
}
//
https://developer.wordpress.org/reference/functions/apply_filters/ return apply_filters( 'pws_zoho_get_database_credentials', array(
'host' => $host,
'port' => $port,
'username' => DB_USER,
'password' => DB_PASSWORD,
) );
}
/**
* Quickly obtain the config for the Zoho SDK
*
* @since {{VERSION}}
* @return array Zoho SDK Config
*/
function pws_zoho_get_config() {
$client_id = pws_zoho_get_option( 'pws_zoho_client_id' );
$client_secret = pws_zoho_get_option( 'pws_zoho_client_secret' );
$db_creds = pws_zoho_get_database_credentials();
$redirect_uri = urlencode_deep( admin_url( 'options-general.php?page=pws-zoho-api' ) );
//
https://developer.wordpress.org/reference/functions/apply_filters/ return apply_filters( 'pws_zoho_get_config', array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'host_address' => $db_creds['host'],
'db_port' => $db_creds['port'],
'db_username' => $db_creds['username'],
'db_password' => $db_creds['password'],
) );
}
$linked = pws_zoho_get_option( 'pws_zoho_app_linked' );
// If we need to get an OAUTH Token
// $_GET['state'] is set by the JavaScript for the oAuth2 Popup
// $_GET['page'] is set properly by our redirect_uri
if ( isset( $_GET['code'] ) &&
isset( $_GET['state'] ) &&
$_GET['state'] == 'saving' &&
isset( $_GET['page'] ) &&
$_GET['page'] == 'pws-zoho-api' &&
( ! $linked || $linked == '-1' ) ) {
$configuration = pws_zoho_get_config();
$notices = (array) get_transient( 'pws_zoho_api_admin_notice' );
ZohoOAuth::initialize( $configuration );
$oAuthClient = ZohoOAuth::getClientInstance();
// This saves both Access and Refresh Tokens to the custom Database
$oAuthTokens = $oAuthClient->generateAccessToken( $_GET['code'] );
if ( ! is_a( $oAuthTokens, 'ZohoOAuthException' ) ) {
pws_zoho_update_option( 'pws_zoho_app_linked', true );
pws_zoho_update_option( 'pws_zoho_refresh_token', $oAuthTokens->getRefreshToken() );
set_transient( 'pws_zoho_api_admin_notice', array_merge( $notices, array( array(
'pws-zoho-api',
'pws_zoho_api_link_successful',
__( 'Zoho App Linked Successfully.', 'pws-zoho-api-plugin' ),
'updated'
) ) ) );
}
else {
set_transient( 'pws_zoho_api_admin_notice', array_merge( $notices, array( array(
'pws-zoho-api',
'pws_zoho_api_link_failure',
__( 'Zoho App Failed to Link', 'pws-zoho-api-plugin' ),
'error'
) ) ) );
}
wp_redirect( admin_url( 'options-general.php?page=pws-zoho-api' ) );
}