Файловый менеджер - Редактировать - /var/www/vhosts/klarna.dev1.mndrn.cloud/klarna_api_test.php
Назад
<?php /** * Test di interazione con le API Klarna * Compatibile con PHP 5.6 e versioni successive * Nessuna dipendenza esterna */ // Abilita la visualizzazione degli errori per il debug error_reporting(E_ALL); ini_set('display_errors', 1); // Inizia la sessione se non è già attiva if (session_status() === PHP_SESSION_NONE || !isset($_SESSION)) { session_start(); } // Funzione per visualizzare i dati in modo leggibile function prettyPrint($data) { echo '<pre>'; print_r($data); echo '</pre>'; } // Funzione per il debug function debug($message, $data = null) { echo '<div style="background-color: #f8d7da; color: #721c24; padding: 10px; margin: 10px 0; border-radius: 5px;">'; echo '<h3>Debug:</h3>'; echo '<p>' . $message . '</p>'; if ($data !== null) { echo '<pre>'; print_r($data); echo '</pre>'; } echo '</div>'; } /** * Classe per l'interazione con le API Klarna */ class KlarnaAPI { // Klarna API credentials private $username; private $password; private $api_base_url; private $is_test_mode = true; /** * Constructor - initialize with credentials */ public function __construct() { // Test mode credentials if ($this->is_test_mode) { $this->username = '119a6338-f9b1-4445-880b-6b60fdff2fd5'; // Klarna playground username $this->password = 'klarna_test_api_OSopNiNXdTRUP0hsbVBrWGY1T3ZManVjb0cxUihpMDksMTE5YTYzMzgtZjliMS00NDQ1LTg4MGItNmI2MGZkZmYyZmQ1LDEsTm5VeEhBVWJQdFNxd2lId1dtaW9IdENZWE55MUJPRHVPYzZwb2JFM0FZRT0'; // Klarna playground password $this->api_base_url = 'https://api.playground.klarna.com'; } else { // Production credentials $this->username = ''; // Replace with your production username $this->password = ''; // Replace with your production password $this->api_base_url = 'https://api.klarna.com'; } } /** * Create a new Klarna payment session * * @param array $order_data Order information * @param string $locale Locale (e.g., 'it-IT', 'en-US') * @return array Session data or error */ public function createSession($order_data, $locale = 'it-IT') { $url = $this->api_base_url . '/payments/v1/sessions'; // Make API request $response = $this->makeApiRequest('POST', $url, $order_data); return $response; } /** * Create an order based on an authorized token * * @param string $authorization_token Authorization token from Klarna * @param array $order_data Order information * @return array Order data or error */ public function createOrder($authorization_token, $order_data) { $url = $this->api_base_url . '/payments/v1/authorizations/' . $authorization_token . '/order'; // Make API request $response = $this->makeApiRequest('POST', $url, $order_data); return $response; } /** * Get order details * * @param string $order_id Klarna order ID * @return array Order details or error */ public function getOrder($order_id) { $url = $this->api_base_url . '/ordermanagement/v1/orders/' . $order_id; // Make API request $response = $this->makeApiRequest('GET', $url); return $response; } /** * Make an API request to Klarna * * @param string $method HTTP method (GET, POST, etc.) * @param string $url API endpoint URL * @param array $data Request data * @return array Response data */ private function makeApiRequest($method, $url, $data = null) { // Verifica che cURL sia disponibile if (!function_exists('curl_init')) { return ['error' => 'CURL non è disponibile su questo server']; } $ch = curl_init(); // Set basic cURL options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', ]); // Set method-specific options if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); if ($data) { $json_data = json_encode($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); } } else if ($method === 'PUT') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); if ($data) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } } else if ($method === 'GET') { // GET is default } // Aggiungiamo opzioni per il debug curl_setopt($ch, CURLOPT_VERBOSE, true); $verbose = fopen('php://temp', 'w+'); curl_setopt($ch, CURLOPT_STDERR, $verbose); // Imposta il timeout a 30 secondi curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Disabilita la verifica SSL per test (rimuovere in produzione) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Execute request $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Log verbose info rewind($verbose); $verboseLog = stream_get_contents($verbose); // Handle errors if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); return ['error' => $error, 'verbose' => $verboseLog]; } curl_close($ch); // Parse response $responseData = json_decode($response, true); // Add HTTP status code to response if (is_array($responseData)) { $responseData['http_code'] = $httpCode; $responseData['verbose'] = $verboseLog; } else { $responseData = [ 'http_code' => $httpCode, 'raw_response' => $response, 'verbose' => $verboseLog ]; } return $responseData; } } // Gestisci diverse azioni in base al parametro 'action' $action = isset($_GET['action']) ? $_GET['action'] : 'form'; // Log dell'azione corrente per debug debug('Azione corrente', $action); // Crea un'istanza della classe KlarnaAPI $klarna = new KlarnaAPI(); switch ($action) { case 'create_session': try { // Crea i dati dell'ordine per Klarna $order_data = [ 'purchase_country' => 'IT', 'purchase_currency' => 'EUR', 'locale' => 'it-IT', 'order_amount' => 9999, // 99.99 EUR in centesimi 'order_tax_amount' => 1803, // 22% VAT di 9999 centesimi, arrotondato 'order_lines' => [ [ 'name' => 'Prodotto Test', 'quantity' => 1, 'unit_price' => 9999, 'tax_rate' => 2200, // 22% in basis points 'total_amount' => 9999, 'total_tax_amount' => 1803 ] ], 'merchant_urls' => [ 'confirmation' => 'https://example.com/confirmation', 'notification' => 'https://example.com/notification' ], 'billing_address' => [ 'given_name' => 'Nome', 'family_name' => 'Cognome', 'email' => 'test@example.com', 'phone' => '1234567890', 'street_address' => 'Via Test 123', 'city' => 'Milano', 'postal_code' => '20100', 'country' => 'IT' ] ]; debug('Dati ordine di test', $order_data); // Crea una sessione Klarna $result = $klarna->createSession($order_data); debug('Risposta API Klarna', $result); // Salva l'ID della sessione in una variabile di sessione per uso futuro $_SESSION['klarna_session_id'] = isset($result['session_id']) ? $result['session_id'] : ''; $_SESSION['klarna_client_token'] = isset($result['client_token']) ? $result['client_token'] : ''; echo '<h1>Risultato della creazione della sessione Klarna</h1>'; prettyPrint($result); // Se la sessione è stata creata con successo, mostra un link per continuare if (isset($result['session_id'])) { echo '<h2>Sessione creata con successo!</h2>'; echo '<p>ID Sessione: ' . $result['session_id'] . '</p>'; echo '<a href="klarna_api_test.php?action=payment_page" class="btn btn-primary">Vai alla pagina di pagamento</a>'; } else { echo '<h2>Errore nella creazione della sessione</h2>'; echo '<a href="klarna_api_test.php" class="btn btn-danger">Torna indietro</a>'; } } catch (Exception $e) { debug('Errore durante la creazione della sessione', $e->getMessage()); echo '<h2>Errore nella creazione della sessione</h2>'; echo '<a href="klarna_api_test.php" class="btn btn-danger">Torna indietro</a>'; } break; case 'payment_page': // Verifica che esista un ID sessione if (empty($_SESSION['klarna_client_token'])) { echo '<h1>Errore</h1>'; echo '<p>Nessun token client Klarna trovato. <a href="klarna_api_test.php">Torna indietro</a> e crea una nuova sessione.</p>'; break; } // Debug del token client debug('Client token Klarna', $_SESSION['klarna_client_token']); // Mostra la pagina di pagamento con il widget Klarna ?> <!DOCTYPE html> <html> <head> <title>Test Pagamento Klarna</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 20px; color: #333; } .container { max-width: 800px; margin: 0 auto; background: #fff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h1, h2, h3, h4 { color: #2c3e50; } .card { border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; } .card-header { background-color: #3498db; color: white; padding: 10px 15px; border-top-left-radius: 5px; border-top-right-radius: 5px; } .card-body { padding: 15px; } .btn { display: inline-block; background: #3498db; color: #fff; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; font-size: 16px; margin-top: 10px; } .btn-primary { background: #3498db; } .btn-success { background: #2ecc71; } .btn-danger { background: #e74c3c; } .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert-success { color: #155724; background-color: #d4edda; border-color: #c3e6cb; } hr { border: 0; border-top: 1px solid #eee; margin: 20px 0; } </style> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <div class="container"> <div class="card"> <div class="card-header"> <h3>Test Pagamento Klarna</h3> </div> <div class="card-body"> <h4>Riepilogo Ordine</h4> <p>Prodotto Test: €99.99</p> <p><strong>Totale: €99.99</strong></p> <hr> <h4>Pagamento con Klarna</h4> <div id="klarna_container"></div> <div id="payment-success" style="display: none;" class="alert alert-success"> Pagamento autorizzato con successo! <a href="klarna_api_test.php?action=create_order" class="btn btn-success">Completa l'ordine</a> </div> </div> </div> </div> <!-- Klarna Payments JS --> <script src="https://x.klarnacdn.net/kp/lib/v1/api.js"></script> <script> // Funzione per il debug in console function consoleDebug(title, data) { console.log('==== ' + title + ' ===='); console.log(data); console.log('=================='); } $(document).ready(function() { consoleDebug('Client token', '<?php echo $_SESSION['klarna_client_token']; ?>'); try { // Inizializza Klarna Payments Klarna.Payments.init({ client_token: '<?php echo $_SESSION['klarna_client_token']; ?>', instance_id: 'klarna-payments-instance' // Aggiungiamo l'instance_id richiesto }); consoleDebug('Klarna.Payments.init completato', 'success'); // Carica il widget di pagamento Klarna.Payments.load({ container: '#klarna_container', instance_id: 'klarna-payments-instance', // Aggiungiamo l'instance_id richiesto payment_method_categories: ['pay_later', 'pay_now', 'pay_over_time'] }, function(res) { consoleDebug('Load result', res); // Aggiungi messaggio di debug visibile if (res.error) { $('#klarna_container').html('<div style="color: red; padding: 10px; border: 1px solid red;">Errore nel caricamento del widget Klarna: ' + res.error_message + '</div>'); } }); // Funzione per autorizzare il pagamento window.authorizePayment = function() { consoleDebug('Inizio autorizzazione', 'attempting'); Klarna.Payments.authorize({ instance_id: 'klarna-payments-instance', // Aggiungiamo l'instance_id richiesto payment_method_category: 'pay_later' }, function(res) { consoleDebug('Authorization result', res); if (res.approved) { // Salva il token di autorizzazione $.post('klarna_api_test.php?action=save_auth_token', { auth_token: res.authorization_token }, function(data) { $('#payment-success').show(); }); } else { alert('Pagamento non autorizzato: ' + (res.error_message || 'Errore sconosciuto')); } }); }; // Aggiungi pulsante per autorizzare il pagamento $('#klarna_container').after('<button onclick="authorizePayment()" class="btn btn-primary">Autorizza Pagamento</button>'); } catch (e) { consoleDebug('Errore JavaScript', e.message); $('#klarna_container').html('<div style="color: red; padding: 10px; border: 1px solid red;">Errore JavaScript: ' + e.message + '</div>'); } }); </script> </body> </html> <?php break; case 'save_auth_token': // Salva il token di autorizzazione nella sessione $_SESSION['klarna_auth_token'] = $_POST['auth_token'] ?? ''; echo 'Token salvato'; break; case 'create_order': try { // Verifica che esista un token di autorizzazione if (empty($_SESSION['klarna_auth_token'])) { echo '<h1>Errore</h1>'; echo '<p>Nessun token di autorizzazione trovato. <a href="klarna_api_test.php?action=payment_page">Torna indietro</a> e autorizza il pagamento.</p>'; break; } debug('Token di autorizzazione', $_SESSION['klarna_auth_token']); // Crea i dati dell'ordine per Klarna $order_data = [ 'purchase_country' => 'IT', 'purchase_currency' => 'EUR', 'locale' => 'it-IT', 'order_amount' => 9999, 'order_tax_amount' => 1803, 'order_lines' => [ [ 'name' => 'Prodotto Test', 'quantity' => 1, 'unit_price' => 9999, 'tax_rate' => 2200, 'total_amount' => 9999, 'total_tax_amount' => 1803 ] ], 'merchant_urls' => [ 'confirmation' => 'https://example.com/confirmation', 'notification' => 'https://example.com/notification' ], 'billing_address' => [ 'given_name' => 'Nome', 'family_name' => 'Cognome', 'email' => 'test@example.com', 'phone' => '1234567890', 'street_address' => 'Via Test 123', 'city' => 'Milano', 'postal_code' => '20100', 'country' => 'IT' ] ]; // Crea l'ordine in Klarna $result = $klarna->createOrder($_SESSION['klarna_auth_token'], $order_data); debug('Risposta API Klarna per la creazione dell\'ordine', $result); echo '<h1>Risultato della creazione dell\'ordine Klarna</h1>'; prettyPrint($result); // Se l'ordine è stato creato con successo, mostra i dettagli if (isset($result['order_id'])) { echo '<h2>Ordine creato con successo!</h2>'; echo '<p>ID Ordine Klarna: ' . $result['order_id'] . '</p>'; // Salva l'ID dell'ordine nella sessione $_SESSION['klarna_order_id'] = $result['order_id']; echo '<a href="klarna_api_test.php?action=get_order" class="btn btn-primary">Visualizza dettagli ordine</a> '; echo '<a href="klarna_api_test.php" class="btn btn-success">Torna alla home</a>'; // Pulisci le variabili di sessione unset($_SESSION['klarna_session_id']); unset($_SESSION['klarna_client_token']); unset($_SESSION['klarna_auth_token']); } else { echo '<h2>Errore nella creazione dell\'ordine</h2>'; echo '<a href="klarna_api_test.php?action=payment_page" class="btn btn-danger">Torna alla pagina di pagamento</a>'; } } catch (Exception $e) { debug('Errore durante la creazione dell\'ordine', $e->getMessage()); echo '<h2>Errore nella creazione dell\'ordine</h2>'; echo '<a href="klarna_api_test.php?action=payment_page" class="btn btn-danger">Torna alla pagina di pagamento</a>'; } break; case 'get_order': try { // Verifica che esista un ID ordine if (empty($_SESSION['klarna_order_id'])) { echo '<h1>Errore</h1>'; echo '<p>Nessun ID ordine trovato. <a href="klarna_api_test.php">Torna indietro</a> e crea un nuovo ordine.</p>'; break; } // Ottieni i dettagli dell'ordine $result = $klarna->getOrder($_SESSION['klarna_order_id']); debug('Risposta API Klarna per i dettagli dell\'ordine', $result); echo '<h1>Dettagli dell\'ordine Klarna</h1>'; prettyPrint($result); echo '<a href="klarna_api_test.php" class="btn btn-success">Torna alla home</a>'; } catch (Exception $e) { debug('Errore durante il recupero dei dettagli dell\'ordine', $e->getMessage()); echo '<h2>Errore nel recupero dei dettagli dell\'ordine</h2>'; echo '<a href="klarna_api_test.php" class="btn btn-danger">Torna alla home</a>'; } break; case 'confirmation': echo '<h1>Conferma Pagamento</h1>'; echo '<p>Grazie per il tuo ordine! Il pagamento è stato confermato con successo.</p>'; echo '<a href="klarna_api_test.php" class="btn btn-success">Torna alla home</a>'; break; case 'notification': // Gestisci le notifiche push da Klarna $input = file_get_contents('php://input'); file_put_contents('klarna_notification.log', date('Y-m-d H:i:s') . ' - ' . $input . PHP_EOL, FILE_APPEND); http_response_code(200); exit; default: // Mostra il form iniziale ?> <!DOCTYPE html> <html> <head> <title>Test API Klarna</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 20px; color: #333; } .container { max-width: 800px; margin: 0 auto; background: #fff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h1, h2, h3 { color: #2c3e50; } .card { border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; } .card-header { background-color: #3498db; color: white; padding: 10px 15px; border-top-left-radius: 5px; border-top-right-radius: 5px; } .card-body { padding: 15px; } .btn { display: inline-block; background: #3498db; color: #fff; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; font-size: 16px; } </style> </head> <body> <div class="container"> <div class="card"> <div class="card-header"> <h3>Test Integrazione API Klarna</h3> </div> <div class="card-body"> <p>Questo è un file di test per verificare l'integrazione con le API Klarna.</p> <p>Clicca sul pulsante qui sotto per creare una sessione di pagamento Klarna di test.</p> <a href="klarna_api_test.php?action=create_session" class="btn">Crea Sessione Klarna</a> </div> </div> </div> </body> </html> <?php break; } ?>
| ver. 1.4 |
Github
|
.
| PHP 8.2.5 | Генерация страницы: 0 |
proxy
|
phpinfo
|
Настройка