Senza categoria

Endpoint EdiSES Oauth2 – Area Riservata

Ambiente di test di auth:
Authorization: https://edisesauth.meetweb.dev/oauth2/authorize
Token: https://edisesauth.meetweb.dev/oauth2/token
Get User Info: https://edisesauth.meetweb.dev/oauth2/userinfo

Client ID: ediseswp_authtest_5423TEST
Client secret: WzfCt2LxqFbpkg2soEmc
Scope: openid
Authorize Endpoint: https://edisesauth.meetweb.dev/oauth2/authorize
Token Endpoint: https://edisesauth.meetweb.dev/oauth2/token
Userinfo Endpoint: https://edisesauth.meetweb.dev/oauth2/userinfo

#######################################################################
 
Gli endpoint dell’ambiente di produzione sono i seguenti:
Authorization: https://auth.edises.it//oauth2/authorize
Token: https://auth.edises.it/oauth2/token
Get User Info: https://auth.edises.it/oauth2/userinfo
 
Qui la documentazione delle specifiche oauth2 https://www.rfc-editor.org/rfc/rfc6749#section-4.

https://areariservataedises.meetweb.dev/purchases-api/doc/

secret JWT 
AJ2pwDCTSamcMR1KxfYSCYrEOXfsioCTWPZcHdzVj6l4t99R3ooOUBYjCqDzmo25T
<?php
/**
 * Plugin Name: Notifica API Area Riservata
 * Plugin URI: https://www.digitalfollowers.com
 * Description: API Notification Area Riservata.
 * Version: 1.3.1
 * Author: Staff - Digital Followers
 * Author URI: https://www.digitalfollowers.com
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Aggiungi il box personalizzato alla pagina dell'ordine
add_action('add_meta_boxes', 'wc_add_generate_api_meetweb');
function wc_add_generate_api_meetweb() {
    add_meta_box(
        'wc_add_generate_api',
        __('API Area Riservata', 'wc-generate-xml'),
        'wc_add_generate_api_meetweb_content',
        'shop_order',
        'side',
        'default'
    );
}

// Callback per il contenuto del box
function wc_add_generate_api_meetweb_content($post) {
    $order_id = $post->ID;
    $api_response = get_post_meta($order_id, '_api_response', true);
    $jwt_payload = get_post_meta($order_id, '_jwt_payload', true);
    ?>
    <button id="notify_api_button" class="button button-primary">Invia Notifica API</button>
    <div id="api_response"><pre><?php echo esc_html($api_response); ?></pre></div>
    <h4>Payload JWT</h4>
    <div style="width:250px;height:auto;overflow:scroll;"><pre id="jwt_payload"><?php echo esc_html($jwt_payload); ?></pre></div>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#notify_api_button').click(function() {
                var orderId = '<?php echo $post->ID; ?>';
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'notify_api',
                        order_id: orderId,
                    },
                    success: function(response) {
                        $('#api_response').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>');
                        $('#jwt_payload').text(response.jwt_payload);
                        location.reload(); // Ricarica la pagina per vedere i dati salvati
                    },
                    error: function(error) {
                        $('#api_response').html('<pre>' + JSON.stringify(error, null, 2) + '</pre>');
                    }
                });
            });
        });
    </script>
    <?php
}

// Gestisci la richiesta AJAX
add_action('wp_ajax_notify_api', 'notify_api_callback');
function notify_api_callback() {
    $order_id = intval($_POST['order_id']);
    $response = notify_purchase_to_external_api($order_id);
    if (!empty($response['jwt_payload'])) {
        update_post_meta($order_id, '_api_response', wp_json_encode($response));
        update_post_meta($order_id, '_jwt_payload', $response['jwt_payload']);
        error_log('Meta updated for order ' . $order_id . ': success');
        
        $order = wc_get_order($order_id);
        $note = 'API Notification Payload: ' . $response['jwt_payload'];
        $order->add_order_note($note);
    } else {
        error_log('JWT payload missing for order ' . $order_id);
    }
    echo wp_json_encode($response);
    wp_die();
}

// Funzione per notificare l'acquisto all'API esterna
function notify_purchase_to_external_api($order_id) {
    $order = wc_get_order($order_id);
    error_log('notify_purchase_to_external_api called for order ' . $order_id); // Debug log
    $products_data = [];
    
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        
        // Ottieni l'ID del libro Magento
        $magentoBookId = get_post_meta($product->get_id(), '_magento_id', true);
        if (!$magentoBookId) {
            $magentoBookId = $product->get_id();
        }
        
        // Ottieni enableResources
        $formato = get_post_meta($product->get_id(), 'formato', true);
        $enableResources = in_array($formato, ['eBook', 'Videocorso completo']);

        $products_data[] = [
            'magentoBookId' => $magentoBookId,
            'enableResources' => $enableResources
        ];
    }

    $payload_details = [
     //   'customerId' => (string) $order->get_user_id(), // Ensure customerId is a string
        'customerId' => "698292", // Ensure customerId is a string
        'customerEmail' => $order->get_billing_email(),
//        'customerEmail' => "fabio@digitalfollowers.com",

        'orderId' => (string) $order->get_id(), // Ensure orderId is a string
        'products' => $products_data
    ];

    $signature = 'AJ2pwDCTSamcMR1KxfYSCYrEOXfsioCTWPZcHdzVj6l4t99R3ooOUBYjCqDzmo25T';
    $jwt = generate_jwt($payload_details, $signature);

    // Esegui la chiamata all'API o log per il test
    $response = [];
    if (!is_test_mode()) {
      
     //   $api_response = wp_remote_post('https://areariservataedises.meetweb.dev/api/notify-purchased-products', [ 
     // meetweb api
        $api_response = wp_remote_post('https://www.digitalfollowers.com/api/endpoint-prodotto.php', [
            'body'    => wp_json_encode(['data' => $jwt]),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($api_response)) {
            $response = ['error' => $api_response->get_error_message(), 'jwt_payload' => $jwt];
        } else {
            $response_body = wp_remote_retrieve_body($api_response);
            error_log('API response body: ' . $response_body); // Log the response body for debugging
            error_log('API response code: ' . wp_remote_retrieve_response_code($api_response)); // Log the response code for debugging
            error_log('API response headers: ' . print_r(wp_remote_retrieve_headers($api_response), true)); // Log the response headers for debugging
            if (wp_remote_retrieve_response_code($api_response) == 200) {
                $response = ['message' => 'Notifica inviata con successo', 'jwt_payload' => $jwt];              
                } else {
                $response_body_decoded = json_decode($response_body, true);
                if (is_array($response_body_decoded)) {
                    $response = array_merge($response_body_decoded, ['jwt_payload' => $jwt]);
                } else {
                    $response = ['error' => 'Invalid response body: ' . $response_body, 'jwt_payload' => $jwt];
                }
            }
        }
    } else {
        // Log the payload for testing
        error_log('Test mode: Payload: ' . wp_json_encode(['data' => $jwt]));
        $response = ['message' => 'Test mode: Payload logged', 'jwt_payload' => $jwt];
    }

    // Aggiorna i metadati dell'ordine
    update_post_meta($order_id, '_api_response', $response['message']);
    update_post_meta($order_id, '_jwt_payload', $response['jwt_payload']);

    $order = wc_get_order($order_id);
    $data = date('d/m/y H:i');
    $note = 'API Notification Payload: ' . 'Data/Ora invio: '. $data .'Payload JWT: ' . $response['jwt_payload'];
    $order->add_order_note($note);
    
    error_log('Meta updated for order ' . $order_id . ': success');
    
    return $response;
}

function generate_jwt($payload, $secret) {
    $header = wp_json_encode(['typ' => 'JWT', 'alg' => 'HS512']);
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(wp_json_encode($payload)));
    $signature = hash_hmac('sha512', $base64UrlHeader . "." . $base64UrlPayload, $secret, true);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
}

function is_test_mode() {
    return false; // Set to false in production
}

// Esegui la notifica automatica quando lo stato dell'ordine viene impostato su "processing"
add_action('woocommerce_order_status_processing', 'notify_purchase_to_external_api');
?>