MP_Addon_Zoho

Class MP_Addon_Zoho.


Source Source

File: calculator-zoho-add-on/inc/MP_Addon_Zoho.php

class MP_Addon_Zoho {


	/**
	 * Get client ID.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return mixed client ID
	 */
	private function get_zoho_client_id() {

		$zoho_client_id = get_option( MortgagePlatform::$prefix . 'zoho' )['zoho_client_id'] ?? '';

		return $zoho_client_id;
	}

	/**
	 * Get client secret.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return mixed client secret
	 */
	private function get_zoho_client_secret() {

		$zoho_client_secret = get_option( MortgagePlatform::$prefix . 'zoho' )['zoho_client_secret'] ?? '';

		return $zoho_client_secret;
	}



	/**
	 * Get refresh token.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return mixed refresh token
	 */
	private function get_zoho_refresh_token() {

		$zoho_refresh_token = get_option( MortgagePlatform::$prefix . 'zoho_refresh_token' );

		return $zoho_refresh_token;
	}


	/**
	 * Set refresh token.
	 * @access private
	 * @since  1.0.0
	 *
	 * @param string $refresh Token zoho refresh token
	 */
	private function set_refresh_token( $refreshToken ) {

		$refreshToken = sanitize_text_field($refreshToken);

		update_option( MortgagePlatform::$prefix . 'zoho_refresh_token', $refreshToken );

	}

	/**
	 * Get zoho access token.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return string|void access token
	 */
	private function get_zoho_access_token() {

		$zoho_access_token = get_option( MortgagePlatform::$prefix . 'zoho_access_token' );

		return $zoho_access_token;

	}

	/**
	 * Set zoho access token.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @param array $token access token.
	 *
	 * @return string|void access token
	 */
	private function set_zoho_access_token( $token ) {

		$zoho_access_token = update_option( MortgagePlatform::$prefix . 'zoho_access_token', $token );

		return $zoho_access_token;

	}

	/**
	 * Revoke refresh token from Zoho.
	 *
	 * @access protected
	 * @since 1.0.0
	 */
	protected function _revoke_token() {

		$url = $this->get_api_domain().'/oauth/v2/token/revoke';
		$params = array(
			'httpversion' => '1.1',
			'blocking'    => true,
			'headers' => array(),
			'body'    => array( 'token' => $this->get_zoho_refresh_token() ),
			'cookies' => array()
		);

		$response = wp_remote_post($url, $params);

		if ( is_wp_error( $response ) ) {
			$error_message = $response->get_error_message();
			die("Error: $error_message");
		}

	}


	/**
	 * Callback function revoke token.
	 *
	 * @access public
	 * @since 1.0.0
	 */
	public function revoke_token() {

		$this->_revoke_token();

		update_option( MortgagePlatform::$prefix . 'zoho_api_domain', '');
		update_option( MortgagePlatform::$prefix . 'zoho_refresh_token', '');
		update_option( MortgagePlatform::$prefix . 'zoho_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( MortgagePlatform::$prefix . 'zoho' )['zoho_redirect_uri'] ?? '';

		return $redirect_url;
	}


	/**
	 * Get zoho account url.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return mixed|string|void Zoho API domain (Default, https://accounts.zoho.com)
	 */
	private function get_api_domain() {

		$url = get_option(MortgagePlatform::$prefix . 'zoho_api_domain');
		$value = $url ? $url : 'https://accounts.zoho.com';

		return $value;
	}



	/**
	 * 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( $_REQUEST['tab'] ) || ! is_string( $_REQUEST['tab'] ) ) {
			return;
		}

		if ( ! isset( $_GET['accounts-server'] ) || ! is_string( $_GET['accounts-server'] ) ) {
			return;
		}

		if ( isset( $_GET['accounts-server'] ) && ! empty( $_GET['accounts-server'] ) ) {
			$url = esc_url_raw($_GET['accounts-server']);
			update_option(MortgagePlatform::$prefix . 'zoho_api_domain', $url);
		}


		if( isset( $_GET['page'] ) && 'mortgage_platform' === $_GET['page'] &&  isset( $_GET['tab'] ) && 'zoho' === $_GET['tab']) {
			$this->get_refresh_code();
            wp_redirect( get_admin_url() . 'admin.php?page=mortgage_platform&tab=zoho' );
        }
	}


	/**
	 * Get authorization url.
	 *
	 * @access public
	 * @since 1.0.0
	 *
	 * @return string authorization URL
	 */
	public function get_url(){

		$url = 'https://accounts.zoho.com/oauth/v2/auth?
		response_type=code
		&client_id='.$this->get_zoho_client_id().'
		&scope=ZohoCRM.modules.ALL
		&redirect_uri='. urlencode($this->get_redirect_uri()).'
		&access_type=offline
		&prompt=consent';

		return $url;
	}


	/**
	 * Get access token.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @param string $code refresh code or authorization code
	 */
	private function get_token($code) {

		$token_url = $this->get_api_domain().'/oauth/v2/token';

		$body = array(
			'code' => $code,
			'grant_type' => 'authorization_code',
			'client_id' => $this->get_zoho_client_id(),
			'client_secret' => $this->get_zoho_client_secret(),
			'redirect_uri' => $this->get_redirect_uri(),
		);

		$response = wp_remote_post( $token_url, array( 'body' => $body ) );

		$token_request_data = json_decode($response['body'], true);

		if (empty($token_request_data))
			die("Couldn't decode '$token_request_data' as a JSON object");

		if (!isset($token_request_data['access_token'])||
		    !isset($token_request_data['api_domain']))
			die("Missing expected data from ".print_r($token_request_data, true));

		$refresh_token = $token_request_data['refresh_token'];

		$token_request_data['date_refresh'] = time() + (int)$token_request_data['expires_in'];
		$this->set_zoho_access_token($token_request_data);
		$this->set_refresh_token($refresh_token);
	}


	/**
	 * Update access token.
	 *
	 * @access private
	 * @since 1.0.0
	 */
	private function update_token() {

		$token_url = $this->get_api_domain().'/oauth/v2/token';

		$body = array(
			'grant_type' => 'refresh_token',
			'client_id' => $this->get_zoho_client_id(),
			'client_secret' => $this->get_zoho_client_secret(),
			'refresh_token' => $this->get_zoho_refresh_token(),
		);

		$response = wp_remote_post( $token_url, array( 'body' => $body ) );

		$token_request_data = json_decode($response['body'], true);

		if (empty($token_request_data))
			die("Couldn't decode '$token_request_data' as a JSON object");

		if (!isset($token_request_data['access_token'])||
		    !isset($token_request_data['api_domain']))
			die("Missing expected data from ".print_r($token_request_data, true));

		$token_request_data['date_refresh'] = time() + (int)$token_request_data['expires_in'];
		$this->set_zoho_access_token($token_request_data);

	}



	/**
	 * Get zoho client.
	 *
	 * Get refresh token.
	 * Get access token.
	 *
	 * @access public
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_client() {

		if(empty(get_option( MortgagePlatform::$prefix . 'zoho_access_token'))){
			$this->get_token($this->get_zoho_refresh_token());
		} else {

			$access_token = $this->get_zoho_access_token();
			$date_refresh = $access_token['date_refresh'];
			$now = time() + 300;

			if ($date_refresh <= $now) {
				$this->update_token();
			}
		}
	}


	/**
	 * Get refresh code from GET params.
	 *
	 * @access public
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_refresh_code() {

		$token_value = $this->get_zoho_refresh_token();
		$code        = '';
		if ( isset( $_GET['code'] ) && ! empty( $_GET['code'] ) ) {
			$code = sanitize_text_field( wp_unslash($_GET['code']) );
			$this->set_refresh_token( $code );
		}
		$value = $token_value ? $token_value : $code;

		return $value;
	}



	/**
	 * Set Lead data to Zoho.
	 * @access public
	 * @since  1.0.0
	 *
	 * @param array $lead_data lead data
	 */
	public function set_lead_data_to_zoho( $lead_data ) {

		$data = $this->prepare_lead_data( $lead_data );

		$this->get_client();

		$this->zoho_request( array($data), $lead_data['lead'] );
	}


	/**
	 * Get invest amount.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @param string $value investment amount value
	 *
	 * @return string investment amount value
	 */
	private function get_invest_amount($value) {

		$leads_investment_amount = '';
		if ( '' !== get_option( MortgagePlatform::$prefix . 'leads' )['leads_investment_amount'] ) {
			$leads_investment_amount = get_option( MortgagePlatform::$prefix . 'leads' )['leads_investment_amount'];
			$leads_investment_amount = explode( "\n", str_replace( "\r", '', $leads_investment_amount ) );
		}
		$investmentamount_value = $leads_investment_amount[$value];

		return $investmentamount_value;

	}

	/**
	 * Prepare lead data to JSON.
	 * @access private
	 * @since  1.0.0
	 *
	 * @param array $lead_data lead data
	 *
	 * @return false|string $lead_data {
	 *   Lead data in JSON.
	 *
	 *  @type string 'firstname' lead first name
	 *  @type string 'secondname' lead second name
	 *  @type string 'email' lead email
	 *  @type string 'phone' lead phone
	 *  @type string 'zipcode' lead zip code
	 *  @type string 'yearofbirth' lead year of birth
	 *  @type string 'investmentamount' investment amount
	 *
	 * }
	 */
	private function prepare_lead_data( $lead_data ) {

		//$investmentamount_value = $this->get_invest_amount($lead_data['investmentamount']);

		$data = array(
			"First_Name" => isset( $lead_data['firstname'] ) ? sanitize_text_field($lead_data['firstname']) : "",
			"Last_Name" => isset( $lead_data['secondname'] ) ? sanitize_text_field($lead_data['secondname']) : "",
			"Company" => MortgagePlatform::$plugin_name,
			"Email" => isset( $lead_data['email'] ) ? sanitize_text_field($lead_data['email']) : "",
			"Phone" => isset( $lead_data['phone'] ) ? sanitize_text_field($lead_data['phone']) : "",
			"Zip_Code" => isset( $lead_data['zipcode'] ) ? sanitize_text_field($lead_data['zipcode']) : "",
		);


		/**
		 * Action zoho data.
		 * @since 1.0.0
		 *
		 * @param array $data {
		 *   Lead data.
		 *
		 *  @type string 'firstname' lead first name
		 *  @type string 'secondname' lead second name
		 *  @type string 'email' lead email
		 *  @type string 'phone' lead phone
		 *  @type string 'zipcode' lead zip code
		 *  @type string 'yearofbirth' lead year of birth
		 *  @type string 'investmentamount' investment amount
		 *
		 * }
		 */
		do_action('zoho_data',$data);

		return $data;
	}




	/**
	 * Get duplicate fields.
	 *
	 * @access private
	 * @since 1.0.0
	 *
	 * @return array fields
	 */
	private function get_duplicate_fields(){

		$field = get_option(MortgagePlatform::$prefix . 'zoho')['zoho_duplicate_fields'] ?? '';

		$duplicate_fields = array('Email');
		switch ($field){
			case 'email':
				$duplicate_fields = array('Email');
				break;
			case 'phone':
				$duplicate_fields = array('Phone');
				break;
			case 'email_phone':
				$duplicate_fields = array('Email','Phone');
				break;
		}

		return $duplicate_fields;
	}

	/**
	 * Zoho request.
	 * @access protected
	 * @since  1.0.0
	 *
	 * @param string $data lead data
	 * @param string $lead lead ID
	 */
    protected function zoho_request($data, $lead = '') {

		$url = "https://www.zohoapis.com/crm/v2/Leads/upsert";
        $token = $this->get_zoho_access_token()['access_token'] ?? '';

		$header=array("Authorization"=> 'Zoho-oauthtoken  ' . $token  ,'content-type'=>'application/json');


		$requestBody = array(
			"data" => $data,
			"duplicate_check_fields" => $this->get_duplicate_fields()
		);

		$response = wp_remote_post( $url, array(
				'headers' => $header,
				'body' => json_encode($requestBody)
			)
		);

		$token_request_data = json_decode($response['body'], true);
		if (empty($token_request_data))
			die("Couldn't decode '$token_request_data' as a JSON object");

		if(!empty($lead)){
			$success_status = isset($token_request_data['data']['0']) ? $token_request_data['data']['0']['status'] . ': ' . $token_request_data['data']['0']['message'] . ' id: ' . $token_request_data['data']['0']['details']['id'] : 'Success';
			$error_status = 'Error: ' . $token_request_data['message'] . ' code: ' . $token_request_data['code'] . ' details: '.  json_encode($token_request_data['details']);

			$status = isset($token_request_data['data']) && isset($token_request_data['data']['0']) && "success" === $token_request_data['data']['0']['status'] ? $success_status : $error_status;

			MP_Logs::set_logs($lead, 'zoho', $status );
		}
	}


	/**
	 * Callback function to send lead data from the lead page.
	 *
	 * @access public
	 * @since 1.0.0
	 */
	public function zoho_send_from_lead_page() {

		MP_Callback::check_nonce($_REQUEST['nonce'], MortgagePlatform::$prefix . 'zoho');

		$post_ID = sanitize_text_field($_POST['id']);

		$lead = array(
			'lead' => $post_ID,
			'firstname' => get_post_meta($post_ID, MortgagePlatform::$prefix . 'lead_firstname', true),
			'secondname' => get_post_meta($post_ID,MortgagePlatform::$prefix . 'lead_secondname', true),
			'phone' => get_post_meta($post_ID,MortgagePlatform::$prefix . 'lead_phone', true),
			'email' => get_post_meta($post_ID,MortgagePlatform::$prefix . 'lead_email', true),
		);

		$this->set_lead_data_to_zoho($lead);


		wp_die();

	}



	/**
	 * Send multiple sending to Zoho.
	 * @access public
	 * @since  1.0.0
	 *
	 * @param array $data $_POST
	 */
	public function send_zoho_manually($data) {

		if (isset($data['connector']) && 'zoho' === $data['connector']) {
			$this->send_zoho($data);
		}

	}


	/**
	 * Send multiple sending to Zoho.
	 * @access private
	 * @since  1.0.0
	 *
	 * @param array $data lead IDs
	 */
	private function send_zoho($data){

		unset( $data['connector'] );

		if ( ! empty( $data ) ) {
			$lead = array();
			foreach ( $data as $lead_id ) {
				$data = array(
					"First_Name" => get_post_meta( $lead_id, MortgagePlatform::$prefix . 'lead_firstname', true ),
					"Last_Name" => get_post_meta( $lead_id, MortgagePlatform::$prefix . 'lead_secondname', true ),
					"Company" => MortgagePlatform::$plugin_name,
					"Email" => get_post_meta( $lead_id, MortgagePlatform::$prefix . 'lead_email', true ),
					"Phone" => get_post_meta( $lead_id, MortgagePlatform::$prefix . 'lead_phone', true ),
					"Zip_Code" => get_post_meta( $lead_id, MortgagePlatform::$prefix . 'lead_zipcode', true ),
				);

				array_push($lead, $data);
			}

			/**
			 * Action lead data to Zoho.
			 * @since 1.0.0
			 *
			 * @param array $lead {
			 *   Lead data.
			 *
			 *  @type string 'firstname' lead first name
			 *  @type string 'secondname' lead second name
			 *  @type string 'email' lead email
			 *  @type string 'phone' lead phone
			 *  @type string 'zipcode' lead zip code
			 *  @type string 'yearofbirth' lead year of birth
			 *  @type string 'investmentamount' investment amount
			 *
			 * }
			 */
			do_action('lead_to_zoho',$lead);


			$this->zoho_request( $lead );

			echo esc_html__( 'Ready', 'CalculatorsZohoAddon' );

		} else {
			echo esc_html__( 'No lead selected', 'CalculatorsZohoAddon' );
		}

	}


	/**
	 * Export Lead data to CSV for Zoho.
	 *
	 * @access public
	 * @since 1.0.0
	 *
	 *
	 */
	public function zoho_csv() {

		MP_Callback::check_nonce( $_REQUEST['nonce'], MortgagePlatform::$prefix . 'zoho' );

		unset( $_REQUEST['action'], $_REQUEST['nonce'], $_REQUEST['connector'] );

		$leads = array();
		if ( isset( $_REQUEST ) ) {
			foreach ( $_REQUEST as $key => $value ) {
				$leads[] = array(
					"First_Name" => get_post_meta( $value, MortgagePlatform::$prefix . 'lead_firstname', true ),
					"Last_Name" => get_post_meta( $value, MortgagePlatform::$prefix . 'lead_secondname', true ),
					"Company" => MortgagePlatform::$plugin_name,
					"Email" => get_post_meta( $value, MortgagePlatform::$prefix . 'lead_email', true ),
					"Phone" => get_post_meta( $value, MortgagePlatform::$prefix . 'lead_phone', true ),
					"Zip_Code" => get_post_meta( $value, MortgagePlatform::$prefix . 'lead_zipcode', true ),
				);
			}

			/**
			 * Add data to CSV for export to Zoho.
			 *
			 * @since 1.0.0
			 */
			do_action('export_csv_to_zoho',$leads);

			echo MP_Settings::create_csv( $leads,'zoho_' . date( "Y-m-d" ) . ".csv");


		} else {
			echo esc_html__( 'No lead selected', 'CalculatorsZohoAddon' );
		}

		wp_die();
	}





}

Top ↑

Methods Methods


Top ↑

Changelog Changelog

Changelog
Version Description
1.0.0 Introduced.