Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Hector Cardoso

POO Php CLASSE $_POST

Recommended Posts


Como deve ser feito para que um valor da super global $_POST entre em uma classe.


Já tentei várias maneiras , mas sem sucesso. Esse valor será tratado dentro da classe.



Obrigado pela atenção !


class SearchTransactionByCode

{

public static function main($transaction_code)

{

try {


/*

* #### Credentials #####

* Substitute the parameters below with your credentials (e-mail and token)

* You can also get your credentials from a config file. See an example:

* $credentials = PagSeguroConfig::getAccountCredentials();

*/



$transaction_code="5307FC6ECC46401590FDE9CE0E172B15" ; // <- este valor tem q vir pelo $_POST

// $credentials = new PagSeguroAccountCredentials("email@email.com.br",

// "68CCFF1BADBD46968030E446764E83E4");

$credentials = PagSeguroConfig::getAccountCredentials();


$transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $transaction_code);


self::printTransaction($transaction);



} catch (PagSeguroServiceException $e) {


die($e->getMessage());


}


}



public static function printTransaction(PagSeguroTransaction $transaction)

{


echo "<h2>Teste";

echo "<h3>Codigo: " . $transaction->getCode() . '</h3>';

echo "<h3>Status: " . $transaction->getStatus()->getTypeFromValue() . '</h3>';

echo "<h4>Referencia: " . $transaction->getReference() . "</h4>";


if ($transaction->getSender()) {

echo "<h4>Sender data:</h4>";

echo "Nome: " . $transaction->getSender()->getName() . '<br>';

echo "Email: " . $transaction->getSender()->getEmail() . '<br>';

if ($transaction->getSender()->getPhone()) {

echo "Phone: " . $transaction->getSender()->getPhone()->getAreaCode() . " - " .

$transaction->getSender()->getPhone()->getNumber();

}

}


if ($transaction->getItems()) {

echo "<h4>Items:</h4>";

if (is_array($transaction->getItems())) {

foreach ($transaction->getItems() as $key => $item) {

echo "Id: " . $item->getId() . '<br>'; // prints the item id, p.e. I39

echo "Desc: " . $item->getDescription() .

'<br>'; // prints the item description, p.e. Notebook prata

echo "qtda: " . $item->getQuantity() . '<br>'; // prints the item quantity, p.e. 1

echo "total: " . $item->getAmount() . '<br>'; // prints the item unit value, p.e. 3050.68

echo "<hr>";

}

}

}

/*

if ($transaction->getShipping()) {

echo "<h4>Shipping information:</h4>";

if ($transaction->getShipping()->getAddress()) {

echo "Postal code: " . $transaction->getShipping()->getAddress()->getPostalCode() . '<br>';

echo "Street: " . $transaction->getShipping()->getAddress()->getStreet() . '<br>';

echo "Number: " . $transaction->getShipping()->getAddress()->getNumber() . '<br>';

echo "Complement: " . $transaction->getShipping()->getAddress()->getComplement() . '<br>';

echo "District: " . $transaction->getShipping()->getAddress()->getDistrict() . '<br>';

echo "City: " . $transaction->getShipping()->getAddress()->getCity() . '<br>';

echo "State: " . $transaction->getShipping()->getAddress()->getState() . '<br>';

echo "Country: " . $transaction->getShipping()->getAddress()->getCountry() . '<br>';

}

echo "Shipping type: " . $transaction->getShipping()->getType()->getTypeFromValue() . '<br>';

echo "Shipping cost: " . $transaction->getShipping()->getCost() . '<br>';

}

* */


}

}


SearchTransactionByCode::main($transaction_code);


?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá Hector, o mais simples acredito que seja isso.

$transaction_code = $_POST['code'];

Pelo que vi, esse código deve ser resultado de outro methodo, você pode envia-lo via curl ou até mesmo salvá-lo em uma sessão para resgatar depois,

 

Espero que ajude, abraço

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado pela dica Rafael, mas já fiz isso antes. A primeira linha do código é:

 

$transaction_code= $_POST['code']; /// depois vem a classe. esqueci de colocar essa parte k

ele pegar e mostra mas depois do :

 

$transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $transaction_code);

não funciona mais. Me retorna isto :

[HTTP 401] - UNAUTHORIZED

 

Será q as as classes ou métodos delas, é q estão restringindo de alguma forma, ou meu código é q tá mau escrito ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tente assim. veja que adicionei uma função estática/dinamica getValue que vai capturar o post enviado.

$transaction_code = self::getValue('code');// Defina o nome corretamente

Code

<?php

require_once "../PagSeguroLibrary/PagSeguroLibrary.php";
class SearchTransactionByCode
{
    
	/**
	* Get a value from $_POST / $_GET
	* if unavailable, take a default value
	*
	* @param string $key Value key
	* @param mixed $default_value (optional)
	* @return mixed Value
	*/
	public static function getValue($key, $default_value = false)
	{
		if (!isset($key) || empty($key) || !is_string($key))
			return false;
		$ret = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : $default_value));

		if (is_string($ret) === true)
			$ret = urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($ret)));
		return !is_string($ret)? $ret : stripslashes($ret);
	}
	
	
	public static function main()
    {		
		
		$transaction_code = self::getValue('transaction_code');
		
        try {
            /*
             * #### Credentials #####
             * Replace the parameters below with your credentials
             * You can also get your credentials from a config file. See an example:
             * $credentials = PagSeguroConfig::getAccountCredentials();
             */
            // seller authentication
            $credentials = new PagSeguroAccountCredentials("vendedor@lojamodelo.com.br",
                "E231B2C9BCC8474DA2E260B6C8CF60D3");
            // application authentication
            //$credentials = PagSeguroConfig::getApplicationCredentials();
            //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3");
            $transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $transaction_code);
            self::printTransaction($transaction);
        } catch (PagSeguroServiceException $e) {
            die($e->getMessage());
        }
    }
    public static function printTransaction(PagSeguroTransaction $transaction)
    {
        echo "<h2>Transaction search by code result";
        echo "<h3>Code: " . $transaction->getCode() . '</h3>';
        echo "<h3>Status: " . $transaction->getStatus()->getTypeFromValue() . '</h3>';
        echo "<h4>Reference: " . $transaction->getReference() . "</h4>";
        echo "grossAmount: " . $transaction->getGrossAmount() . '<br>';
        echo "discountAmount: " . $transaction->getDiscountAmount() . '<br>';
        echo "installmentCount: " . $transaction->getInstallmentCount() . '<br>';
        if ($transaction->getCreditorFees()) {
            echo "<h4>CreditorFees:</h4>";
            echo "intermediationRateAmount: " . $transaction->getCreditorFees()->getIntermediationRateAmount() . '<br>';
            echo "intermediationFeeAmount: " . $transaction->getCreditorFees()->getIntermediationFeeAmount() . '<br>';
        }
        if ($transaction->getItems()) {
            echo "<h4>Items:</h4>";
            if (is_array($transaction->getItems())) {
                foreach ($transaction->getItems() as $key => $item) {
                    echo "Id: " . $item->getId() . '<br>'; // prints the item id, e.g. I39
                    echo "Description: " . $item->getDescription() .
                        '<br>'; // prints the item description, e.g. Notebook prata
                    echo "Quantidade: " . $item->getQuantity() . '<br>'; // prints the item quantity, e.g. 1
                    echo "Amount: " . $item->getAmount() . '<br>'; // prints the item unit value, e.g. 3050.68
                    echo "<hr>";
                }
            }
        }
        if ($transaction->getSender()) {
            echo "<h4>Sender data:</h4>";
            echo "Name: " . $transaction->getSender()->getName() . '<br>';
            echo "Email: " . $transaction->getSender()->getEmail() . '<br>';
            if ($transaction->getSender()->getPhone()) {
                echo "Phone: " . $transaction->getSender()->getPhone()->getAreaCode() . " - " .
                    $transaction->getSender()->getPhone()->getNumber();
            }
        }
        if ($transaction->getShipping()) {
            echo "<h4>Shipping information:</h4>";
            if ($transaction->getShipping()->getAddress()) {
                echo "Postal code: " . $transaction->getShipping()->getAddress()->getPostalCode() . '<br>';
                echo "Street: " . $transaction->getShipping()->getAddress()->getStreet() . '<br>';
                echo "Number: " . $transaction->getShipping()->getAddress()->getNumber() . '<br>';
                echo "Complement: " . $transaction->getShipping()->getAddress()->getComplement() . '<br>';
                echo "District: " . $transaction->getShipping()->getAddress()->getDistrict() . '<br>';
                echo "City: " . $transaction->getShipping()->getAddress()->getCity() . '<br>';
                echo "State: " . $transaction->getShipping()->getAddress()->getState() . '<br>';
                echo "Country: " . $transaction->getShipping()->getAddress()->getCountry() . '<br>';
            }
            echo "Shipping type: " . $transaction->getShipping()->getType()->getTypeFromValue() . '<br>';
            echo "Shipping cost: " . $transaction->getShipping()->getCost() . '<br>';
        }
    }
}
SearchTransactionByCode::main();

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.