php - How to pass a data array from one hooked function to another in WooCommerce

one text

Solution:

You can simply set your array in a custom WC_Session variable, that you will be able to use afterwards like:

$data_verif = array(
    "refs"         =>  array(
        "country"  => $billingcountry,
    ),
    "settings"     =>  array(
        "language" => $cur_lang
    ),
    "policyholder" =>  array(
        "firstName"  => $fields['billing_first_name'] ,
        "lastName"   => $fields['billing_last_name'],
        "email"      => $fields['billing_email'],
        "phone"      => $fields['billing_phone'],
        "birthdate"  => $fields['insurance-birthdate'],
        "gender"     => $fields['gender-selection' ],
        "address"    =>  array(
            "country"  => $billingcountry,
            "zip"      => $fields['billing_postcode'],
            "city"     => $fields['billing_city'],
            "street"   => $fields['billing_address_1'],
            "number"   => $fields['billing_address_2'],
            "box"      => "box"
        ),
        "entityType" => "ENTITY_TYPE_PERSON"
    ), 
    "risk"         => array(
         "model"            => $_product -> get_title(),
         "originalValue"    =>  $_product -> get_price() * 100,
         "antiTheftMeasure" => "ANTI_THEFT_MEASURE_NONE",
    ),
    "terms"        => array(
        "depreciation" => false
    ),
);

// Set the array to a custom WC_Session variable (to be used afterwards)
WC()->session->set('data_verif', $data_verif);

// API CALL HERE AND CHECK WHETHER VALID OR NOT

Then you will be able to call that array in woocommerce_payment_complete hooked function using:

$data_verif = WC()->session->get('data_verif');

This should work.


Now is better to remove (delete) this custom session variable once you have finished to use it… You can do it using the __unset() method like:

WC()->session->__unset('data_verif');

So in your 2nd hooked function:

//After payment is completed
add_action( 'woocommerce_payment_complete', 'apicall_create' );
function apicall_create() {
    // Get the data array
    WC()->session->get('data_verif');

    // Do the API CALL HERE
    
    // Remove the session variable
    WC()->session->__unset('data_verif');
}

Source