get_meta('_wc_zugferd_invoice_path'); if (!empty($existing_path) && file_exists($existing_path)) { return; } $result = self::generate_for_order($order); if ($result['success']) { $order->add_order_note(__('ZUGFeRD 2.2 E-Rechnung automatisch via API generiert.', 'agrunert-e-rechnung-for-zugferd')); } else { $order->add_order_note(sprintf(__('Fehler bei automatischer ZUGFeRD Generierung: %s', 'agrunert-e-rechnung-for-zugferd'), $result['error'])); } } public static function generate_for_order($order) { $api_key = get_option('wc_zugferd_api_key', ''); $test_mode = get_option('wc_zugferd_test_mode', '1'); $api_url = trailingslashit(get_option('wc_zugferd_api_url', 'https://e-rechnung-cloud.de')); if (empty($api_key)) { if ($test_mode === '1') { $api_key = 'api_key_test_public'; } else { return array('success' => false, 'error' => __('Kein API-Schlüssel konfiguriert. Jetzt Live-API-Key holen unter https://e-rechnung-cloud.de/#pricing', 'agrunert-e-rechnung-for-zugferd')); } } $payload = self::build_invoice_payload($order); if (is_wp_error($payload)) { return array('success' => false, 'error' => $payload->get_error_message()); } $endpoint = $api_url . 'v1/invoice/generate'; $response = wp_remote_post($endpoint, array( 'headers' => array( 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', 'User-Agent' => 'WooCommerce-ZUGFeRD/' . WC_ZUGFERD_VERSION ), 'body' => wp_json_encode($payload), 'timeout' => 45 )); if (is_wp_error($response)) { return array('success' => false, 'error' => $response->get_error_message()); } $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); if ($code !== 200) { $err_data = json_decode($body, true); $msg = isset($err_data['detail']) ? (is_array($err_data['detail']) ? json_encode($err_data['detail']) : $err_data['detail']) : 'HTTP ' . $code; if (in_array($code, array(401, 402, 429), true)) { $msg .= ' (Live-API-Key / Guthaben aufladen unter https://e-rechnung-cloud.de/#pricing)'; } return array('success' => false, 'error' => $msg); } // Save PDF $save_result = self::save_invoice_pdf($order, $body); if (!$save_result['success']) { return $save_result; } $order->update_meta_data('_wc_zugferd_invoice_path', $save_result['file_path']); $order->update_meta_data('_wc_zugferd_created_at', current_time('mysql')); $order->save(); return array('success' => true, 'file_path' => $save_result['file_path']); } public static function build_invoice_payload($order) { $order_id = $order->get_id(); $date = $order->get_date_created() ? $order->get_date_created()->date('Y-m-d') : current_time('Y-m-d'); // Seller data from settings $seller_name = get_option('wc_zugferd_seller_name', get_bloginfo('name')); $seller_street = get_option('wc_zugferd_seller_street', ''); $seller_zip = get_option('wc_zugferd_seller_zip', ''); $seller_city = get_option('wc_zugferd_seller_city', ''); $seller_country = get_option('wc_zugferd_seller_country', 'DE'); $seller_vat = get_option('wc_zugferd_seller_vat_id', ''); $seller_iban = get_option('wc_zugferd_seller_iban', ''); if (empty($seller_name) || empty($seller_street) || empty($seller_zip) || empty($seller_city)) { return new WP_Error('missing_seller_data', __('Verkäufer-Stammdaten in den ZUGFeRD-Einstellungen unvollständig.', 'agrunert-e-rechnung-for-zugferd')); } // Buyer data from order $buyer_company = $order->get_billing_company(); $buyer_name = !empty($buyer_company) ? $buyer_company : trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()); if (empty($buyer_name)) { $buyer_name = 'Kunde #' . $order_id; } $buyer_street = trim($order->get_billing_address_1() . ' ' . $order->get_billing_address_2()); if (empty($buyer_street)) { $buyer_street = 'Standard-Adresse'; } $buyer_zip = $order->get_billing_postcode(); if (empty($buyer_zip)) $buyer_zip = '00000'; $buyer_city = $order->get_billing_city(); if (empty($buyer_city)) $buyer_city = 'Unbekannt'; $buyer_country = $order->get_billing_country(); if (empty($buyer_country)) $buyer_country = 'DE'; // Check for VAT ID from popular B2B plugins (Germanized, German Market, B2B Market, etc.) $buyer_vat = $order->get_meta('_billing_vat_number'); if (empty($buyer_vat)) $buyer_vat = $order->get_meta('vat_number'); if (empty($buyer_vat)) $buyer_vat = $order->get_meta('_vat_number'); // Line Items $line_items = array(); foreach ($order->get_items() as $item_id => $item) { $qty = (float) $item->get_quantity(); if ($qty <= 0) $qty = 1.0; $total = (float) $item->get_total(); $tax = (float) $item->get_total_tax(); $unit_price = round($total / $qty, 2); $tax_rate = ($total > 0) ? round(($tax / $total) * 100, 1) : 0.0; // Normalize standard German tax rates (19% or 7%) if (abs($tax_rate - 19.0) < 1.0) $tax_rate = 19.0; elseif (abs($tax_rate - 7.0) < 1.0) $tax_rate = 7.0; $line_items[] = array( 'description' => $item->get_name(), 'quantity' => $qty, 'unit_price' => $unit_price, 'tax_rate_percent' => $tax_rate ); } // Shipping as line item if greater than 0 $shipping_total = (float) $order->get_shipping_total(); if ($shipping_total > 0) { $shipping_tax = (float) $order->get_shipping_tax(); $shipping_tax_rate = ($shipping_total > 0) ? round(($shipping_tax / $shipping_total) * 100, 1) : 0.0; if (abs($shipping_tax_rate - 19.0) < 1.0) $shipping_tax_rate = 19.0; elseif (abs($shipping_tax_rate - 7.0) < 1.0) $shipping_tax_rate = 7.0; $line_items[] = array( 'description' => !empty($order->get_shipping_method()) ? $order->get_shipping_method() : __('Versandkosten', 'agrunert-e-rechnung-for-zugferd'), 'quantity' => 1.0, 'unit_price' => $shipping_total, 'tax_rate_percent' => $shipping_tax_rate ); } // Ensure at least one line item if (empty($line_items)) { $line_items[] = array( 'description' => sprintf(__('Pauschale Bestellung #%s', 'agrunert-e-rechnung-for-zugferd'), $order_id), 'quantity' => 1.0, 'unit_price' => (float) $order->get_total(), 'tax_rate_percent' => 19.0 ); } $seller = array( 'name' => $seller_name, 'street' => $seller_street, 'zip_code' => $seller_zip, 'city' => $seller_city, 'country' => $seller_country, ); if (!empty($seller_vat)) $seller['vat_id'] = $seller_vat; if (!empty($seller_iban)) $seller['iban'] = preg_replace('/\s+/', '', $seller_iban); $buyer = array( 'name' => $buyer_name, 'street' => $buyer_street, 'zip_code' => $buyer_zip, 'city' => $buyer_city, 'country' => $buyer_country, ); if (!empty($buyer_vat)) $buyer['vat_id'] = $buyer_vat; $invoice_number = 'RE-' . $order->get_order_number(); $buyer_ref = $order->get_meta('_billing_leitweg_id') ? $order->get_meta('_billing_leitweg_id') : $order->get_meta('_buyer_reference'); return array( 'invoice_number' => $invoice_number, 'issue_date' => $date, 'currency' => $order->get_currency() ? $order->get_currency() : 'EUR', 'seller' => $seller, 'buyer' => $buyer, 'line_items' => $line_items, 'buyer_reference'=> !empty($buyer_ref) ? sanitize_text_field($buyer_ref) : null ); } private static function save_invoice_pdf($order, $binary_pdf) { $upload_dir = wp_upload_dir(); $target_dir = trailingslashit($upload_dir['basedir']) . 'zugferd-invoices'; if (!file_exists($target_dir)) { wp_mkdir_p($target_dir); // Protect directory against direct browsing @file_put_contents($target_dir . '/index.php', '\n Order Deny,Allow\n Deny from all\n"); } $token = wp_generate_password(12, false); $file_name = sprintf('rechnung_%d_%s.pdf', $order->get_id(), $token); $file_path = $target_dir . '/' . $file_name; $written = @file_put_contents($file_path, $binary_pdf); if ($written === false) { return array('success' => false, 'error' => __('Konnte PDF nicht im Upload-Ordner speichern.', 'agrunert-e-rechnung-for-zugferd')); } return array('success' => true, 'file_path' => $file_path); } public static function check_api_credits($api_key, $api_url) { $endpoint = trailingslashit($api_url) . 'v1/invoice/credits'; $response = wp_remote_get($endpoint, array( 'headers' => array( 'X-API-Key' => $api_key ), 'timeout' => 10 )); if (is_wp_error($response)) { return array('valid' => false, 'credits' => 0); } $code = wp_remote_retrieve_response_code($response); if ($code !== 200) { return array('valid' => false, 'credits' => 0); } $data = json_decode(wp_remote_retrieve_body($response), true); return array( 'valid' => isset($data['valid']) ? (bool) $data['valid'] : true, 'credits' => isset($data['credits_remaining']) ? (is_numeric($data['credits_remaining']) ? (int) $data['credits_remaining'] : sanitize_text_field((string) $data['credits_remaining'])) : 0 ); } }