en["authtoken_ZB"]; $authtoken_ZC = $abdDatGen["authtoken_ZC"]; #== Datos y Variables para OAuth Token $coa_ClientId = $abdDatGen["C_OAuth_client_id"]; $coa_ClientSecret = $abdDatGen["C_OAuth_client_secret"]; $coa_RefreshToken = $abdDatGen["C_OAuth_refresh_token"]; $coa_GrantType = $abdDatGen["C_OAuth_grant_type"]; $coa_RedirectUri = $abdDatGen["C_OAuth_redirect_uri"]; $coa_AuthUrl = "https://accounts.zoho.com/oauth/v2/token"; #---------------------------------------------------------------- # JFA: 2021-06-12 # Obtenemos el access_token #---------------------------------------------------------------- $access_token = oauth($appOwner, 'ZCreator', $coa_RefreshToken, $coa_ClientId, $coa_ClientSecret, $coa_RedirectUri, $coa_GrantType, $coa_AuthUrl); #== Conexión a Zoho Creator para el detalle del CFDI # Actualización a API V2 y OAuth JFA y FFR 2021-06-18 $request_url = 'https://creator.zoho.com/api/v2/'.$appOwner.'/'.$applnkname.'/report/cfdi_I_query/'.$bRecId; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); #JFA: Cambiamos el método de Autenticación a OAuth curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $access_token)); $r = curl_exec($ch); $array = json_decode($r); $bdDatArt = $array->data->jsonInvoiceDetail; $abdDatArt = json_decode($bdDatArt,true); curl_close ($ch); ### 4. DESTINATARIOS DE E-MAILS, PERSONAS A QUIENES LES LLEGARÁ DE MANERA ADJUNTA LA FACTURA ELECTRÓNICA EN ARCHIVOS .XML Y .PDF $CadenaEmails = $abdDatGen["CadenaEmails"]; $CadenaEmails = "ffaccinetto@aptus-legal.com"; ### 5. DATOS GENERALES DE LA FACTURA ############################################## $fact_serie = $abdDatGen["fact_serie"]; $fact_folio = $abdDatGen["fact_folio"]; if ($bFolioN <> ""){ $fact_folio = $bFolioN; } $NoFac = $fact_serie.$fact_folio; $fact_tipcompr = $abdDatGen["fact_tipcompr"]; $fact_exportacion = $abdDatGen["fact_exportacion"]; $tasa_iva = $abdDatGen["tasa_iva"]; $subTotal = number_format($abdDatGen["subTotal"],2,'.',''); $descuento = number_format($abdDatGen["descuento"],2,'.',''); $IVA = number_format($abdDatGen["IVA"],2,'.',''); $total = number_format($abdDatGen["total"],2,'.',''); $fecha_fact = $abdDatGen["fecha_fact"]; $condicionesDePago = $abdDatGen["condicionesDePago"]; $formaDePago = utf8_decode($abdDatGen["formaDePago"]); $metodoDePago = utf8_decode($abdDatGen["metodoDePago"]); $TipoCambio = $abdDatGen["TipoCambio"]; $LugarExpedicion = utf8_decode($abdDatGen["LugarExpedicion"]); $moneda = $abdDatGen["moneda"]; $invoiceID = $abdDatGen["invoiceID"]; $invoiceNumber = $abdDatGen["invoiceNumber"]; $TipoRelacion = $abdDatGen["TipoRelacion"]; if($incAddenda == 1) { $folio_AdAs = $abdDatGen["Folio_AdAs"]; $serie_AdAs = $abdDatGen["Serie_AdAs"]; $no_Prov_AdAs = $abdDatGen["No_Prov_AdAs"]; $ord_Com_AdAs = $abdDatGen["Ord_Comp_AdAs"]; $tip_Pro_AdAs = $abdDatGen["Tipo_Prov_AdAs"]; $jsonAddenda = $abdDatGen["JSON_Addenda_ASO"]; $ajsonAddenda = json_decode($jsonAddenda,true); } if($TipPDFGen == 1) { $sObservaciones = base64_encode(utf8_decode($abdDatGen["Observaciones"])); $sOrdenCobro = $abdDatGen["OrdenCobro"]; } $subTotal = 0; $subTotTraslados = 0; $totalImpuestosRetenidos = 0; // 5.24 Total de impuestos retenidos. $totalImpuestosTrasladados = 0; // 5.25 Total de impuestos trasladados. if ($tipoTest > 0){ ### 6. MUESTRA LA ZONA HORARIA PREDETERMINADA DEL SERVIDOR (OPCIONAL A MOSTRAR) ###### echo '
'; echo 'FECHA Y HORA DE SOLICITUD DE TIMBRADO'; echo '
'; echo '
'; echo $fecha_fact; // 6.1 Se muestra solo para consultar y confirmar que sea la correcta. echo '

'; } // Calculando subTotal, Impuestos Trasladados y Retenidos. for ($i = 0; $icreateElement("cfdi:Comprobante"); $root = $xml->appendChild($root); $cadena_original='||'; $noatt= array(); #== 10.2 Se crea e inserta el primer nodo donde se declaran los namespaces ====== cargaAtt($root, array("xsi:schemaLocation"=>"http://www.sat.gob.mx/cfd/4 http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd", "xmlns:cfdi"=>"http://www.sat.gob.mx/cfd/4", "xmlns:xsi"=>"http://www.w3.org/2001/XMLSchema-instance" ) ); $FechaFactur = "2022-05-31"."T".date("H:i:s"); #== 10.3 Rutina de integración de nodos ========================================= if($TipPDFGen == 1) { cargaAtt($root, array( "Version"=>"4.0", "Serie"=>$fact_serie, "Folio"=>$invoiceNumber, "Fecha"=>date("Y-m-d")."T".date("H:i:s"), "FormaPago"=>$formaDePago, "NoCertificado"=>$noCertificado, "CondicionesDePago"=>$condicionesDePago, "SubTotal"=>$subTotal, "Descuento"=>$descuento, "Moneda"=>$moneda, "TipoCambio"=>$TipoCambio, "Total"=>$total, "TipoDeComprobante"=>$fact_tipcompr, "Exportacion"=>$fact_exportacion, "MetodoPago"=>$metodoDePago, "LugarExpedicion"=>$LugarExpedicion ) ); } else { cargaAtt($root, array( "Version"=>"4.0", "Serie"=>$fact_serie, "Folio"=>$fact_folio, "Fecha"=>date("Y-m-d")."T".date("H:i:s"), "FormaPago"=>$formaDePago, "NoCertificado"=>$noCertificado, "CondicionesDePago"=>$condicionesDePago, "SubTotal"=>$subTotal, "Descuento"=>$descuento, "Moneda"=>$moneda, "TipoCambio"=>$TipoCambio, "Total"=>$total, "TipoDeComprobante"=>$fact_tipcompr, "Exportacion"=>$fact_exportacion, "MetodoPago"=>$metodoDePago, "LugarExpedicion"=>$LugarExpedicion ) ); } // Adicionado por FFR en Marzo 30, 2019 // Para el manejo de los CFDI Relacionados if($bDatRel <> "") { $cfdiRelacionados = $xml->createElement("cfdi:CfdiRelacionados"); $cfdiRelacionados = $root->appendChild($cfdiRelacionados); cargaAtt($cfdiRelacionados, array("TipoRelacion"=>utf8_decode($TipoRelacion))); for ($i=0; $i < count($abdDatRel); $i++) { $cfdiRelacionado = $xml->createElement("cfdi:CfdiRelacionado"); $cfdiRelacionado = $cfdiRelacionados->appendChild($cfdiRelacionado); cargaAtt($cfdiRelacionado, array("UUID"=>utf8_decode($abdDatRel[$i]["UUID"]))); } } $emisor = $xml->createElement("cfdi:Emisor"); $emisor = $root->appendChild($emisor); cargaAtt($emisor, array("Rfc"=>$emisor_rfc, "Nombre"=>$emisor_rs, "RegimenFiscal"=>$emisor_regfis ) ); $receptor = $xml->createElement("cfdi:Receptor"); $receptor = $root->appendChild($receptor); cargaAtt($receptor, array("Rfc"=>$receptor_rfc, "Nombre"=>$receptor_rs, "DomicilioFiscalReceptor"=>$receptor_cp, "RegimenFiscalReceptor"=>$receptor_regfis, "UsoCFDI"=>$receptor_uso ) ); $conceptos = $xml->createElement("cfdi:Conceptos"); $conceptos = $root->appendChild($conceptos); $isrImpuesto = "001"; $ivaImpuesto = "002"; #== 10.4 Ciclo "for", recopilación de datos de artículos e integración de sus respectivos nodos == $ivaTasaOCuota = 0.160000; $isrTasaOCuota = 0.060000; for ($i=0; $icreateElement("cfdi:Concepto"); $concepto = $conceptos->appendChild($concepto); $sOrdCom = ""; foreach ( $abdDatArt[$i] as $nombre => $hexa ) { if($nombre == "NoIdentificacion") { $sOrdCom = $hexa; } } if($sOrdCom != "") { cargaAtt($concepto, array( "ClaveProdServ"=>utf8_decode($abdDatArt[$i]["claveProd"]), "NoIdentificacion"=>utf8_decode($abdDatArt[$i]["NoIdentificacion"]), "Cantidad"=>$abdDatArt[$i]["cantidad"], "ClaveUnidad"=>utf8_decode($abdDatArt[$i]["unidad"]), "Unidad"=>trim(utf8_decode($abdDatArt[$i]["descUnidad"])), "Descripcion"=>trim(utf8_decode($abdDatArt[$i]["descripcion"])), "ValorUnitario"=>number_format($abdDatArt[$i]["valorUnitario"],2,'.',''), "Importe"=>number_format($abdDatArt[$i]["importe"],2,'.',''), "Descuento"=>number_format($abdDatArt[$i]["descuento"],2,'.',''), "ObjetoImp"=>utf8_decode($abdDatArt[$i]["ObjetoImp"]) ) ); } else { cargaAtt($concepto, array( "ClaveProdServ"=>utf8_decode($abdDatArt[$i]["claveProd"]), "Cantidad"=>$abdDatArt[$i]["cantidad"], "ClaveUnidad"=>utf8_decode($abdDatArt[$i]["unidad"]), "Unidad"=>trim(utf8_decode($abdDatArt[$i]["descUnidad"])), "Descripcion"=>trim(utf8_decode($abdDatArt[$i]["descripcion"])), "ValorUnitario"=>number_format($abdDatArt[$i]["valorUnitario"],2,'.',''), "Importe"=>number_format($abdDatArt[$i]["importe"],2,'.',''), "Descuento"=>number_format($abdDatArt[$i]["descuento"],2,'.',''), "ObjetoImp"=>utf8_decode($abdDatArt[$i]["ObjetoImp"]) ) ); } if ($abdDatArt[$i]["ivaImporte"] > 0 || $abdDatArt[$i]["isrImporte"] > 0) { $impuestos = $xml->createElement("cfdi:Impuestos"); $impuestos = $concepto->appendChild($impuestos); if ($abdDatArt[$i]["ivaImporte"] > 0) { $Traslados = $xml->createElement("cfdi:Traslados"); $Traslados = $impuestos->appendChild($Traslados); $Traslado = $xml->createElement("cfdi:Traslado"); $Traslado = $Traslados->appendChild($Traslado); $ivaImpuesto = $abdDatArt[$i]["ivaImpuesto"]; cargaAtt($Traslado, array( "Base"=>number_format($abdDatArt[$i]["ivaBase"],2,'.',''), "Impuesto"=>$abdDatArt[$i]["ivaImpuesto"], "TipoFactor"=>$abdDatArt[$i]["ivaTipoFactor"], "TasaOCuota"=>number_format($abdDatArt[$i]["ivaTasaOCuota"],6,'.',''), "Importe"=>number_format($abdDatArt[$i]["ivaImporte"],2,'.','') ) ); $ivaTasaOCuota = $abdDatArt[$i]["ivaTasaOCuota"]; } if ($abdDatArt[$i]["isrImporte"] > 0) { $Retenciones = $xml->createElement("cfdi:Retenciones"); $Retenciones = $impuestos->appendChild($Retenciones); $Retencion = $xml->createElement("cfdi:Retencion"); $Retencion = $Retenciones->appendChild($Retencion); $isrImpuesto = $abdDatArt[$i]["isrImpuesto"]; cargaAtt($Retencion, array( "Base"=>number_format($abdDatArt[$i]["isrBase"],2,'.',''), "Impuesto"=>$abdDatArt[$i]["isrImpuesto"], "TipoFactor"=>$abdDatArt[$i]["isrTipoFactor"], "TasaOCuota"=>number_format($abdDatArt[$i]["isrTasaOCuota"],6,'.',''), "Importe"=>number_format($abdDatArt[$i]["isrImporte"],2,'.','') ) ); $isrTasaOCuota = $abdDatArt[$i]["isrTasaOCuota"]; } } } if ($totalImpuestosTrasladados > 0 || $totalImpuestosRetenidos > 0) { $Impuestos = $xml->createElement("cfdi:Impuestos"); $Impuestos = $root->appendChild($Impuestos); if ($totalImpuestosRetenidos > 0) { $Retenciones = $xml->createElement("cfdi:Retenciones"); $Retenciones = $Impuestos->appendChild($Retenciones); $Retencion = $xml->createElement("cfdi:Retencion"); $Retencion = $Retenciones->appendChild($Retencion); cargaAtt($Retencion, array( "Impuesto"=>$isrImpuesto, "Importe"=>number_format($totalImpuestosRetenidos,2,'.','') ) ); cargaAtt($Impuestos, array( "TotalImpuestosRetenidos"=>number_format($totalImpuestosRetenidos,2,'.','') ) ); } if ($totalImpuestosTrasladados > 0) { $Traslados = $xml->createElement("cfdi:Traslados"); $Traslados = $Impuestos->appendChild($Traslados); $Traslado = $xml->createElement("cfdi:Traslado"); $Traslado = $Traslados->appendChild($Traslado); cargaAtt($Traslado, array( "Base"=>number_format($subTotTraslados,2,'.',''), "Impuesto"=>$ivaImpuesto, "TipoFactor"=>"Tasa", "TasaOCuota"=>number_format($ivaTasaOCuota,6,'.',''), "Importe"=>number_format($totalImpuestosTrasladados,2,'.','') ) ); cargaAtt($Impuestos, array( "TotalImpuestosTrasladados"=>number_format($totalImpuestosTrasladados,2,'.','') ) ); } } $complemento = $xml->createElement("cfdi:Complemento"); $complemento = $root->appendChild($complemento); #== 10.7 Termina de conformarse la "Cadena original" con doble || $cadena_original .= "|"; if ($tipoTest > 0){ #=== Muestra la cadena original (opcional a mostrar) ======================= echo '
'; echo 'CADENA ORIGINAL'; echo '
'; echo '
'; echo $cadena_original; echo '

'; } #== 10.8 Proceso para obtener el sello digital del archivo .pem.key ========= $keyid = openssl_get_privatekey(file_get_contents($SendaPEMS.$file_key)); openssl_sign($cadena_original, $crypttext, $keyid, OPENSSL_ALGO_SHA256); openssl_free_key($keyid); #== 10.9 Se convierte la cadena digital a Base 64 =========================== $sello = base64_encode($crypttext); if ($tipoTest > 0){ #=== Muestra el sello (opcional a mostrar) ================================= echo '
'; echo 'SELLO'; echo '
'; echo '
'; echo $sello; echo '

'; } #== 10.10 Proceso para extraer el certificado del sello digital ================== $file = $SendaPEMS.$file_cer; // Ruta al archivo $datos = file($file); $certificado = ""; $carga=false; for ($i=0; $i 0){ #=== Muestra el certificado del sello digital (opcional a mostrar) ========= echo '
'; echo 'CERTIFICADO DEL SELLO DIGITAL'; echo '
'; echo '
'; echo $certificado; echo '

'; } #== 10.11 Se continua con la integración de nodos =========================== $root->setAttribute("Sello",$sello); $root->setAttribute("Certificado",$certificado); # Certificado. #== Fin de la integración de nodos ========================================= #=== 10.12 Se guarda el archivo .XML antes de ser timbrado ======================= $cfdi = $xml->saveXML(); $xml->formatOutput = true; $xml->save($SendaCFDI."PreCFDI-33_".$NoFac.".xml"); unset($xml); #=== 10.13 Se dan permisos de escritura al archivo .xml. ========================= chmod($SendaCFDI."PreCFDI-33_".$NoFac.".xml", 0777); ### 11. PROCESO DE TIMBRADO ######################################################## if ($tipoTest > 0){ #=== Se muestra el .XML antes de ser timbrado (opcional a mostrar)========== echo '
'; echo 'FACTURA .XML A TIMBRAR'; echo '
'; echo '
'; echo htmlspecialchars($cfdi); echo '

'; } #== 11.1 Se crea una variable de tipo DOM y se le carga el CFDI ================================= $xml2 = new DOMDocument(); $xml2->loadXML($cfdi); #== 11.2 Proceso de validación de la variable de tipo DOM (estructura del CFDI a timbrar) contra el esquema cfdv32.xsd ========================== $fname = $SendaCFDI."PreCFDI-33_".$NoFac.".xml"; if(!file_exists($fname)){ die(PHP_EOL . "File not found" . PHP_EOL . PHP_EOL); } $handle = fopen($fname, "r"); $sData = ''; #== 11.3 Convirtiendo el contenido del CFDI a BASE 64 ====================== while(!feof($handle)) $sData .= fread($handle, filesize($fname)); fclose($handle); $b64 = base64_encode($sData); $response = ''; #== 11.5 Se lleva a cabo el timbrado del XML ============================ try { $client = new SoapClient($urlPAC); $params = array('usuario' => $username, 'password' => $password, 'cfdiBase64'=>$b64, 'zip'=>False); $response = $client->__soapCall('timbrarBase64', array('parameters' => $params)); } catch (SoapFault $fault) { $j_array = array('code' => "400", "message" => $fault->faultcode."-".$fault->faultstring); $Resultado = json_encode($j_array); echo $Resultado; return; } $ret = $response->return; if($ret->status != 200) { $j_array = array('code' => "500", "message" => "ERROR EN EL PROCESO DE TIMBRADO. ".$ret->status." - ".$ret->mensaje); $Resultado = json_encode($j_array); echo $Resultado; return; } /* if ($tipoTest > 0){ echo '
'; print_r($ret); echo '
'; return; } */ #=== 11.7 Muestra los resultados del timbrado del CFDI ========================= $RespServ = $ret->resultados->cfdiTimbrado; if($RespServ == NULL){ $j_array = array('code' => "600", "message" => "ERROR EN EL PROCESO DE TIMBRADO. status: ".$ret->status.", mensaje: ".$ret->mensaje.". ==> Resultado Timbrado: "." status: ".$ret->resultados->status.", mensaje: ".$ret->resultados->mensaje); $Resultado = json_encode($j_array); echo $Resultado; return; /* //echo $cadena_original; echo "status: ".$ret->resultados->status.", mensaje: ".$ret->resultados->mensaje; echo "
"; echo "
"; print_r($ret); echo "
"; echo "
"; die(PHP_EOL . "Error al timbrar el CFDI." . PHP_EOL . PHP_EOL); */ } if ($tipoTest > 0){ #== 12.5 Se muestra el .XML ya timbrado (CFDI V 3.2), opcional a mostrar ===== echo '
'; echo 'FACTURA .XML (CFDI) YA TIMBRADA'; echo '
'; echo '
'; echo htmlspecialchars($RespServ); echo '

'; } ## 12. PROCESOS POSTERIORES AL TIMBRADO ######################################## #== 12.1 Se asigna la respuesta del servidor a una variable de tipo DOM ==== $VarXML = new DOMDocument(); $VarXML->loadXML($RespServ); #== 12.1.1 Se valida si tiene addenda y se le agrega al CFDI ==== if($incAddenda == 1) { $root = $VarXML->firstChild; $addenda = $VarXML->createElement("cfdi:Addenda"); $addenda = $root->appendChild($addenda); $asonioscoc = $VarXML->createElement("ASONIOSCOC"); $asonioscoc = $addenda->appendChild($asonioscoc); cargaAttNodo($asonioscoc, array( "tipoProveedor"=>$tip_Pro_AdAs, "folio"=>$folio_AdAs, "ordenCompra"=>$ord_Com_AdAs, "noProveedor"=>$no_Prov_AdAs, "serie"=>$serie_AdAs ) ); $partidas = $VarXML->createElement("Partidas"); $partidas = $asonioscoc->appendChild($partidas); $partida = $VarXML->createElement("Partida"); $partida = $partidas->appendChild($partida); for ($i = 0; $i$ajsonAddenda[i]["ivaDevengado"], "ivaAcreditable"=>$ajsonAddenda[i]["ivaAcreditable"], "noPartida"=>$ajsonAddenda[i]["noPartida"], "Otros"=>$ajsonAddenda[i]["Otros"] ) ); } #== 12.2 Se graba la respuesta del servidor a un archivo .xml $VarXML->save($SendaCFDI."RespServ_".$NoFac.".xml"); chmod($SendaCFDI."RespServ_".$NoFac.".xml", 0777); if($TipPDFGen == 1) { $NomArchXML = "CFDI_".$fact_serie."_".$invoiceNumber.".xml"; $NomArchPDF = "CFDI_".$fact_serie."_".$invoiceNumber.".pdf"; } else { $NomArchXML = "CFDI_".$fact_serie.str_pad($fact_folio, 6, "0", STR_PAD_LEFT)."_".$invoiceNumber.".xml"; $NomArchPDF = "CFDI_".$fact_serie.str_pad($fact_folio, 6, "0", STR_PAD_LEFT)."_".$invoiceNumber.".pdf"; } $xmlt = new DOMDocument(); $xmlt->loadXML($RespServ); $xmlt->save($SendaCFDI.$NomArchXML); chmod($SendaCFDI.$NomArchXML, 0777); #== 12.7 Procesos para extraer datos del Timbre Fiscal del CFDI ========= $docXML = new DOMDocument(); //$docXML->load($SendaCFDI."Fact_CFDI_".$NoFac.".xml"); $docXML->load($SendaCFDI.$NomArchXML); $comprobante = $docXML->getElementsByTagName("TimbreFiscalDigital"); #== 12.8 Se obtienen contenidos de los atributos y se asignan a variables para ser mostrados ======= foreach($comprobante as $timFis){ $version_timbre = $timFis->getAttribute('Version'); $sello_SAT = $timFis->getAttribute('SelloSAT'); $cert_SAT = $timFis->getAttribute('NoCertificadoSAT'); $sello_CFD = $timFis->getAttribute('SelloCFD'); $tim_fecha = $timFis->getAttribute('FechaTimbrado'); $tim_uuid = $timFis->getAttribute('UUID'); $tim_RfcPac = $timFis->getAttribute('RfcProvCertif'); } if ($tipoTest > 0){ echo 'Versión del timbre: '.$version_timbre.'
'; echo 'Sello del SAT: '.$sello_SAT.'
'; echo 'Certificado del SAT: '.$cert_SAT.'
'; echo 'Sello del CFDI: '.$sello_CFD.'
'; echo 'Fecha de timbrado: '.$tim_fecha.'
'; echo 'Folio fiscal: '.$tim_uuid.'
'; echo 'RFC del PAC: '.$tim_RfcPac.'
'; echo 'No. de factura asignado por el sistema local: '.$NoFac.'

'; } #== 12.8.1 Se muestra el número de factura asignado por el sistema local (no asingado por el SAT). $params = $docXML->getElementsByTagName('Emisor'); foreach ($params as $param) { $Emisor_RFC = $param->getAttribute('Rfc'); } $params = $docXML->getElementsByTagName('Receptor'); foreach ($params as $param) { $Receptor_RFC = $param->getAttribute('Rfc'); } $params = $docXML->getElementsByTagName('Comprobante'); foreach ($params as $param) { $total = $param->getAttribute('Total'); } #== 12.9 Se crea el archivo .PNG con codigo bidimensional ================================= $filename = "archs_graf/Img_".$tim_uuid.".png"; ### 13. CREACION DE PDF ########################### # 13.1 Creación del Archivo PDF //$url = 'http://64.235.39.50/aptusCFDIRF/wsInvoicePDF_v33.php?NomArchXML='.$NomArchXML.'&NomArchPDF='.$NomArchPDF; if($TipPDFGen == 1) { $url = 'https://aptuslegal.app/aptusCFDIRF/'.$FormatoPDF.'.php?NomArchXML='.$NomArchXML.'&NomArchPDF='.$NomArchPDF.'&pInvNumb='.$invoiceNumber.'&pOrdCob='.$sOrdenCobro.'&pObserva='.$sObservaciones.'&pDirRecep='.$sDireRecep; } else { $url = 'https://aptuslegal.app/aptusCFDIRF/'.$FormatoPDF.'.php?NomArchXML='.$NomArchXML.'&NomArchPDF='.$NomArchPDF; } $objCurl = curl_init(); curl_setopt($objCurl, CURLOPT_URL, $url); curl_setopt($objCurl, CURLOPT_HEADER, 0); curl_setopt($objCurl, CURLOPT_RETURNTRANSFER, true); curl_exec($objCurl); curl_close($objCurl); # 13.3 Envio del Archivos a Invoice de Zoho Books # Primero actualizamos el access_token de Books #== Datos y Variables para OAuth Token $boa_ClientId = $abdDatGen["B_OAuth_client_id"]; $boa_ClientSecret = $abdDatGen["B_OAuth_client_secret"]; $boa_RefreshToken = $abdDatGen["B_OAuth_refresh_token"]; $boa_GrantType = $abdDatGen["B_OAuth_grant_type"]; $boa_RedirectUri = $abdDatGen["B_OAuth_redirect_uri"]; $boa_AuthUrl = "https://accounts.zoho.com/oauth/v2/token"; #---------------------------------------------------------------- # JFA: 2021-06-12 # Obtenemos el access_token #---------------------------------------------------------------- // $Params = array( // "refresh_token" => $boa_RefreshToken, // "client_id" => $boa_ClientId, // "client_secret" => $boa_ClientSecret, // "redirect_uri" => $boa_RedirectUri, // "grant_type" => $boa_GrantType // ); // $curl = curl_init(); // curl_setopt($curl, CURLOPT_URL, $boa_AuthUrl); // curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); // curl_setopt($curl, CURLOPT_POSTFIELDS, $Params); // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // $response = curl_exec($curl); // $array = json_decode($response); // $boa_access_token = $array->access_token; $boa_access_token = oauth($appOwner, 'ZBooks', $boa_RefreshToken, $boa_ClientId, $boa_ClientSecret, $boa_RedirectUri, $boa_GrantType, $boa_AuthUrl); //echo $access_token; if($organi_id_ZB != "673221150") { # Primero el PDF $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$NomArchPDF; $request_url = 'https://books.zoho.com/api/v3/invoices/'.$invoiceID.'/attachment'; if (function_exists('curl_file_create')) { // php 5.6+ $cFile = curl_file_create($file_name_with_full_path); } else { $cFile = '@' . realpath($file_name_with_full_path); } $post = array( //'authtoken' => $authtoken_ZB, 'organization_id' => $organi_id_ZB, 'can_send_in_mail' => 'true', 'attachment'=> $cFile); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); #JFA: Cambiamos el método de Autenticación a OAuth curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $boa_access_token)); $r = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close ($ch); $ra = json_decode($r); $resultPDF = $ra->code.' - '.$ra->message; if($ra->code != 0) { $NomArchHttp = '/var/www/html/aptusCFDIRF/archs_txt/'."CFDI_".$fact_serie."_".$invoiceNumber.".txt"; $variable = fopen($NomArchHttp,"w"); fwrite($variable,$httpcode . PHP_EOL); fwrite($variable,$ra->code.' - '.$ra->message); fclose($variable); } //print_r($r); } # Segundo el XML $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$NomArchXML; $request_url = 'https://books.zoho.com/api/v3/invoices/'.$invoiceID.'/attachment'; if (function_exists('curl_file_create')) { // php 5.6+ $cFile = curl_file_create($file_name_with_full_path); } else { $cFile = '@' . realpath($file_name_with_full_path); } $post = array( //'authtoken' => $authtoken_ZB, 'organization_id' => $organi_id_ZB, //'can_send_in_mail' => 'true', 'attachment'=> $cFile); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); #JFA: Cambiamos el método de Autenticación a OAuth curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $boa_access_token)); $r = curl_exec($ch); //print_r($r); curl_close ($ch); $ra = json_decode($r); $resultXML = $ra->code.' - '.$ra->message; # 13.4 Envio del Archivos a Invoice de Zoho Creator # Primero el PDF $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$NomArchPDF; //$request_url = 'https://creator.zoho.com/api/xml/fileupload/scope=creatorapi'; # Actualización a API V2 y OAuth JFA y FFR 2021-06-18 $request_url = 'https://creator.zoho.com/api/v2/'.$appOwner.'/'.$applnkname.'/report/cfdi_I_query/'.$bRecId.'/File_CFDI_PDF/upload'; if (function_exists('curl_file_create')) { // php 5.6+ $cFile = curl_file_create($file_name_with_full_path); } else { $cFile = '@' . realpath($file_name_with_full_path); } $post = array( // 'authtoken' => $authtoken_ZC, // 'applinkname' => $applnkname, // 'formname' => 'CreacionCFDIv33', // 'fieldname' => 'File_CFDI_PDF', // 'recordId' => $bRecId, //'filename' => $NomArchPDF, 'file'=> $cFile); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); #JFA: Cambiamos el método de Autenticación a OAuth curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $access_token)); $r = curl_exec($ch); curl_close ($ch); # Segundo el XML $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$NomArchXML; //$request_url = 'https://creator.zoho.com/api/xml/fileupload/scope=creatorapi'; # Actualización a API V2 y OAuth JFA y FFR 2021-06-18 $request_url = 'https://creator.zoho.com/api/v2/'.$appOwner.'/'.$applnkname.'/report/cfdi_I_query/'.$bRecId.'/File_CFDI_XML/upload'; if (function_exists('curl_file_create')) { // php 5.6+ $cFile = curl_file_create($file_name_with_full_path); } else { $cFile = '@' . realpath($file_name_with_full_path); } $post = array( // 'authtoken' => $authtoken_ZC, // 'applinkname' => $applnkname, // 'formname' => 'CreacionCFDIv33', // 'fieldname' => 'File_CFDI_XML', // 'recordId' => $bRecId, //'filename' => $NomArchXML, 'file'=> $cFile); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); #JFA: Cambiamos el método de Autenticación a OAuth curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $access_token)); $r = curl_exec($ch); curl_close ($ch); #== Se elimina los archivos de trabajo unlink($SendaCFDI."PreCFDI-33_".$NoFac.".xml"); unlink($SendaCFDI."RespServ_".$NoFac.".xml"); unlink($filename); $j_array = array('code' => "200", 'message' => "Proceso de creacion de CFDI fue exitoso", 'version_timbre' => $version_timbre, 'cert_SAT' => $cert_SAT, 'tim_fecha' => $tim_fecha, 'tim_uuid' => $tim_uuid, 'tim_RfcPac' => $tim_RfcPac, 'sello_SAT' => $sello_SAT, 'sello_CFD' => $sello_CFD); $Resultado = json_encode($j_array); echo $Resultado; return; ### 14. FUNCIONES DEL MÓDULO ######################################################### # 14.1 Función que integra los nodos al archivo .XML y forma la "Cadena original". function cargaAtt(&$nodo, $attr){ global $xml, $cadena_original; $quitar = array('sello'=>1,'noCertificado'=>1,'certificado'=>1); foreach ($attr as $key => $val){ $val = preg_replace('/\s\s+/', ' ', $val); $val = trim($val); if (strlen($val)>0){ $val = utf8_encode(str_replace("|","/",$val)); $nodo->setAttribute($key,$val); if (!isset($quitar[$key])) if (substr($key,0,3) != "xml" && substr($key,0,4) != "xsi:") $cadena_original .= $val . "|"; } } } # 14.2 Funciónes que da formato al "Importe total" como lo requiere el SAT para ser integrado al código QR. function ProcesImpTot($ImpTot){ $ImpTot = number_format($ImpTot, 4); // <== Se agregó el 30 de abril de 2017. $ArrayImpTot = explode(".", $ImpTot); $NumEnt = $ArrayImpTot[0]; $NumDec = ProcesDecFac($ArrayImpTot[1]); return $NumEnt.".".$NumDec; } function ProcesDecFac($Num){ $FolDec = ""; if ($Num < 10){$FolDec = "00000".$Num;} if ($Num > 9 and $Num < 100){$FolDec = $Num."0000";} if ($Num > 99 and $Num < 1000){$FolDec = $Num."000";} if ($Num > 999 and $Num < 10000){$FolDec = $Num."00";} if ($Num > 9999 and $Num < 100000){$FolDec = $Num."0";} return $FolDec; } function limpioCaracteresXML($cadena){ $search = array("<", ">", "&", "'"); $replace = array("<", ">", "&", "&apos"); $final = str_replace($search, $replace, $cadena); return $final; } function cargaAttNodo(&$nodo, $attr){ global $xmldoc; foreach ($attr as $key => $val){ $val = preg_replace('/\s\s+/', ' ', $val); $val = trim($val); if (strlen($val)>0){ $val = utf8_encode(str_replace("|","/",$val)); $nodo->setAttribute($key,$val); } } }