public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
// 1) Monta array de produtos (como funcionava antes)
$items = $order->get_items();
$products = array();
foreach ( $items as $item_id => $item ) {
$product_id = $item->get_product_id();
$product_name = $item->get_name();
$quantity = intval( $item->get_quantity() );
$price = floatval( $order->get_line_subtotal( $item, false ) );
$products[] = array(
'id' => (string) $product_id,
'name' => $product_name,
'quantity' => $quantity,
'price' => $price,
);
}
// 2) Recupera e sanitiza CPF (somente dígitos)
$raw_document = isset( $_POST['billing_cpf'] ) ? wc_clean( $_POST['billing_cpf'] ) : '';
$documentDigits = preg_replace( '/\D/', '', $raw_document );
// 3) CORREÇÃO: Usar o valor TOTAL (com desconto já aplicado) em amount
// A API espera o valor final que será cobrado, não o subtotal
$payload = array(
'identifier' => $this->generate_identifier(),
'amount' => floatval( $order->get_total() ), // VALOR FINAL (R$ 271,93)
'shippingFee' => floatval( $order->get_shipping_total() ),
'extraFee' => 0.0,
'discount' => 0.0, // ZERO - desconto já aplicado no WooCommerce
'client' => array(
'name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
'document' => $documentDigits,
),
'products' => $products,
'splits' => array(),
'dueDate' => date( 'Y-m-d', strtotime( '+' . apply_filters( 'wc_safirapay_pix_due_days', 1 ) . ' days' ) ),
'metadata' => new stdClass(),
'callbackUrl' => esc_url_raw( $this->get_return_url( $order ) ),
);
$json_payload = wp_json_encode( $payload, JSON_UNESCAPED_UNICODE );
$endpoint = 'https://app.safirapag.com/api/v1/gateway/pix/receive';
// 4) Debug simples para verificar
$debug_info = array(
'order_total' => floatval( $order->get_total() ),
'products_sum' => array_sum( array_column( $products, 'price' ) ),
'shipping' => floatval( $order->get_shipping_total() ),
'discount_in_payload' => 0.0
);
$debug_path = ABSPATH . 'safirapay_simple_debug.txt';
file_put_contents( $debug_path, "=== " . date('Y-m-d H:i:s') . " ===\n" . print_r($debug_info, true) . "\n", FILE_APPEND );
// 5) Chamada à API (resto igual ao original)
$args = array(
'method' => 'POST',
'timeout' => 45,
'headers' => array(
'Content-Type' => 'application/json',
'x-public-key' => $this->public_key,
'x-secret-key' => $this->secret_key,
),
'body' => $json_payload,
);
$response = wp_remote_post( $endpoint, $args );
$http_code = wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
$result = json_decode( $body, true );
// 6) Verifica erros de conexão
if ( is_wp_error( $response ) ) {
if ( $this->logging ) {
error_log( 'Erro SafiraPay PIX (WP_Error): ' . $response->get_error_message() );
}
wc_add_notice( __( 'SafiraPay PIX falhou: Problema de conexão.', 'wc-safirapay' ), 'error' );
return array( 'result' => 'failure' );
}
// 7) Aceita HTTP 200 OU 201 como sucesso
if ( $http_code !== 200 && $http_code !== 201 ) {
if ( $this->logging ) {
error_log( sprintf( 'Erro SafiraPay PIX – HTTP Code: %s', $http_code ) );
error_log( sprintf( 'Erro SafiraPay PIX – Response body: %s', $body ) );
}
$mensagem = 'SafiraPay PIX falhou: ';
if ( isset( $result['errorCode'] ) && isset( $result['message'] ) ) {
$mensagem .= $result['errorCode'] . ' – ' . $result['message'];
if ( isset( $result['details'] ) ) {
file_put_contents( ABSPATH . 'pix_error_details.txt', print_r( $result['details'], true ) );
$mensagem .= ' Detalhes: ' . wp_json_encode( $result['details'] );
}
} else {
$mensagem .= 'Erro genérico ao criar cobrança PIX.';
}
wc_add_notice( $mensagem, 'error' );
return array( 'result' => 'failure' );
}
// 8) Sucesso
update_post_meta( $order_id, '_safirapay_pix_response', $result );
$order->update_status( 'on-hold', __( 'Aguardando pagamento PIX', 'wc-safirapay' ) );
wc_reduce_stock_levels( $order_id );
WC()->cart->empty_cart();
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order ),
);
}
Shop – Kinzan Cosmeticos
“LATTAFA – Emeer 100ml Eau de Parfum” foi adicionado ao seu carrinho.
Ver carrinho
R$ 679,90
ou 12× de R$ 66,66
R$ 605,10
ou 12× de R$ 59,33
Ver opções
Este produto tem várias variantes. As opções podem ser escolhidas na página do produto
R$ 475,30
ou 12× de R$ 46,60
R$ 291,70
ou 12× de R$ 28,60
R$ 475,90
ou 12× de R$ 46,66
R$ 375,20
ou 12× de R$ 36,79
R$ 507,90
ou 12× de R$ 49,80
Ver opções
Este produto tem várias variantes. As opções podem ser escolhidas na página do produto
Ver opções
Este produto tem várias variantes. As opções podem ser escolhidas na página do produto
Ver opções
Este produto tem várias variantes. As opções podem ser escolhidas na página do produto
R$ 509,90
ou 12× de R$ 49,99