How get JSON from external API on every page load if not existing in transient?

Question

I need to collect data from an external API and import/populate it to my custom post type “Agent”. On the one hand there is a need for checking if any updates have occured to anyone of the agents or if there are new ones (on the API side). Checking this against transients on each page load will do just fine, though I have never worked with transients before.

On the other hand I really(!) need to forward and echo online/offline statuses “on the fly” if it’s at all possible using WP.

The code down below works when performing a manual request in the browser (note that actual urls are replaced with dummy ones). However I need it to actually work on its own, automatically but haven’t yet succeeded. I tried wrapping it all inside an action hook (after_setup_theme) but it didn’t work.

<?php

  add_action('wp_ajax_nopriv_get_all_agents_from_api', 'get_all_agents_from_api');
  add_action('wp_ajax_get_all_agents_from_api', 'get_all_agents_from_api');
  add_action('wp_ajax_nopriv_update_agents_on_api', 'update_agents_on_api');
  add_action('wp_ajax_update_agents_on_api', 'update_agents_on_api');

function get_all_agents_from_api() {

    $file = get_stylesheet_directory() . '/agentData.txt';
    $profiles = [];

    $username="xxxxx.xxxxxxx@xxxxxxxx.com";
    $password = 'tJ75F9tG&QISC#$2t';

    $args = array(
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
        )
    );
    // Get a list of our local agents to avoid duplicates
    $local = wp_remote_retrieve_body(wp_remote_get(get_site_url(null, '/wp-json/wp/v2/agents')));
    $local = json_decode($local, true);
    $localagents=Array();
    foreach($local as $agent)
    {
      $localagents[]=$agent['slug']; // Not the best ID, but good enough for now
    }

    $results = wp_remote_retrieve_body(wp_remote_get('https://api.somefancyurl.com/mockupagents/v1/Agents', $args));
    file_put_contents($file, "Current Page: 1\n\n", FILE_APPEND);

    // JSON decode the response
    $results = json_decode($results);

    if(!is_array($results) || empty($results)) {
        return false;
    }

    foreach($results as $agent)
    {
        foreach($agent->profiles as $profile) {

            $profile_slug = sanitize_title($profile->profileName . '-' . $profile->profileId);
            if(in_array($profile_slug, $localagents)){continue;} // Already got it

            $inserted_profile = wp_insert_post([
                'post_name' => $profile_slug,
                'post_title' => $profile->profileName,
                'post_content' => '',
                'post_type' => 'agent',
                'post_status' => 'publish'
            ], $wp_error=true);

            if(is_wp_error($inserted_profile)) {
                continue;
            }

            // Added to profile_data: agentId, agent_status_available, agent_status_inCall and agent_status_loggedOut.
            $profile_data = [
                'field_6295da4e335b1' => 'profileId',
                'field_6297663deba92' => 'agentId',
                'field_62447e691eb7f' => 'profileName',
                'field_62447e8e1eb80' => 'serviceName',
                'field_629617a81de38' => 'accessNumber',
                'field_624c212c894e0' => 'serviceId',
                'field_62c2f62c8e9b2' => 'agent_status_available',
                'field_62c2f6848e9b3' => 'agent_status_inCall',
                'field_62c2f6b58e9b4' => 'agent_status_loggedOut'
            ];

            foreach($profile_data as $key => $profileName) {
                update_field($key, $profile->$profileName, $inserted_profile);
            }
            update_field('field_6245952692451', $agent->notes, $inserted_profile);

        }

    }

}

function idtrim($url)
{
  $slash=strrpos($url, "https://wordpress.stackexchange.com/");
  return substr($url, $slash+1);
}

function update_agents_on_api() {
  // Set up RPC auth
  $username="xxxxx.xxxxxxx@xxxxxxxx.com";
  $password = 'tJ75F9tG&QISC#$2t';

  $patchargs = array(
    'method' => 'PATCH',
    'headers' => array(
      'Authorization'=>'Basic '.base64_encode($username.':'.$password),
      'Content-type'=>'application/json'
    )
  );
  $args = array(
    'headers' => array(
      'Authorization'=>'Basic '.base64_encode($username.':'.$password),
      'Content-type'=>'application/json'
    )
  );
  // Get our current list of remote agents to check if we should create or update
  $results=wp_remote_retrieve_body(wp_remote_get('https://api.somefancyurl.com/mockupagents/v1/Agents', $args));
  $results=json_decode($results, true);
  $remoteagents=Array();
  foreach($results as $agent)
  {
    if(!isset($agent['profiles'][0])){continue;} // No profile=no name to turn into a slug
    $profile=$agent['profiles'][0];
    $slug=sanitize_title($profile['profileName']);//.'-'.$profile['profileId']);
    $remoteagents[$slug]=Array($agent['agentId'], $agent['profiles'][0]['profileId']);
  }
  // Get a list of our local agents
  $local=wp_remote_retrieve_body(wp_remote_get(get_site_url(null, '/wp-json/wp/v2/agents')));
  $local=json_decode($local, true);
  $localagents=Array();
  foreach($local as $agent)
  {
    $names=explode(' ', $agent['title']['rendered']);
    $agentinfo=Array(
      'agentName'=>$agent['title']['rendered'],
      'notes'=>htmlentities($agent['acf']['about_advisor']),
      'agentNumber'=>$agent['id'],
      'phoneNumber'=>'37907107795',
      'pin'=>$agent['id'],
      );
    $profileinfo=Array();
    if(!isset($remoteagents[$agent['slug']]))
    { // Agent doesn't exist yet, create it
//print('Creating '.$agent['title']['rendered'].' because $remoteagents['.$agent['slug'].'] is undefined<br />');
      $profileinfo['profileName']=$agent['slug'];//htmlentities($agent['acf']['screen_name']);
      $profileinfo['profileNumber']=random_int(1,999);
      $profileinfo['serviceId']=427;//random_int(1,999);
      $args['body']=json_encode($agentinfo);
      $r=wp_remote_post('https://api.somefancyurl.com/mockupagents/v1/Agents', $args);
      if(substr($r['response']['code'],0,1)!='2' && substr($r['response']['code'],0,1)!='3'){print(1);break;}
      // Profile
      $profileinfo['agentId']=idtrim($r['headers']['location']);
      if(!$profileinfo['agentId']){continue;} // Invalid
      $args['body']=json_encode($profileinfo);
      $r=wp_remote_post('https://api.somefancyurl.com/mockupagents/v1/Profiles', $args);
      if(substr($r['response']['code'],0,1)!='2' && substr($r['response']['code'],0,1)!='3'){print(2);break;}
    }else{
      // Update agent
      $id=$remoteagents[$agent['slug']][0];
      $profileinfo['agentId']=$id;
      $patchargs['method']='PUT';
      $patchargs['body']=json_encode($agentinfo);
      $r=wp_remote_request('https://api.somefancyurl.com/mockupagents/v1/Agents'.$id, $patchargs);
      if(substr($r['response']['code'],0,1)!='2' && substr($r['response']['code'],0,1)!='3'){print(3);break;}
      // Profile
      $id=$remoteagents[$agent['slug']][1];
      $patchargs['method']='PATCH';
      $patchargs['body']=json_encode($profileinfo);
      $r=wp_remote_request('https://api.somefancyurl.com/mockupagents/v1/Profiles/'.$id, $patchargs);
      if(substr($r['response']['code'],0,1)!='2' && substr($r['response']['code'],0,1)!='3'){print(4);break;}
    }
  }
}

If anyone could please help me solve this I will be forever grateful!
//Seb

0
Seblito 2 weeks 2022-08-05T07:33:20-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse