annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); declaration = containingFunction; } break; case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; } break; case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; } break; default: return Debug.fail(String(errorCode)); } importAdder.writeFixes(changes); return declaration; } function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) { if (isIdentifier(declaration.name)) { annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { if (!isIdentifier(parameterDeclaration.name)) { return; } const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); if (isInJSFile(containingFunction)) { annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */, sourceFile); if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */)); for (const { declaration, type } of parameterInferences) { if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, importAdder, sourceFile, declaration, type, program, host); } } if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */)); } } function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); if (!references || !references.length) { return; } const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host); if (!typeNode) { return; } if (isInJSFile(containingFunction)) { annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); } else { changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); } } function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { changes.addJSDocTags(sourceFile, containingFunction, [ factory.createJSDocThisTag( /*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode) ) ]); } function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); if (type === program.getTypeChecker().getAnyType()) { type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); } if (isInJSFile(setAccessorDeclaration)) { annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); } else { annotate(changes, importAdder, sourceFile, param, type, program, host); } } } function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (isInJSFile(sourceFile) && declaration.kind !== 171 /* PropertySignature */) { const parent2 = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; if (!parent2) { return; } const typeExpression = factory.createJSDocTypeExpression(typeNode); const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag( /*tagName*/ void 0, typeExpression, /*comment*/ void 0 ) : factory.createJSDocTypeTag( /*tagName*/ void 0, typeExpression, /*comment*/ void 0 ); changes.addJSDocTags(sourceFile, parent2, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { forEach(importableReference.symbols, (s) => importAdder.addImportFromExportedSymbol( s, /*isValidTypeOnlyUseSite*/ true )); return true; } return false; } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { const signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { return; } const inferences = mapDefined(parameterInferences, (inference) => { const param = inference.declaration; if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) { return; } const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); if (typeNode) { const name = factory.cloneNode(param.name); setEmitFlags(name, 3072 /* NoComments */ | 4096 /* NoNestedComments */); return { name: factory.cloneNode(param.name), param, isOptional: !!inference.isOptional, typeNode }; } }); if (!inferences.length) { return; } if (isArrowFunction(signature) || isFunctionExpression(signature)) { const needParens = isArrowFunction(signature) && !findChildOfKind(signature, 21 /* OpenParenToken */, sourceFile); if (needParens) { changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(21 /* OpenParenToken */)); } forEach(inferences, ({ typeNode, param }) => { const typeTag = factory.createJSDocTypeTag( /*tagName*/ void 0, factory.createJSDocTypeExpression(typeNode) ); const jsDoc = factory.createJSDocComment( /*comment*/ void 0, [typeTag] ); changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " }); }); if (needParens) { changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(22 /* CloseParenToken */)); } } else { const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag( /*tagName*/ void 0, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /*isNameFirst*/ false, /*comment*/ void 0 )); changes.addJSDocTags(sourceFile, signature, paramTags); } } function getReferences(token, program, cancellationToken) { return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry) => entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { const references = getReferences(token, program, cancellationToken); return inferTypeFromReferences(program, references, cancellationToken).single(); } function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { const references = getFunctionReferences(func, sourceFile, program, cancellationToken); return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p) => ({ declaration: p, type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() })); } function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { let searchToken; switch (containingFunction.kind) { case 176 /* Constructor */: searchToken = findChildOfKind(containingFunction, 137 /* ConstructorKeyword */, sourceFile); break; case 219 /* ArrowFunction */: case 218 /* FunctionExpression */: const parent2 = containingFunction.parent; searchToken = (isVariableDeclaration(parent2) || isPropertyDeclaration(parent2)) && isIdentifier(parent2.name) ? parent2.name : containingFunction.name; break; case 262 /* FunctionDeclaration */: case 174 /* MethodDeclaration */: case 173 /* MethodSignature */: searchToken = containingFunction.name; break; } if (!searchToken) { return void 0; } return getReferences(searchToken, program, cancellationToken); } function inferTypeFromReferences(program, references, cancellationToken) { const checker = program.getTypeChecker(); const builtinConstructors = { string: () => checker.getStringType(), number: () => checker.getNumberType(), Array: (t) => checker.createArrayType(t), Promise: (t) => checker.createPromiseType(t) }; const builtins = [ checker.getStringType(), checker.getNumberType(), checker.createArrayType(checker.getAnyType()), checker.createPromiseType(checker.getAnyType()) ]; return { single: single2, parameters, thisParameter }; function createEmptyUsage() { return { isNumber: void 0, isString: void 0, isNumberOrString: void 0, candidateTypes: void 0, properties: void 0, calls: void 0, constructs: void 0, numberIndex: void 0, stringIndex: void 0, candidateThisTypes: void 0, inferredTypes: void 0 }; } function combineUsages(usages) { const combinedProperties = /* @__PURE__ */ new Map(); for (const u of usages) { if (u.properties) { u.properties.forEach((p, name) => { if (!combinedProperties.has(name)) { combinedProperties.set(name, []); } combinedProperties.get(name).push(p); }); } } const properties = /* @__PURE__ */ new Map(); combinedProperties.forEach((ps, name) => { properties.set(name, combineUsages(ps)); }); return { isNumber: usages.some((u) => u.isNumber), isString: usages.some((u) => u.isString), isNumberOrString: usages.some((u) => u.isNumberOrString), candidateTypes: flatMap(usages, (u) => u.candidateTypes), properties, calls: flatMap(usages, (u) => u.calls), constructs: flatMap(usages, (u) => u.constructs), numberIndex: forEach(usages, (u) => u.numberIndex), stringIndex: forEach(usages, (u) => u.stringIndex), candidateThisTypes: flatMap(usages, (u) => u.candidateThisTypes), inferredTypes: void 0 // clear type cache }; } function single2() { return combineTypes(inferTypesFromReferencesSingle(references)); } function parameters(declaration) { if (references.length === 0 || !declaration.parameters) { return void 0; } const usage = createEmptyUsage(); for (const reference of references) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } const calls = [...usage.constructs || [], ...usage.calls || []]; return declaration.parameters.map((parameter, parameterIndex) => { const types = []; const isRest = isRestParameter(parameter); let isOptional = false; for (const call of calls) { if (call.argumentTypes.length <= parameterIndex) { isOptional = isInJSFile(declaration); types.push(checker.getUndefinedType()); } else if (isRest) { for (let i = parameterIndex; i < call.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); } } else { types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); } } if (isIdentifier(parameter.name)) { const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred); } const type = combineTypes(types); return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, declaration: parameter }; }); } function thisParameter() { const usage = createEmptyUsage(); for (const reference of references) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } return combineTypes(usage.candidateThisTypes || emptyArray); } function inferTypesFromReferencesSingle(references2) { const usage = createEmptyUsage(); for (const reference of references2) { cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } return inferTypes(usage); } function calculateUsageOfNode(node, usage) { while (isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } switch (node.parent.kind) { case 244 /* ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; case 225 /* PostfixUnaryExpression */: usage.isNumber = true; break; case 224 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; case 226 /* BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; case 296 /* CaseClause */: case 297 /* DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; case 213 /* CallExpression */: case 214 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } else { inferTypeFromContextualType(node, usage); } break; case 211 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; case 212 /* ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; case 172 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; case 260 /* VariableDeclaration */: { const { name, initializer } = node.parent; if (node === name) { if (initializer) { addCandidateType(usage, checker.getTypeAtLocation(initializer)); } break; } } default: return inferTypeFromContextualType(node, usage "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan el Propoietario de la Aplicación"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bRecId == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan el ID del CFDI a actualizar"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bDatPAC == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los Datos del PAC"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bDatGen == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los Datos Generales"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bDatEmi == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los Datos del Emisor"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bDatRec == "" or $bDatArt == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los Datos del Receptor"); $Resultado = json_encode($j_array); echo $Resultado; return; } if($bDatArt == "") { $j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los Datos de los Articulos"); $Resultado = json_encode($j_array); echo $Resultado; return; } ### 0. EXTRACCION DE PARAMETROS PARA EL CFDI ###################################################### #== Primero, extraemos el JSON del string en base 64 $bdDatPAC = base64_decode($bDatPAC); $bdDatGen = base64_decode($bDatGen); $bdDatEmi = base64_decode($bDatEmi); $bdDatRec = base64_decode($bDatRec); $bdDatArt = base64_decode($bDatArt); if($bDatRel <> "") { $bdDatRel = base64_decode($bDatRel); } #== Segundo, decodificamos el JSON a un arreglo $abdDatPAC = json_decode($bdDatPAC,true); $abdDatGen = json_decode($bdDatGen,true); $abdDatEmi = json_decode($bdDatEmi,true); $abdDatRec = json_decode($bdDatRec,true); $abdDatArt = json_decode($bdDatArt,true); if($bDatRel <> "") { $abdDatRel = json_decode($bdDatRel,true); } $dirBase = realpath("../"); ### CÓDIGO FUENTE, FACTURACIÓN ELECTRÓNICA CFDI VERSIÓN 3.2 ACORDE A LOS REQUIRIMIENTOS DEL SAT, ANEXO 20. ### 1. CONFIGURACIÓN INICIAL ###################################################### # 1.1 Configuración de zona horaria date_default_timezone_set('America/Mexico_City'); // # 1.2 Muestra la zona horaria predeterminada del servidor (opcional a mostrar) ### 2. DEFINICIÓN DE CONSTANTES ################################################### $SendaPEMS = "archs_pem/"; $SendaCFDI = "archs_cfdi/"; $SendaGRAFS = "archs_graf/"; $SendaXSD = "archs_xsd/"; // 2.1 Datos de acceso del usuario (proporcionados por el PAC). if($abdDatPAC["tipoTim"] == 1){ ## Timbrado en producción $urlPAC = "https://solucionfactible.com/ws/services/Timbrado"; } else { ## Timbrado en pruebas $urlPAC = "https://testing.solucionfactible.com/ws/services/Timbrado?wsdl"; } $username = $abdDatPAC["username"]; $password = $abdDatPAC["password"]; $valorNod = ''; $metodoDePago = ""; ### MUESTRA LOS DATOS DEL USUARIO QUE ESTÁ TIMBRANDO (OPCIONAL A MOSTRAR) ###### ### 3. DEFINICIÓN DE VARIABLES INICIALES ########################################## //$noCertificado = "00001000000409970859"; //$file_cer = "00001000000409970859.cer.pem"; //$file_key = "00001000000409970859.key.pem"; $noCertificado = $abdDatGen["Certificado_SAT"]; $file_cer = $abdDatGen["Archivo_CER"]; $file_key = $abdDatGen["Archivo_KEY"]; $organi_id_ZB = $abdDatGen["organization_id_ZB"]; $authtoken_ZB = $abdDatGen["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); ### 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"]; $NoFac = $fact_serie.$fact_folio; $fact_tipcompr = $abdDatGen["fact_tipcompr"]; $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($TipPDFGen == 1) { $sObservaciones = base64_encode(utf8_decode($abdDatGen["Observaciones"])); $sOrdenCobro = $abdDatGen["OrdenCobro"]; } $subTotal = 0; $totalImpuestosRetenidos = 0; // 5.24 Total de impuestos retenidos. $totalImpuestosTrasladados = 0; // 5.25 Total de impuestos trasladados. // 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" ) ); #== 10.3 Rutina de integración de nodos ========================================= 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, "MetodoPago"=>$metodoDePago, "LugarExpedicion"=>$LugarExpedicion ) ); $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 ) ); // 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"]))); } } $conceptos = $xml->createElement("cfdi:Conceptos"); $conceptos = $root->appendChild($conceptos); $isrImpuesto = "001"; $ivaImpuesto = "002"; $lIvaTraslad = false; $lIsrRetenid = false; #== 10.4 Ciclo "for", recopilación de datos de artículos e integración de sus respectivos nodos = $ivaTasaOCuota = 0.160000; for ($i=0; $icreateElement("cfdi:Concepto"); $concepto = $conceptos->appendChild($concepto); cargaAtt($concepto, array( "ClaveProdServ"=>utf8_decode($abdDatArt[$i]["claveProd"]), "Cantidad"=>$abdDatArt[$i]["cantidad"], "ClaveUnidad"=>utf8_decode($abdDatArt[$i]["unidad"]), "Unidad"=>utf8_decode($abdDatArt[$i]["descUnidad"]), "Descripcion"=>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"]) ) ); $impuestos = $xml->createElement("cfdi:Impuestos"); $impuestos = $concepto->appendChild($impuestos); //if ($abdDatArt[$i]["ivaImporte"] > 0) if($abdDatArt[$i]["ivaImpuesto"] == "002") { $lIvaTraslad = true; $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) if($abdDatArt[$i]["isrImpuesto"] == "001") { $lIsrRetenid = true; $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,'.','') ) ); } } $Impuestos = $xml->createElement("cfdi:Impuestos"); $Impuestos = $root->appendChild($Impuestos); //if ($totalImpuestosTrasladados > 0) if ($lIvaTraslad == true) { $Traslados = $xml->createElement("cfdi:Traslados"); $Traslados = $Impuestos->appendChild($Traslados); $Traslado = $xml->createElement("cfdi:Traslado"); $Traslado = $Traslados->appendChild($Traslado); cargaAtt($Traslado, array( "Impuesto"=>$ivaImpuesto, "TipoFactor"=>"Tasa", "TasaOCuota"=>number_format($ivaTasaOCuota,6,'.',''), "Importe"=>number_format($totalImpuestosTrasladados,2,'.','') ) ); cargaAtt($Impuestos, array( "TotalImpuestosTrasladados"=>number_format($totalImpuestosTrasladados,2,'.','') ) ); } //if ($totalImpuestosRetenidos > 0) if ($lIsrRetenid == true) { $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,'.','') ) ); } $complemento = $xml->createElement("cfdi:Complemento"); $complemento = $root->appendChild($complemento); #== 10.7 Termina de conformarse la "Cadena original" con doble || $cadena_original .= "|"; #=== Muestra la cadena original (opcional a mostrar) ======================= #== 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); #=== Muestra el sello (opcional a mostrar) ================================= #== 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; $isetAttribute("sello",$sello); $root->setAttribute("certificado",$certificado); # Certificado. //$root->setAttribute("motivoDescuento",$MotivDesc); # Motivo de descuento. //$root->setAttribute("folio",$fact_folio); # Folio de la factura (número entero). //$root->setAttribute("serie",$fact_serie); # Serie de la factura (letra o letras). #== Fin de la integración de nodos ========================================= #=== 10.12 Se guarda el archivo .XML antes de ser timbrado ======================= $NomArchCFDI = $SendaCFDI."PreCFDI-33_".$NoFac.".xml"; $NomArchPDF1 = $SendaCFDI."VP_CFDI_".$fact_serie.str_pad($fact_folio, 6, "0", STR_PAD_LEFT)."_".$invoiceNumber.".pdf"; $NomArchXML = "PreCFDI-33_".$NoFac.".xml"; $NomArchPDF = "VP_CFDI_".$fact_serie.str_pad($fact_folio, 6, "0", STR_PAD_LEFT)."_".$invoiceNumber.".pdf"; // $cfdi = $xml->saveXML(); $xml->formatOutput = true; $xml->save($NomArchCFDI); // Guarda el archivo .XML (sin timbrar) en el directorio predeterminado. unset($xml); #=== 10.13 Se dan permisos de escritura al archivo .xml. ========================= chmod($NomArchCFDI, 0777); ### 13. CREACION DE PDF Y ENVIO DE CORREO CON XML Y PDF ########################### # 13.1 Creación del Archivo PDF //$url = 'http://localhost/aptusCFDIRF/wsInvoicePDF_VP_v33.php?NomArchXML='.$NomArchXML.'&NomArchPDF='.$NomArchPDF; //$url = 'http://localhost/aptusCFDIRF/'.$FormatoPDF.'.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 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 con OAuth. JFA y FFR 2021-06-18 $request_url = 'https://creator.zoho.com/api/v2/'.$appOwner.'/'.$applnkname.'/report/cfdi_I_query/'.$bRecId.'/File_PDF_VP/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); } /* echo $bRecId; echo "
"; echo $authtoken_ZC; echo "
"; echo $NomArchPDF; echo "
"; echo $file_name_with_full_path; echo "
"; echo $request_url; echo "
"; echo "Parametros"; print_r($post); echo "
"; */ $post = array( // 'authtoken' => $authtoken_ZC, // 'applinkname' => $applnkname, // 'formname' => 'CreacionCFDIv33', // 'fieldname' => 'File_PDF_VP', // '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); //print_r($r); //echo "
"; curl_close ($ch); #== Se elimina los archivos de trabajo //unlink($NomArchCFDI); //unlink($NomArchPDF1); $j_array = array('code' => "200", "message" => "Proceso de creacion de CFDI fue exitoso", 'file_upload' => $NomArchPDF); $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){ $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; }