__( 'Hubspot CRM', 'advanced-form-integration' ), 'tasks' => array( 'add_contact' => __( 'Create New Contact', 'advanced-form-integration' ) ) ); return $actions; } add_filter( 'adfoin_settings_tabs', 'adfoin_hubspot_settings_tab', 10, 1 ); function adfoin_hubspot_settings_tab( $providers ) { $providers['hubspot'] = __( 'Hubspot CRM', 'advanced-form-integration' ); return $providers; } add_action( 'adfoin_settings_view', 'adfoin_hubspot_settings_view', 10, 1 ); function adfoin_hubspot_settings_view( $current_tab ) { if( $current_tab != 'hubspot' ) { return; } if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) { require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php'; } $fields = array( array( 'name' => 'tokenType', 'label' => __( 'Token Type', 'advanced-form-integration' ), 'type' => 'select', 'required' => true, // Existing accounts predate this field; the table and the edit // modal fall back to this value when nothing is stored. 'default' => 'service_key', 'options' => array( 'service_key' => __( 'Service Key (recommended)', 'advanced-form-integration' ), 'private_app' => __( 'Private App (legacy)', 'advanced-form-integration' ), ), 'description' => __( 'HubSpot issues the same kind of Bearer token either way. This only records which flow you used, so the setup steps and support answers match your account.', 'advanced-form-integration' ), 'show_in_table' => true ), array( 'name' => 'accessToken', 'label' => __( 'Access Token', 'advanced-form-integration' ), 'type' => 'text', 'required' => true, 'mask' => true, 'placeholder' => __( 'Enter your Access Token', 'advanced-form-integration' ), 'show_in_table' => true ) ); $instructions = sprintf( '
%s
' . '%s
%s
%s
', __( 'HubSpot offers two ways to create this token. Both work here, so pick either one.', 'advanced-form-integration' ), __( 'Option 1: Service Key (recommended)', 'advanced-form-integration' ), __( 'In HubSpot, go to Settings > Integrations > Service Keys.', 'advanced-form-integration' ), __( 'Click Create service key and give it a name.', 'advanced-form-integration' ), __( 'Select the scopes you need: Contacts read and write, plus Companies, Deals, Tickets or Custom Objects if you map to them.', 'advanced-form-integration' ), __( 'Click Create, then copy the token and paste it below.', 'advanced-form-integration' ), __( 'Option 2: Private App (legacy)', 'advanced-form-integration' ), __( 'In HubSpot, go to Settings > Integrations > Private Apps.', 'advanced-form-integration' ), __( 'Click Create a private app and give it a name.', 'advanced-form-integration' ), __( 'Open the Scopes tab and select the same scopes listed above.', 'advanced-form-integration' ), __( 'Click Create app, then Show token and copy it below.', 'advanced-form-integration' ), __( 'Private apps still work and HubSpot has not announced a shutdown date, but they no longer get new features. Service Keys are the replacement and are currently in public beta. The token works the same way in both cases, so you can switch later by pasting a new token here.', 'advanced-form-integration' ) ); ADFOIN_Account_Manager::render_settings_view( 'hubspot', __( 'HubSpot CRM', 'advanced-form-integration' ), $fields, $instructions ); } add_action( 'wp_ajax_adfoin_get_hubspot_credentials', 'adfoin_get_hubspot_credentials', 10, 0 ); /* * Get HubSpot credentials */ function adfoin_get_hubspot_credentials() { if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) { require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php'; } ADFOIN_Account_Manager::ajax_get_credentials_list( 'hubspot' ); } add_action( 'wp_ajax_adfoin_save_hubspot_credentials', 'adfoin_save_hubspot_credentials', 10, 0 ); /* * Save HubSpot credentials */ function adfoin_save_hubspot_credentials() { if ( ! class_exists( 'ADFOIN_Account_Manager' ) ) { require_once plugin_dir_path( __FILE__ ) . '../../includes/class-adfoin-account-manager.php'; } ADFOIN_Account_Manager::ajax_save_credentials( 'hubspot', array( 'accessToken' => 'token', 'tokenType' => 'select', ) ); } /* * HubSpot Credentials List */ function adfoin_hubspot_get_credentials_list() { $credentials = adfoin_read_credentials( 'hubspot' ); foreach ($credentials as $option) { printf('', esc_attr($option['id']), esc_html($option['title'])); } } // Legacy single-account import: surfaces old `adfoin_hubspot_*` options // as a Legacy Account record when the new credentials store is empty. add_action( 'plugins_loaded', function() { if ( class_exists( 'ADFOIN_Account_Manager' ) ) { ADFOIN_Account_Manager::register_legacy_option_importer( 'hubspot', array( 'accessToken' => array( 'adfoin_hubspot_access_token', 'adfoin_hubspot_api_token' ), ) ); } }, 20 ); /* * One-time backfill: accounts created before the Token Type field existed were * all made with private apps, so label them that way instead of letting the * 'service_key' default misreport them. */ add_action( 'admin_init', 'adfoin_hubspot_backfill_token_type', 20 ); function adfoin_hubspot_backfill_token_type() { if ( get_option( 'adfoin_hubspot_token_type_backfilled' ) ) { return; } $all = (array) maybe_unserialize( get_option( 'adfoin_credentials', array() ) ); if ( ! empty( $all['hubspot'] ) && is_array( $all['hubspot'] ) ) { $changed = false; foreach ( $all['hubspot'] as &$cred ) { if ( ! is_array( $cred ) ) { continue; } if ( empty( $cred['tokenType'] ) && empty( $cred['token_type'] ) ) { $cred['tokenType'] = 'private_app'; $changed = true; } } unset( $cred ); if ( $changed ) { update_option( 'adfoin_credentials', $all ); } } update_option( 'adfoin_hubspot_token_type_backfilled', 1 ); } // Deprecated - kept for backward compatibility add_action( 'admin_post_adfoin_save_hubspot_access_token', 'adfoin_save_hubspot_access_token', 10, 0 ); function adfoin_save_hubspot_access_token() { // Security Check // Authorization check adfoin_require_manage_options(); if (! wp_verify_nonce( $_POST['_nonce'], 'adfoin_hubspot_settings' ) ) { die( __( 'Security check Failed', 'advanced-form-integration' ) ); } $access_token = sanitize_text_field( wp_unslash( $_POST["adfoin_hubspot_access_token"] ) ); // Save tokens update_option( "adfoin_hubspot_access_token", $access_token ); advanced_form_integration_redirect( "admin.php?page=advanced-form-integration-settings&tab=hubspot" ); } add_action( 'adfoin_add_js_fields', 'adfoin_hubspot_js_fields', 10, 1 ); function adfoin_hubspot_js_fields( $field_data ) {} add_action( 'adfoin_action_fields', 'adfoin_hubspot_action_fields', 10, 1 ); function adfoin_hubspot_action_fields() { ?> HubSpot.', 'advanced-form-integration' ) ); if( $record ) { adfoin_add_to_log( $error, $endpoint, array( 'method' => $method, 'body' => $data ), $record ); } return $error; } $args = array( 'method' => $method, 'timeout' => 30, 'headers' => array( 'Content-Type' => 'application/json' ) ); $base_url = 'https://api.hubapi.com/crm/v3/'; $url = $base_url . $endpoint; $args['headers']['Authorization'] = 'Bearer ' . $access_token; if( 'POST' == $method || 'PUT' == $method || 'PATCH' == $method ) { $args['body'] = wp_json_encode( $data ); } $response = wp_remote_request( $url, $args ); // Retry on 429 (rate limited), honouring Retry-After, bounded to 2 retries. // HubSpot enforces strict per-second/burst limits; high-volume forms hit // them and previously failed with no retry. if ( ! is_wp_error( $response ) && 429 == (int) wp_remote_retrieve_response_code( $response ) && $retry_count < 2 ) { $retry_after = wp_remote_retrieve_header( $response, 'retry-after' ); $delay = $retry_after ? min( (int) $retry_after, 10 ) : ( $retry_count + 1 ) * 2; sleep( $delay ); return adfoin_hubspot_request( $endpoint, $method, $data, $record, $cred_id, $retry_count + 1 ); } if( $record ) { adfoin_add_to_log( adfoin_hubspot_readable_response( $response ), $url, $args, $record ); } return $response; } /* * Copy of the response for the log, with HubSpot's error message instead of * "Bad Request". */ function adfoin_hubspot_readable_response( $response, $note = '' ) { if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); if ( $code >= 300 ) { $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! empty( $body['message'] ) ) { $response['response']['message'] = $body['message']; } } elseif ( $note ) { $response['response']['message'] = sprintf( 'OK (%s)', $note ); } return $response; } /* * Mapped values without empty ones, keeping 0 and "0". */ function adfoin_hubspot_filter_properties( $properties ) { return array_filter( $properties, function ( $value ) { return null !== $value && '' !== $value && array() !== $value; } ); } add_action( 'wp_ajax_adfoin_get_hubspot_contact_fields', 'adfoin_get_hubspot_contact_fields', 10, 0 ); /* * Get HubSpot Contact Fields */ function adfoin_get_hubspot_contact_fields() { // Security Check if (! wp_verify_nonce( $_POST['_nonce'], 'advanced-form-integration' ) ) { die( __( 'Security check Failed', 'advanced-form-integration' ) ); } $cred_id = isset( $_POST['credId'] ) ? sanitize_text_field( wp_unslash( $_POST['credId'] ) ) : ''; $contact_fields = array(); $data = adfoin_hubspot_request( 'properties/contacts', 'GET', array(), array(), $cred_id ); if( is_wp_error( $data ) ) { wp_send_json_error(); } $body = json_decode( wp_remote_retrieve_body( $data ) ); if( isset( $body->results ) && is_array( $body->results ) ) { foreach( $body->results as $single ) { if( false == $single->modificationMetadata->readOnlyValue ) { $description = $single->description; // Tell the user the expected date format so a locale string like // DD/MM/YYYY (which HubSpot mis-parses) isn't mapped to a date // property by mistake. if( isset( $single->type ) && 'date' == $single->type ) { $description .= ' ' . __( '(Date — use YYYY-MM-DD)', 'advanced-form-integration' ); } elseif( isset( $single->type ) && 'datetime' == $single->type ) { $description .= ' ' . __( '(Date & time — ISO 8601, e.g. 2026-12-25T10:00:00Z)', 'advanced-form-integration' ); } if( $single->options ) { if( is_array( $single->options ) ) { $description .= " Possible values are: "; $values = wp_list_pluck( $single->options, 'value' ); $description .= implode( ' | ', $values ); } } array_push( $contact_fields, array( 'key' => $single->name, 'value' => $single->label, 'description' => $description ) ); } } } wp_send_json_success( $contact_fields ); } add_action( 'adfoin_hubspot_job_queue', 'adfoin_hubspot_job_queue', 10, 1 ); function adfoin_hubspot_job_queue( $data ) { adfoin_hubspot_send_data( $data['record'], $data['posted_data'] ); } /* * Handles sending data to Hubspot API */ function adfoin_hubspot_send_data( $record, $posted_data ) { $record_data = json_decode( $record["data"], true ); if ( adfoin_check_conditional_logic( $record_data['action_data']['cl'] ?? array(), $posted_data ) ) { return; } $data = $record_data["field_data"]; $cred_id = isset( $data['credId'] ) ? $data['credId'] : ''; $task = $record["task"]; // Backward compatibility: if no cred_id, use first available credential if( empty( $cred_id ) ) { $all_credentials = adfoin_read_credentials( 'hubspot' ); if( !empty( $all_credentials ) ) { $cred_id = $all_credentials[0]['id']; } } // Suppress a duplicate fire of the same submission (form auto-save, a // double-clicked submit, or a hook firing twice) within a short window. if ( adfoin_hubspot_is_duplicate_submission( $record, $posted_data ) ) { adfoin_hubspot_log_duplicate( $record ); return; } if( $task == "add_contact" ) { $holder = array(); if( $data ) { foreach( $data as $key => $value ) { // Skip credId - it's for internal use only, not a HubSpot property if( $key === 'credId' ) { continue; } $holder[$key] = adfoin_get_parsed_values( adfoin_hubspot_unescape_template( $value ), $posted_data ); } } $response = adfoin_hubspot_upsert_contact( $holder, $record, $cred_id ); } return; } /** * Create or update a contact atomically by email using the v3 batch upsert * (idProperty=email). This replaces the previous search-then-create/PATCH flow, * which raced because HubSpot's search index is eventually consistent — a rapid * re-submit (auto-save, retry) could search-miss the just-created contact and * then 409, or duplicate. With no email to dedupe on, fall back to a plain create. */ function adfoin_hubspot_upsert_contact( $holder, $record, $cred_id ) { $email = isset( $holder['email'] ) ? $holder['email'] : ''; $properties = adfoin_hubspot_filter_properties( $holder ); if ( $email ) { $body = array( 'inputs' => array( array( 'idProperty' => 'email', 'id' => $email, 'properties' => $properties, ), ), ); return adfoin_hubspot_request( 'objects/contacts/batch/upsert', 'POST', $body, $record, $cred_id ); } // No email to match on: HubSpot creates a new contact every time. $response = adfoin_hubspot_request( 'objects/contacts', 'POST', array( 'properties' => $properties ), array(), $cred_id ); adfoin_add_to_log( adfoin_hubspot_readable_response( $response, __( 'no email mapped: a new contact is created each time', 'advanced-form-integration' ) ), 'https://api.hubapi.com/crm/v3/objects/contacts', array( 'method' => 'POST', 'body' => array( 'properties' => $properties ) ), $record ); return $response; } function adfoin_hubspot_log_duplicate( $record ) { adfoin_add_to_log( new WP_Error( 'hubspot_duplicate', __( 'Not sent: the same submission was already sent to HubSpot less than 2 minutes ago.', 'advanced-form-integration' ) ), '', array(), $record ); } /** * Idempotency guard for HubSpot submissions. Returns true when an identical * submission for the same integration was seen within the window. Backed by an * atomic add_option lock (UNIQUE option_name), so concurrent jobs are handled. * Filterable via `adfoin_hubspot_dedupe`. */ function adfoin_hubspot_is_duplicate_submission( $record, $posted_data ) { if ( ! apply_filters( 'adfoin_hubspot_dedupe', true, $record, $posted_data ) ) { return false; } $id = isset( $record['id'] ) ? (string) $record['id'] : ''; if ( '' === $id ) { return false; } $key = 'adfoin_hsdup_' . md5( $id . '|' . wp_json_encode( $posted_data ) ); $now = time(); $ttl = 120; // The locks are options (for an atomic add); remove expired ones now and // then so they don't pile up in wp_options. if ( 1 === wp_rand( 1, 20 ) ) { global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d", $wpdb->esc_like( 'adfoin_hsdup_' ) . '%', $now ) ); } if ( add_option( $key, (string) ( $now + $ttl ), '', 'no' ) ) { return false; // first time — not a duplicate } $expires = (int) get_option( $key, 0 ); if ( $expires > 0 && $now > $expires ) { update_option( $key, (string) ( $now + $ttl ), 'no' ); return false; // stale lock taken over } return true; // identical submission within the window } function adfoin_hubspot_contact_exists( $email, $cred_id = '' ) { $data = array( 'filterGroups' => array( array( 'filters' => array( array( 'value' => $email, 'propertyName' => 'email', 'operator' => 'EQ' ) ) ) ) ); $result = adfoin_hubspot_request( 'objects/contacts/search', 'POST', $data, array(), $cred_id ); if( 200 == wp_remote_retrieve_response_code( $result ) ) { $body = json_decode( wp_remote_retrieve_body( $result ), true ); if( isset( $body['total'], $body['results'][0]['id'] ) && $body['total'] > 0 ) { return $body['results'][0]['id']; } } return false; }