Permite inicializar una transacción en Webpay, como respuesta a la invocación
se genera un token que representa en  forma única una transacción
170312
function initCompleteTransaction($amount, $buyOrder, $sessionId, $cardExpirationDate, $cvv, $cardNumber) {

        try {

            $wsCompleteInitTransactionInput = new wsCompleteInitTransactionInput();
            $completeCardDetail = new completeCardDetail();
            $wsCompleteTransactionDetail = new wsCompleteTransactionDetail();

            /** (Obligatorio) Indica el tipo de transacción, su valor debe ser siempre TR_COMPLETA_WS */
            $wsCompleteInitTransactionInput->transactionType = 'TR_COMPLETA_WS';
            $wsCompleteInitTransactionInput->sessionId = $sessionId;

            $wsCompleteTransactionDetail->amount = $amount;
            $wsCompleteTransactionDetail->buyOrder = $buyOrder;
            $wsCompleteTransactionDetail->commerceCode = $this->config->getCommerceCode();

            $completeCardDetail->cardExpirationDate = $cardExpirationDate;
            $completeCardDetail->cvv = $cvv;
            $completeCardDetail->cardNumber = $cardNumber;

            /** (Obligatorio) Objeto del tipo wsTransactionDetail que contiene información asociada a la tarjeta de crédito */
            $wsCompleteInitTransactionInput->cardDetail = $completeCardDetail; // cardDetails

            /** (Obligatorio) Lista de objetos del tipo wsTransactionDetail, el cual contiene datos de la transacción. Máxima cantidad de repeticiones es de 1 para este tipo de transacción */
            $wsCompleteInitTransactionInput->transactionDetails = $wsCompleteTransactionDetail; // wsTransactionDetail

            $initCompleteTransactionResponse = $this->_initCompleteTransaction(
                    array("wsCompleteInitTransactionInput" => $wsCompleteInitTransactionInput)
            );

            $xmlResponse = $this->soapClient->__getLastResponse();
            $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
            $validationResult = $soapValidation->getValidationResult();

            if ($validationResult === TRUE) {

                $wsCompleteInitTransactionOutput = $initCompleteTransactionResponse->return;
                return $wsCompleteInitTransactionOutput;
            } else {

                $error["error"] = "Error validando conexi&oacute;n a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";
                $error["detail"] = "No se pudo completar la conexi&oacute;n con Webpay";
            }
        } catch (Exception $e) {

            $error["error"] = "Error conectando a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";

            $replaceArray = array('<!--' => '', '-->' => '');
            $error["detail"] = str_replace(array_keys($replaceArray), array_values($replaceArray), $e->getMessage());
        }

        return $error;
    }
313748
def create_card
      raise StandardError, 'Cliente null' if @client.nil?
      # la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta
      card = PayuLatam::Card.new(@client)
      # hay un metodo card_params que genera el objeto a enviar con los datos correctos
      # se asignan los params correctos para la peticion
      card.params.merge! card_params

      # intento de creacion de tarjeta
      card.create!
      # si todo bien
      if card.success?
        # se llena la variable @card con la instancia de la clase PayuLatam::Card
        @card = card

        # no me acuerdo XD
        @client.remove_cards
        
        # se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente
        # es el mismo array de payu
        @client.add_card( card.response )

        # la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces
        # volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo
        _card = card.load(card.response['token'])
        # se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta
        @current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type'])
      else
        raise StandardError, "Error generando token de tarjeta: #{card.error}"
      end
    end
601925
protected function createToken()
    {
        $token = $this->getToken()->createApplicationToken(
            $this->connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID(),
            $this->connect->getSaml()->getPrivateKey()
        );
        return $token['token'];
    }
1086739
public function token()
    {
        if (session_id() == '') {
            @session_start([
                    'cookie_httponly' => true,
                    'cookie_secure'   => true
            ]);
        }
        /* On génère un token totalement unique. */
        $token                    = uniqid(rand(), true);
        //Et on le stocke
        $_SESSION[ 'token' ]      = $token;
        /* On enregistre aussi le timestamp correspondant au moment de la création du token. */
        $_SESSION[ 'token_time' ] = time();

        $this->input('token', [
            'type' => 'hidden',
            'id'   => 'token',
            'attr' => [ 'value' => $token ]
        ]);

        return $this;
    }
753133
public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
		if (!$this->access_token && !$this->checkAuth()) return false;
		$postdata = array(
				"appid"=>$this->appid,
				"appkey"=>$this->paysignkey,
				"openid"=>$openid,
				"transid"=>strval($transid),
				"out_trade_no"=>strval($out_trade_no),
				"deliver_timestamp"=>strval(time()),
				"deliver_status"=>strval($status),
				"deliver_msg"=>$msg,
		);
		$postdata['app_signature'] = $this->getSignature($postdata);
		$postdata['sign_method'] = 'sha1';
		unset($postdata['appkey']);
		$result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
		if ($result)
		{
			$json = json_decode($result,true);
			if (!$json || !empty($json['errcode'])) {
				$this->errCode = $json['errcode'];
				$this->errMsg = $json['errmsg'];
				return false;
			}
			return $json;
		}
		return false;
	}
920422
public final function beginTransaction()
    {
        //łączenie jeśli niepołączony
        if (!$this->_connected) {
            $this->connect();
        }
        //rozpoczęcie transakcji
        $this->_transactionInProgress = true;
        return $this->_upstreamPdo->beginTransaction();
    }
1306306
protected function parseTransactionAccount()
    {
        $account = parent::parseTransactionAccount();
        if ($account !== '') {
            return $account;
        }

        // IBAN
        $transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData());
        $transactionData = preg_replace('![\r\n]+!', '', $transactionData);
        if (preg_match('#/CNTP/(.*?)/#', $transactionData, $results)) {
            $account = trim($results[1]);
            if (!empty($account)) {
                return $this->sanitizeAccount($account);
            }
        }
        if (preg_match('#:86:([A-Z]{2}[\d]{2}[A-Z]{4}[\d]+?) [A-Z]{6}[A-Z0-9]{0,4} #', $transactionData, $results)) {
            $account = trim($results[1]);
            if (!empty($account)) {
                return $this->sanitizeAccount($account);
            }
        }

        return '';
    }
909109
def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
        cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
        codigo_localidad_destino, codigo_cosecha, peso_neto_carga, 
        cant_horas=None, patente_vehiculo=None, cuit_transportista=None, 
        km_a_recorrer=None, remitente_comercial_como_canjeador=None, 
        cuit_corredor=None, remitente_comercial_como_productor=None, 
        turno=None,
        **kwargs):
        ""
        # ajusto parámetros según validaciones de AFIP:
        if not cuit_canjeador or int(cuit_canjeador) == 0:
            cuit_canjeador = None         # nulo
        if not cuit_corredor or int(cuit_corredor) == 0:
            cuit_corredor = None         # nulo
        if not remitente_comercial_como_canjeador:
            remitente_comercial_como_canjeador = None
        if not remitente_comercial_como_productor:
            remitente_comercial_como_productor = None
        if turno == '':
            turno  = None                # nulo

        ret = self.client.solicitarCTGInicial(request=dict(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuitRepresentado': self.Cuit, },
                         datosSolicitarCTGInicial=dict(
                            cartaPorte=numero_carta_de_porte, 
                            codigoEspecie=codigo_especie,
                            cuitCanjeador=cuit_canjeador or None, 
                            remitenteComercialComoCanjeador=remitente_comercial_como_canjeador,
                            cuitDestino=cuit_destino, 
                            cuitDestinatario=cuit_destinatario, 
                            codigoLocalidadOrigen=codigo_localidad_origen,
                            codigoLocalidadDestino=codigo_localidad_destino, 
                            codigoCosecha=codigo_cosecha, 
                            pesoNeto=peso_neto_carga, 
                            cuitTransportista=cuit_transportista,
                            cantHoras=cant_horas,
                            patente=patente_vehiculo, 
                            kmARecorrer=km_a_recorrer,
                            cuitCorredor=cuit_corredor,
                            remitenteComercialcomoProductor=remitente_comercial_como_productor,
                            turno=turno,
                            )))['response']
        self.__analizar_errores(ret)
        self.Observaciones = ret['observacion']
        datos = ret.get('datosSolicitarCTGResponse')
        if datos:
            self.CartaPorte = str(datos['cartaPorte'])
            datos_ctg = datos.get('datosSolicitarCTG')
            if datos_ctg:
                self.NumeroCTG = str(datos_ctg['ctg'])
                self.FechaHora = str(datos_ctg['fechaEmision'])
                self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
                self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
                self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
            self.__analizar_controles(datos)
        return self.NumeroCTG or 0
554571
public function preAuthCode() {
        $key = 'WeChatThirdPreAuthCode';
        if (Factory::cache()->has($key)) {
            return Factory::cache()->get($key);
        }
        $args = $this->getPreAuthCode()->json();
        if (!is_array($args)) {
            throw new \Exception('HTTP ERROR!');
        }
        if (!array_key_exists('pre_auth_code', $args)) {
            throw new \Exception(isset($args['errmsg']) ? $args['errmsg'] : 'GET ACCESS TOKEN ERROR!');
        }
        Factory::cache()->set($key, $args['pre_auth_code'], $args['expires_in']);
        return $args['pre_auth_code'];
    }
48102
public function token()
    {
        try {
            $response = $this->oauthServer->respondToAccessTokenRequest($this->request, new Response());

            $this->pruneTokens();

            return $response;
        } catch (\Exception $e) {
            // Rethrow the exception
            throw $e;
        }
    }
944005
public function getNewToken()
    {
        $post = array(
            'auth' => array(
                'username' => $this->username,
                'password' => $this->password,
            ),
        );
        return $this->http->call(HttpMethod::POST, $this->host.'/auth', $post)->token;
    }
873182
protected function verifyPayment()
	{
		try {
			$soap = new SoapClient($this->serverUrl);

			$result = $soap->CheckRequestStatusResult(
				$this->transactionId(),
				$this->config->get('gateway.sadad.merchant'),
				$this->config->get('gateway.sadad.terminalId'),
				$this->config->get('gateway.sadad.transactionKey'),
				$this->refId(),
				$this->amount
			);

		} catch (\SoapFault $e) {
			$this->transactionFailed();
			$this->newLog('SoapFault', $e->getMessage());
			throw $e;
		}

		if (empty($result) || !isset($result->AppStatusCode))
			throw new SadadException('در دریافت اطلاعات از بانک خطایی رخ داده است.');

		$statusResult = strval($result->AppStatusCode);
		$appStatus = strtolower($result->AppStatusDescription);

		$message = $this->getMessage($statusResult, $appStatus);

		$this->newLog($statusResult, $message['fa']);

		if ($statusResult != 0 || $appStatus !== 'commit') {
			$this->transactionFailed();
			throw new SadadException($message['fa'], $statusResult);
		}
		$this->trackingCode = $result->TraceNo;
		$this->cardNumber = $result->CustomerCardNumber;
		$this->transactionSucceed();
	}
758562
def GenerarRemito(self, id_req, archivo="qr.png"):
        ""
        if not self.remito['arrayContingencias']:
            del self.remito['arrayContingencias']
        response = self.client.generarRemito(
                                authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
                                idReq=id_req, remito=self.remito) 
        ret = response.get("generarRemitoReturn")
        if ret:
            self.__analizar_errores(ret)
            self.__analizar_observaciones(ret)
            self.__analizar_evento(ret)
            self.AnalizarRemito(ret, archivo)
        return bool(self.CodRemito)
879171
function acknowledgeTransaction($token) {

        $acknowledgeTransaction = new acknowledgeTransaction();
        $acknowledgeTransaction->tokenInput = $token;
        $acknowledgeTransactionResponse = $this->_acknowledgeTransaction($acknowledgeTransaction);

        $xmlResponse = $this->soapClient->__getLastResponse();
        $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
        $validationResult = $soapValidation->getValidationResult();
        return $validationResult === TRUE;
    }
620736
public function processPayboxRequest()
    {
        // The response code to the server
        $request = $this->getRequest();

        $this->getLog()->addInfo(
            $this->getTranslator()->trans(
                "Paybox platform request received.",
                [],
                Paybox::MODULE_DOMAIN
            )
        );

        $orderId = 0;
        $orderReference = $this->getTranslator()->trans('UNDEFINED', [], Paybox::MODULE_DOMAIN);

        $orderStatus = $this->getTranslator()->trans('UNKNOWN', [], Paybox::MODULE_DOMAIN);

        $payboxRequestValues = [];

        $variables = explode(';', Paybox::PARAMETRES_RETOUR);

        foreach ($variables as $variable) {
            list($nom, $dummy) = explode(':', $variable);

            $payboxRequestValues[$nom] = $request->get($nom);
        }

        // Vérification de la signature
        $stringParam = '';

        foreach ($payboxRequestValues as $key => $value) {
            // Ignore sign parameter
            if ($key == 'sign') {
                continue;
            }
            
            $stringParam .= "&".$key.'='.$value;
        }

        $stringParam = ltrim($stringParam, '&');

        $signature = base64_decode($request->get('sign'));

        // Charger le fichier qui contient la clef publique de Paybox
        $publicKeyFile = __DIR__ . DS . '..' . DS . 'Config' . DS . 'clef-publique-paybox.pem';

        if (false !== $publicKeyData = file_get_contents($publicKeyFile)) {
            $publicKey = openssl_pkey_get_public($publicKeyData);

            if (openssl_verify($stringParam, $signature, $publicKey)) {
                // L'ID de transaction passé est l'ID de la commande
                $orderId = intval($payboxRequestValues['ref']);

                $orderStatus = $this->getTranslator()->trans('NOT PAID', [], Paybox::MODULE_DOMAIN);

                if (null !== $order = $this->getOrder($orderId)) {
                    $orderReference = $order->getRef();

                    $codeRetour = $payboxRequestValues['erreur'];

                    // Check payment status
                    if ($codeRetour == '00000') {
                        $orderStatus = $this->getTranslator()->trans('PAID', [], Paybox::MODULE_DOMAIN);

                        if (!$order->isPaid()) {
                            $this->confirmPayment($orderId);

                            $message = $this->getTranslator()->trans(
                                "Order ID %id is confirmed.",
                                [ '%id' => $orderId ],
                                Paybox::MODULE_DOMAIN
                            );
                        } else {
                            $message = $this->getTranslator()->trans(
                                "Order ID %id already paid, message ignored.",
                                [ '%id' => $orderId ],
                                Paybox::MODULE_DOMAIN
                            );
                        }
                    } else {
                        $message = $this->getTranslator()->trans(
                            "Order cannot be confirmed, Paybox returned error %num: %text",
                            [
                                '%num' => $codeRetour,
                                '%text' => $this->getTextualMessage($codeRetour)
                            ],
                            Paybox::MODULE_DOMAIN
                        );
                    }
                } else {
                    $message = $this->getTranslator()->trans(
                        "Order ID %id was not found. Transaction reference is '%ref'.",
                        [ '%id' => $orderId, '%ref' =>  $payboxRequestValues['ref']],
                        Paybox::MODULE_DOMAIN
                    );
                }
            } else {
                $message = $this->getTranslator()->trans(
                    "Request parameters signature verification failed.",
                    [],
                    Paybox::MODULE_DOMAIN
                );
            }
        } else {
            $message = $this->getTranslator()->trans(
                "Failed to open %file, please check Paybox configuration",
                [ '%file' => $publicKeyFile ],
                Paybox::MODULE_DOMAIN
            );
        }

        $this->getLog()->addInfo($message);

        $this->getLog()->info(
            $this->getTranslator()->trans(
                "Paybox platform request processing terminated.",
                [],
                Paybox::MODULE_DOMAIN
            )
        );

        $this->sendPaymentNotification($orderId, $orderReference, $orderStatus, $message);

        return Response::create('');
    }
142529
def AjustarLiquidacion(self):
        ""
        # limpio los elementos que no correspondan por estar vacios:
        for item_liq in self.solicitud['itemDetalleAjusteLiquidacion']:
            campo = 'ajusteCompraAsociada'
            if campo in item_liq and not item_liq[campo]:
                del item_liq[campo]
        for campo in self.solicitud.get('ajusteFinanciero', {}).copy():
            if not self.solicitud['ajusteFinanciero'][campo]:
                del self.solicitud['ajusteFinanciero'][campo]
        # llamo al webservice:
        ret = self.client.generarAjuste(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuit': self.Cuit, },
                        solicitud=self.solicitud,
                        )
        # analizo la respusta
        ret = ret['respuesta']
        self.__analizar_errores(ret)
        self.AnalizarLiquidacion(ret)
        return True
1205269
def ConsultarTiposComprobante(self, sep="||"):
        ""
        ret = self.client.consultarTiposComprobante(
                            authRequest={
                                'token': self.Token, 'sign': self.Sign,
                                'cuitRepresentada': self.Cuit, },
                                )['consultarTiposComprobanteReturn']
        self.__analizar_errores(ret)
        array = ret.get('arrayTiposComprobante', [])
        lista = [it['codigoDescripcion'] for it in array]
        return [(u"%s {codigo} %s {descripcion} %s" % (sep, sep, sep)).format(**it) if sep else it for it in lista]