"Doesn't matter how you do, what really matters is the result."

Gateway de Pagamento Cielo ASP.net C#

Posted: June 28th, 2011 | Author: admin | Filed under: blog | No Comments »

Olá Amigos,

Estive envolvido com uma situação fora do comum do meu dia-a-dia.
Faltando menos de 6 dias para que a Cielo não processase mais pedidos que não utilizassem o gateway proprio deles, me foi passado que eu deveria migrar os gateways de uma aplicação financeira de Moset para a Cielo, em .Net com C#.

A cielo manda uma loja de exemplo usando PHP e Java, mas não é o meu caso e isso complicou minha vida.

Enfim, não teria nenhum problema para fazer a alteração se fosse PHP, mas não utiliza-se PHP nesta aplicação e nem adianta querer fazer o PHP rodar no IIS (que sei que roda perfeitamente) pois a empresa responsável pelo servidor (nós mesmos) possui várias outras aplicações que rodam neste mesmo ambiente, e que como não sabemos com facilidade (sem demandar muito tempo para descobrir) o impacto em qualquer modificação na configuração do IIS.

Não teria nenhum problema se:

1. Fosse PHP (minha especialidade) mas não é.
2. Fosse Java (meu dia-a-dia e minha futura especialidade ) mas não é.
3. Fosse necessário apenas algumas alterações no código atual, mas não é.

Resumindo, é necessário fazer de novo, porque a comunicação antiga da Moset, não se dava via XML (pelo menos na minha situação) e logo todo o código produzido deveria ser jogado fora.

Foi apartir dai, que comecei então a desenvolver o novo código ontem, e após alguns testes e a algumas vasculhadas nas comunidades .Net que falavam sobre XML que eu cheguei ao código atual.

O código que estou postando, deixo claro, que não é o 100% ideal, e que irei aprimorar ele devidamente nos próximos dias, mas é oque tem para hoje, ja que amanhã é o último dia para homologar o sistema.

Quem quiser ajudar, mandar dicas, aprimorar o código, estamos aceitando, a ideia é de que tenhamos um código bacana aqui disponivel para todos. O meu final sera postado nos próximos dias.

<%@ Page language="C#" %>

    <%

        //globais

        string dadosPortadorNumero = "4551870000000183";
        string dadosPortadorVal = "201508";
        string dadosPortadorInd = "1";
        string dadosPortadorCodSeg = "973";
        string dadosPortadorNome = "";

        string dadosPedidoNumero = "1225554887884389";
        string dadosPedidoValor = "100000";
		string dadosPedidoMoeda = "986";
        string dadosPedidoData = "2011-06-27T17:23:19";
        string dadosPedidoDescricao = "";
		string dadosPedidoIdioma = "PT";

        string formaPagamentoBandeira = "visa";
        string formaPagamentoProduto = "1";
		string formaPagamentoParcelas = "1";

		string urlRetorno = "Return.aspx";
        string autorizar = "3";
        string capturar = "0";

		string tid;
		string status;
		string urlAutenticacao;

        string dadosEcNumero = "1006993069";
        string dadosEcChave = "25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3";

        string XMLDadosEc = "\n";
                XMLDadosEc += ("");
                XMLDadosEc += (dadosEcNumero);
                XMLDadosEc += ("\n");
                XMLDadosEc += ("");
                XMLDadosEc += (dadosEcChave);
                XMLDadosEc += ("\n");
                XMLDadosEc += ("\n");

        string XMLFormaPagamento = "
";
                XMLFormaPagamento += ("\n");
                XMLFormaPagamento += (formaPagamentoBandeira);
                XMLFormaPagamento += ("");
                XMLFormaPagamento += ("
\n");
                XMLFormaPagamento += (formaPagamentoProduto);
                XMLFormaPagamento += ("");
                XMLFormaPagamento += ("
\n");
                XMLFormaPagamento += (formaPagamentoParcelas);
                XMLFormaPagamento += ("");
                XMLFormaPagamento += ("\n");

        string XMLDadosPortador = "\n";
			    XMLDadosPortador += ("");
				XMLDadosPortador += (dadosPortadorNumero);
				XMLDadosPortador += ("\n");
				XMLDadosPortador += ("");
				XMLDadosPortador += (dadosPortadorVal);
				XMLDadosPortador += ("\n");
				XMLDadosPortador += ("");
				XMLDadosPortador += (dadosPortadorInd);
				XMLDadosPortador += ("\n");
				XMLDadosPortador += ("");
			    XMLDadosPortador += (dadosPortadorCodSeg);
                XMLDadosPortador += ("\n");
                XMLDadosPortador += ("\n");

			// Verifica se Nome do Portador foi informado                

        string XMLDadosPedido = "\n";
				XMLDadosPedido += ("");
                XMLDadosPedido += (dadosPedidoNumero);
				XMLDadosPedido += ("\n");
				XMLDadosPedido += ("");
				XMLDadosPedido += (dadosPedidoValor);
				XMLDadosPedido += ("\n");
				XMLDadosPedido += ("");
				XMLDadosPedido += (dadosPedidoMoeda);
				XMLDadosPedido += ("\n");
				XMLDadosPedido += ("");
				XMLDadosPedido += (dadosPedidoData);
				XMLDadosPedido += ("\n");
                XMLDadosPedido += ("");

        string XMLRetorno = "\n";
                XMLRetorno += (urlRetorno);
                XMLRetorno += ("");

        string XMLAutorizar = "\n";
                XMLAutorizar += (autorizar);
                XMLAutorizar += ("\n");

        string XMLCapturar = "\n";
                XMLCapturar += (capturar);
                XMLCapturar += ("");

        // requisição
        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "mensagem=";
        postData += ("");
        postData += (XMLDadosEc);
        postData += (XMLDadosPortador);
        postData += (XMLDadosPedido);
        postData += (XMLFormaPagamento);
        postData += (XMLRetorno);
        postData += (XMLAutorizar);
        postData += (XMLCapturar);
        postData += ("");

        byte[] data = encoding.GetBytes(postData);

        // Prepare web request...
        System.Net.HttpWebRequest myRequest =
          (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.ContentLength = data.Length;
        System.IO.Stream newStream = myRequest.GetRequestStream();
        // Send the data.

        newStream.Write(data, 0, data.Length);
        newStream.Close();

        // getting to text
        System.Net.WebResponse response = myRequest.GetResponse();
        System.IO.Stream responseStream = response.GetResponseStream();

        System.Text.Encoding myencoding = System.Text.Encoding.Default;
        System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, myencoding);

        Char[] charBuffer = new Char[256];
        int count = reader.Read(charBuffer, 0, charBuffer.Length);
        StringBuilder Dados = new StringBuilder();

        while (count > 0)
        {
            Dados.Append(new String(charBuffer, 0, count));
            count = reader.Read(charBuffer, 0, charBuffer.Length);
        }

        Response.Write("");

    %>

Todas as informações acima como cartão, código de segurança, chave, etc… esta na documentação da Cielo que pode ser baixada no link abaixo:

http://200.183.118.67/kit.ecommerce.cielo.zip

Ajuda do amigo William Fabricio Werling

Como muitos me perguntaram e eu não soube responder, aqui vai uma ajuda do nosso amigo William Fabricio Werling.

Para aqueles que por algum motivo o script não funciona (a pagina da cielo não poder ser acessada), da timeout, e etc… (problemas de conectividade com a cielo) a solução é esta:

httpWebRequest.Proxy = HttpWebRequest.GetSystemWebProxy();
httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

agradeçam ao William !

Abraço a todos!


PHP and OOP

Posted: May 15th, 2010 | Author: admin | Filed under: blog | 6 Comments »

Hi guys !

Today I’m coming with some very basic OOP tutorial to PHP.

The question is that many people listening about OOP but don’t know why to use it, if in the end, the final product will be the same, same features, same final interface, layout etc…

the question is that many people don’t know that OOP is used in the big companies, and is the most professional way to work with many other programming languages, like a default. by example, Java and .Net.

I’ll show you WHY OOP is more professional and clean. Int the beginning you will think you’re writing more code on OOP, but you will see that will be much more easy to understand your code, you will have less code in your pages, just calling classes and setting methods, and of course, will be much more easy to keep working in new implamentations on your code alone, or with a team of guys working together.

Imagine I’m going to add an user to my website using procedural way. I would have:

$name = "fernando";
$city = "Los Angeles";
$state = "CA";
$zipcode = "87795";

$sql = "insert into users (name,city,state,zipcode) values ('$name','$city','$state','$zipcode');

$gosql = mysql_query($sql) or die ("SQL Error: ".mysql_error());

This example shows in procedural, how this could be done. But imagine that you would need to use this lines in every page that you would need to add an user. I know that to a sign up, this just exist in a unique place. But exist other situations that we do the same thing in many pages, and we copy and paste codes in many time.

My tutorial, will be a very simple example of how to do the same Procedural code above, but using OOP.

If you will like more procedural, no problem. if you work alone, keep with procedural.. but the companies are asking for

OOP ;)

Starting

I’ll have a Class called Users, with the Get and Set methods.

So let’s start.

class User {

var $name; // string
var $city; // string
var $state; // string
var $zipcode; // integer

function setName($name){

$this->name = $name;

}

function setCity($city){

$this->city = $city;

}

function setState($state){

$this->state = $state;

}

function setZipcode($zipcode){

$this->zipcode = $zipcode;

}

function getName(){

return $this->name;

}

function getCity(){

return $this->city;

}

function getState(){

return $this->state;

}

function getZipcode(){

return $this->zipcode;

}

}

This is the basic structure of our class.

Now, imagine you will include a new User on your database, right ? so we need to start our class, and to fill data into it. here we go.


$newuser = new User();
$newuser->setName("fernando");
$newuser->setCity("Los Angeles");
$newuser->setState("CA");
$newuser->setZipcode("87975");

here we inserted data on our class, we can see if our class is with the data correctly, printing the var $newuser on the screen, we will see that:

echo "<pre>";
print_r($newuser);

the code above, return this data:
user Object

(
[name] => fernando
[city] => Los Angeles
[state] => CA
[zipcode] => 87975
)

So here we can see a User Object, with an array, right ? really simple =)

So u tell me: Ok fernando, from now on, I know how to get this data. I can just get it doing that:


$newuser[name] or $newuser[0]

So I say that now, you can access a object data at this way, you need to use this: ->

see here how I would show just the Name data:

echo $newuser->name;

you will see: Fernando

very easy right ?

So when you need to send the new user information to another class or to another method that isn’t inside the User class, you can send the object, and there you get the data.. example:

class Database{

function saveUser($object){

$sql = "insert into Users (name,city,state,zipcode) values ('$object->name','$object->city','$object->state','$object->zipcode')";

}

}

$database = new Database();

$database->saveUser($newuser);

Explaining…

I created a new class, a database class, where we will have a method that save a new user.

When I call this method, I send my Object $newuser that we filled before, and I access the right data properties ready inside my saveUser object.

So here is the whole example code:

Hope it be useful.

class User {

var $name; // string
var $city; // string
var $state; // string
var $zipcode; // integer

function setName($name){
$this->name = $name;
}

function setCity($city){
$this->city = $city;
}

function setState($state){

$this->state = $state;

}

function setZipcode($zipcode){

$this->zipcode = $zipcode;

}

function getName(){

return $this->name;

}

function getCity(){

return $this->city;

}

function getState(){

return $this->state;

}

function getZipcode(){

return $this->zipcode;

}

}

class Database{

function saveUser($object){

$sql = "insert into Users (name,city,state,zipcode) values ('$object->name','$object->city','$object->state','$object->zipcode')";

echo $sql;

}

}

$newuser = new User();
$newuser->setName("fernando");
$newuser->setCity("Los Angeles");
$newuser->setState("CA");
$newuser->setZipcode("87975");
$database = new Database();
$database->saveUser($newuser);

Thanks and until the next !