Jfb action external api

From Lonsdale201/wp-agent-skills · View interactive version

Jfb action external api is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. How to read submitted JetFormBuilder form data from a custom action, transform it (including %macro% replacement of admin-typed templates), call an external HTTP API, write the response back into the form context for downstream actions to use, and dispatch JFB events based on the API outcome. Use wh

How to use this skill

Skill file

JetFormBuilder: action — read form data, call external API, write result back

Most custom JFB actions follow the same data-flow shape: pull values out of the submitted form, optionally interpolate admin-typed templates with %field% macros, hit an external HTTP API, transform the response, write it back into the form context so downstream actions can read it, and (optionally) dispatch a custom JFB event based on the outcome to fan out to conditional follow-up actions.

This skill covers that full lifecycle inside do_action(). It complements jfb-form-action (which covers the action class structure) and jfb-action-events (which covers event dispatch). This one is specifically about the PHP-side data flow — the API surface JFB exposes for read/write/macro/dispatch from inside an action.

API stability note

The jet_fb_context() global (with get_value, update_request, has_field, resolve_request), Tools::sanitize_text_field(), and the Tab_Handler_Manager::instance()->options( $tab_id ) accessor have been stable across JFB 3.x in source observed. The WordPress HTTP API (wp_remote_post, wp_remote_retrieve_body, WP_Error handling) is WP core. The plugin-version-tested value records last end-to-end verification.

When to use this skill

Architecture in one paragraph

JFB exposes the live form submission as a singleton via jet_fb_context(). From inside do_action( array $request, Action_Handler $handler ), the $request parameter is an associative array of field IDs to current values, but the same data is also available through jet_fb_context()->get_value( $field_id ) — and the context is the source of truth: subsequent actions read from it. To write a value back (so downstream actions see it), call jet_fb_context()->update_request( $value, $field_id ). Admin-typed templates with %field% placeholders are interpolated by a small replacer that calls jet_fb_context()->has_field() and get_value(). External API calls go through WordPress's HTTP API (wp_remote_post etc.) with proper timeout, header, and error handling — never file_get_contents or curl_* directly. API credentials come from the plugin's settings tab via Tab_Handler_Manager::instance()->options( $tab_id ). Outcome branching is done by dispatching a custom event through jet_fb_events()->execute( EventClass::class, $form_id ) — this fans out the chain without the action knowing which followups exist.

Step 1 — read the form data

There are two correct ways to read a field's submitted value, with different semantics:

public function do_action( array $request, Action_Handler $handler ) {
    $email = $request['email_field_id'] ?? '';                 // direct from request
    $email = jet_fb_context()->get_value( 'email_field_id' );  // through context
}

Use $request[...] when reading values that won't be changed by previous actions in the chain (most common case — submitted-as-is data).

Use jet_fb_context()->get_value( $field_id ) when:

get_value() returns the current context value (post any updates). $request is the snapshot passed to your do_action. They diverge only when intermediate actions mutate; if you control the chain, both work. If in doubt, prefer the context API — it's the source of truth.

Step 2 — sanitize and validate

Form data has been validated by JFB's field rules but NOT sanitized for your specific output target. Your action is responsible for sanitization that fits how the data leaves your code.

$email = sanitize_email( (string) $email );
if ( ! is_email( $email ) ) {
    throw new Action_Exception(
        __( 'Provided email is not valid.', 'myplugin' )
    );
}

// For text passed to an external API (no HTML expected):
$instructions = sanitize_textarea_field( $this->settings['instructions'] ?? '' );

// For values that act as identifiers (no whitespace, no special chars):
$external_id = Tools::sanitize_text_field( $request['external_id'] ?? '' );

// For numeric IDs:
$user_id = absint( $request['user_id'] ?? 0 );

Tools::sanitize_text_field() is JFB's wrapper that trims plus does the standard sanitize_text_field work. Use it for action settings that the user typed in the editor.

Step 3 — macro replacement (`%field_id%` in admin templates)

A common pattern: the admin types a template like "Hi %first_name%, your order %order_id% is ready" in an action setting, and you substitute the form's actual field values at runtime. The replacer reads jet_fb_context() so it stays in sync with any mutations from upstream actions.

private function replace_macros( string $template ): string {
    if ( false === strpos( $template, '%' ) ) {
        return $template;
    }

    return preg_replace_callback(
        '/%(?P<name>[a-zA-Z0-9\-_]+)%/',
        static function ( $match ) {
            $field = $match['name'];

            if ( ! jet_fb_context()->has_field( $field ) ) {
                return $match[0]; // leave the placeholder as-is
            }

            $value = jet_fb_context()->get_value( $field );

            if ( is_array( $value ) || is_object( $value ) ) {
                $value = wp_json_encode( $value );
            }

            return (string) $value;
        },
        $template
    );
}

Notes:

JFB ships its own macro / preset / dynamic-value subsystems for richer cases (date formatters, computed values, related-post lookups). If your needs grow past simple field substitution, look into jet_fb_dynamic_value() or the macros module instead of expanding this regex.

Step 4 — call the external API (WP HTTP API)

Always use wp_remote_* — never file_get_contents, curl_init, fopen for HTTP. WordPress's HTTP API handles transport selection, proxy config, SSL verify, and timeout consistently across hosts.

private function call_external_api( array $payload ): array {
    $settings = $this->get_api_settings();
    $api_key  = trim( (string) ( $settings['api_key'] ?? '' ) );

    if ( '' === $api_key ) {
        throw new Action_Exception(
            __( 'API key is missing. Configure it in the plugin settings.', 'myplugin' )
        );
    }

    $response = wp_remote_post(
        'https://api.example.com/v1/endpoint',
        array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ),
            'body'    => wp_json_encode( $payload ),
            'timeout' => 30,
        )
    );

    if ( $response instanceof \WP_Error ) {
        throw new Action_Exception(
            sprintf(
                /* translators: %s: HTTP error message */
                __( 'API request failed: %s', 'myplugin' ),
                $response->get_error_message()
            )
        );
    }

    $code = (int) wp_remote_retrieve_response_code( $response );
    $body = (string) wp_remote_retrieve_body( $response );

    if ( $code < 200 || $code >= 300 ) {
        throw new Action_Exception(
            sprintf(
                /* translators: 1: HTTP status code, 2: response body excerpt */
                __( 'API returned %1$d: %2$s', 'myplugin' ),
                $code,
                wp_strip_all_tags( substr( $body, 0, 200 ) )
            )
        );
    }

    $decoded = json_decode( $body, true );
    if ( ! is_array( $decoded ) ) {
        throw new Action_Exception(
            __( 'API returned a non-JSON response.', 'myplugin' )
        );
    }

    return $decoded;
}

Critical points:

For SSRF protection when the URL is admin-configurable (e.g. webhook URLs the user types in), additionally validate the URL host against an allowlist or use the reject_unsafe_urls request arg.

Step 5 — write the result back into form context

When your action produces data that downstream actions should see (e.g. ChatGPT writes its answer into a hidden field, a translation action replaces a value with its translated form), use update_request:

$answer = $api_response['choices'][0]['message']['content'] ?? '';
$answer = sanitize_textarea_field( $answer );

jet_fb_context()->update_request( $answer, $target_field_id );

Key semantics:

If your action ALSO wants to pass non-field metadata to specific downstream actions (e.g. an internal API transaction ID, a calculated score), use $handler->add_context_once( $this->get_id(), [...] ) instead. That's keyed by action type, not exposed as a form field, and accessible via $handler->get_context( $action_type, $key ) in later actions.

Step 6 — dispatch outcome events

Once you have the API result and have written it back, branch the chain by dispatching a custom event. Each branch can have its own followups (different actions wired to different events).

use MyPlugin\Events\ApiSuccessEvent;
use MyPlugin\Events\ApiFailureEvent;

if ( $api_response['ok'] ?? false ) {
    jet_fb_events()->execute( ApiSuccessEvent::class, $handler->get_form_id() );
} else {
    jet_fb_events()->execute( ApiFailureEvent::class, $handler->get_form_id() );
}

Important caveats from observed production usage:

$previous_position = $handler->get_position();

try {
    jet_fb_events()->execute( $event_class, $handler->get_form_id() );
} finally {
    if ( $previous_position ) {
        $handler->set_current_action( $previous_position );
    } else {
        $handler->set_current_action( $this->_id );
    }
}

Step 7 — credentials: read from settings tab, not constants

API keys and similar secrets should live in the plugin's settings tab (admin-managed, stored in wp_options). Don't hardcode, don't ship wp-config.php constants for plugin features — those are for the site owner.

private function get_api_settings(): array {
    $defaults = array(
        'api_key' => '',
        'model'   => 'gpt-4',
        'enable_log' => false,
    );

    return array_merge(
        $defaults,
        Tab_Handler_Manager::instance()->options( 'myplugin-api-tab', array() )
    );
}

Tab_Handler_Manager::instance()->options( $tab_id, $defaults ) reads the JFB settings tab's stored options — see jfb-settings-tab for how to register the tab itself. This pattern keeps the action code agnostic to where the credentials live, and makes it trivial for site admins to rotate keys.

Step 8 — debug logging (gated)

Production actions called from form submissions can flood logs if you log indiscriminately. Gate logs behind a settings flag:

private function should_log(): bool {
    static $enabled = null;
    if ( null !== $enabled ) {
        return $enabled;
    }
    $options = Tab_Handler_Manager::instance()->options( 'myplugin-api-tab', array() );
    $enabled = ! empty( $options['enable_log'] );
    return $enabled;
}

private function log( string $message ): void {
    if ( ! $this->should_log() ) {
        return;
    }
    error_log( '[MyPlugin] ' . $message );
}

The static $enabled cache avoids re-reading options on every log call within one request.

What to log:

What NOT to log:

End-to-end example: complete `do_action()`

/**
 * @throws Action_Exception
 */
public function do_action( array $request, Action_Handler $handler ) {
    // 1. Read settings (template + target field).
    $instructions = sanitize_textarea_field( $this->settings['instructions'] ?? '' );
    $target_field = Tools::sanitize_text_field( $this->settings['fields_map']['answer'] ?? '' );

    if ( '' === $target_field ) {
        throw new Action_Exception(
            __( 'Target field is required.', 'myplugin' )
        );
    }

    // 2. Macro-replace admin templates.
    $prompt = $this->replace_macros( $instructions );

    // 3. Call the API.
    $response = $this->call_external_api( array(
        'prompt' => $prompt,
        'model'  => $this->get_api_settings()['model'],
    ) );

    // 4. Sanitize + write the result back into form context.
    $answer = sanitize_textarea_field( $response['answer'] ?? '' );
    jet_fb_context()->update_request( $answer, $target_field );

    // 5. Dispatch outcome event.
    $previous_position = $handler->get_position();
    try {
        $event_class = ( $response['decision'] ?? false )
            ? \MyPlugin\Events\DecisionTrueEvent::class
            : \MyPlugin\Events\DecisionFalseEvent::class;

        jet_fb_events()->execute( $event_class, $handler->get_form_id() );
    } finally {
        if ( $previous_position ) {
            $handler->set_current_action( $previous_position );
        } else {
            $handler->set_current_action( $this->_id );
        }
    }
}

This shape — settings → macro → API → context write → event dispatch — covers the vast majority of integration actions. Most of the implementation effort is steering the API specifics; the JFB-side glue is constant.

Critical rules

Common pitfalls (failure modes inferred from the API contract)

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.