Gateway/Moip.pm untested

filter: Statementstmt 0.0% 0 / 245 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 474 CC 64 SCAR 49.4
CC
64
Cov
0%
add_entrega
342.0
add_pagador
240.0
add_boleto
132.0
CRAP 139.9
1 package Business::CPI::Gateway::Moip;
2 use Moo;
3 use MIME::Base64;
4 use Carp 'croak';
5 use bareword::filehandles;
6 use indirect;
7 use multidimensional;
8 use HTTP::Tiny;
9 use Data::Dumper;
10 extends 'Business::CPI::Gateway::Base';
11  
12 our $VERSION = '0.05';
13  
14 =pod
15  
16 =encoding utf-8
17  
18 =head1 NAME
19  
20 Business::CPI::Gateway::Moip - Inteface para pagamentos Moip
21  
22 =head1 SYNOPSIS
23  
24 use Data::Printer;
25 use Business::CPI::Buyer::Moip;
26 use Business::CPI::Cart::Moip;
27 use Business::CPI::Gateway::Moip;
28  
29 my $cpi = Business::CPI::Gateway::Moip->new(
30 currency => 'BRL',
31 sandbox => 1,
32 token_acesso => 'YC110LQX7UQXEMQPLYOPZ1LV9EWA8VKD',
33 chave_acesso => 'K03JZXJLOKJNX0CNL0NPGGTHTMGBFFSKNX6IUUWV',
34 receiver_email => 'teste@oemail.com.br',
35 receiver_label => 'Nome Cliente ou Loja',
36 id_proprio => 'ID_INTERNO_'.int rand(int rand(99999999)),
37  
38 );
39  
40 my $cart = $cpi->new_cart({
41 buyer => {
42 name => 'Mr. Buyer',
43 email => 'sender@andrewalker.net',
44 address_street => 'Rua das Flores',
45 address_number => '360',
46 address_district => 'Vila Mariana',
47 address_complement => 'Ap 35',
48 address_city => 'São Paulo',
49 address_state => 'SP',
50 address_country => 'Brazil',
51 address_zip_code => '04363-040',
52 phone => '11-9911-0022',
53 id_pagador => 'O11O22X33X',
54 },
55 mensagens => [
56 'Produto adquirido no site X',
57 'Total pago + frete - Preço: R$ 144,10',
58 'Mensagem linha3',
59 ],
60 boleto => {
61 expiracao => {
62 dias => 7,
63 tipo => 'corridos', #ou uteis
64 },
65 data_vencimento => '2012/12/30T24:00:00.0-03:00',
66 instrucao1 => 'Primeira linha de instrução de pagamento do boleto bancário',#OPT
67 instrucao2 => 'Segunda linha de instrução de pagamento do boleto bancário', #OPT
68 instrucao3 => 'Terceira linha de instrução de pagamento do boleto bancário',#OPT
69 logo_url => 'http://www.nixus.com.br/img/logo_nixus.png', #OPT
70 },
71 formas_pagamento => [
72 'BoletoBancario',
73 'CartaoDeCredito',
74 'DebitoBancario',
75 'CartaoDeDebito',
76 'FinanciamentoBancario',
77 'CarteiraMoIP',
78 ],
79 url_retorno => 'http://www.url_retorno.com.br',
80 url_notificacao => 'http://www.url_notificacao.com.br',
81 entrega => {
82 destino => 'MesmoCobranca',
83 calculo_frete => [
84 {
85 tipo => 'proprio', #ou correios
86 valor_fixo => 2.30, #ou valor_percentual
87 prazo => {
88 tipo => 'corridos', #ou uteis
89 valor => 2,
90 }
91 },
92 {
93 tipo => 'correios',
94 valor_percentual => 12.30,
95 prazo => {
96 tipo => 'corridos',#ou uteis
97 valor => 2,
98 },
99 correios => {
100 peso_total => 12.00,
101 forma_entrega => 'Sedex10', #ou sedex sedexacobrar sedexhoje
102 mao_propria => 'PagadorEscolhe', #ou SIM ou NAO
103 valor_declarado => 'PagadorEscolhe', #ou SIM ou NAO
104 aviso_recebimento => 'PagadorEscolhe', # ou SIM ou NAO
105 cep_origem => '01230-000',
106 },
107 },
108 {
109 tipo => 'correios',
110 valor_percentual => 12.30,
111 prazo => {
112 tipo => 'corridos',#ou uteis
113 valor => 2,
114 },
115 correios => {
116 peso_total => 12.00,
117 forma_entrega => 'Sedex10', #ou sedex sedexacobrar sedexhoje
118 mao_propria => 'PagadorEscolhe', #ou SIM ou NAO
119 valor_declarado => 'PagadorEscolhe', #ou SIM ou NAO
120 aviso_recebimento => 'PagadorEscolhe', # ou SIM ou NAO
121 cep_origem => '01230-000',
122 },
123 },
124 ]
125 }
126 },
127 );
128  
129 my $item = $cart->add_item({
130 id => 2,
131 quantity => 1,
132 price => 222,
133 description => 'produto2',
134 });
135  
136 my $item = $cart->add_item({
137 id => 1,
138 quantity => 2,
139 price => 111,
140 description => 'produto1',
141 });
142  
143 my $res = $cpi->make_xml_transaction( $cart );
144  
145 Return on success:
146 $res = {
147 code "SUCCESS",
148 id 201301231157322850000001500872,
149 token "C2R0A1V3K0P132J3Q1C1S5M7R3N2P2N8B5L0Q0M0J05070U1W5K0P018D7T2"
150 }
151  
152 Return on error:
153 $res = {
154 code "ERROR",
155 raw_error "<ns1:EnviarInstrucaoUnicaResponse xmlns:ns1="http://www.moip.com.br/ws/alpha/"><Resposta><ID>201301231158069350000001500908</ID><Status>Falha</Status><Erro Codigo="2">O valor do pagamento deverá ser enviado obrigator
156 iamente</Erro></Resposta></ns1:EnviarInstrucaoUnicaResponse>"
157 }
158  
159 =head1 EXAMPLE USING Business:CPI
160  
161 The following example will use Business::CPI directly
162  
163 use Business::CPI;
164 use Data::Printer;
165  
166 my $moip = Business::CPI->new(
167 gateway => "Moip",
168 sandbox => 1,
169 token_acesso => 'YC110LQX7UQXEMQPLYOPZ1LV9EWA8VKD',
170 chave_acesso => 'K03JZXJLOKJNX0CNL0NPGGTHTMGBFFSKNX6IUUWV',
171 receiver_email => 'teste@oemail.com.br',
172 receiver_label => 'Nome Cliente ou Loja',
173 id_proprio => 'ID_INTERNO_'.int rand(int rand(99999999)),
174 );
175  
176 my $cart = $moip->new_cart({
177 buyer => {
178 name => 'Mr. Buyer',
179 email => 'sender@andrewalker.net',
180 address_street => 'Rua das Flores',
181 address_number => '360',
182 address_district => 'Vila Mariana',
183 address_complement => 'Ap 35',
184 address_city => 'São Paulo',
185 address_state => 'SP',
186 address_country => 'BRA',
187 address_zip_code => '04363-040',
188 phone => '11-9911-0022',
189 id_pagador => 'O11O22X33X',
190 }
191 });
192  
193 $cart->parcelas([
194 {
195 parcelas_min => 2,
196 parcelas_max => 6,
197 juros => 2.99,
198 },
199 {
200 parcelas_min => 7,
201 parcelas_max => 12,
202 juros => 10.99,
203 },
204 ]);
205  
206 my $item = $cart->add_item({
207 id => 2,
208 quantity => 1,
209 price => 222,
210 description => 'produto2',
211 });
212  
213 my $item = $cart->add_item({
214 id => 1,
215 quantity => 2,
216 price => 111,
217 description => 'produto1',
218 });
219  
220 my $res = $moip->make_xml_transaction( $cart );
221 warn p $res;
222  
223 =head1 MOIP DOCUMENTATION REFERENCE
224  
225 http://labs.moip.com.br
226  
227 http://labs.moip.com.br/referencia/minuto/
228  
229 http://labs.moip.com.br/referencia/pagamento_parcelado/
230  
231 =head1 SANDBOX
232  
233 Register yourself in the Moip sandbox: http://labs.moip.com.br/
234  
235 =head1 DESCRIPTION
236  
237 Business::CPI::Gateway::Moip allows you to make moip transactions using Business::CPI standards.
238  
239 Currently, Moip uses XML format for transactions.
240  
241 This module will allow you to easily create a cart with items and buyer infos and payment infos. And, after setting up all this information, you will be able to:
242  
243 ->make_xml_transaction
244  
245 and register your transaction within moip servers to obtain a moip transaction tokenid.
246  
247 ** make_xml_transaction will return a TOKEN and code SUCCESS upon success. You will need this info so your user can checkout afterwards.
248  
249 * see the tests for examples
250  
251 =head1 MOIP TRANSACTION FLOW
252  
253 Here, ill try to describe how the moip transaction flow works:
254  
255 1. You post the paymentXML to the moip servers
256 2. Moip returns a transaction token id upon success
257  
258 Then, you have 2 options for checkout:
259  
260 - option1 (send the user to moip site to finish transaction):
261 - 3. You redirect your client to moip servers passing the transaction token id
262  
263 - option2 (use the moip transaction id and some javascript for checkout):
264 3. You use some javascript with the transaction token id
265  
266 4. Your client pays
267  
268 =head1 CRUDE EXAMPLE
269  
270 Ive prepared this example just in case you want to test the moip payment sistem without using any other module.
271 The following snippet uses only HTTP::Tiny to register the moip transaction.
272  
273 my $conteudo = <<'XML';
274 <EnviarInstrucao>
275 <InstrucaoUnica>
276 <Razao>Pagamento com HTTP Tiny</Razao>
277 <Valores>
278 <Valor moeda='BRL'>1.50</Valor>
279 </Valores>
280 <Pagador>
281 <IdPagador>cliente_id</IdPagador>
282 </Pagador>
283 </InstrucaoUnica>
284 </EnviarInstrucao>
285 XML
286 my $res = HTTP::Tiny->new( verify_SSL => $self->verify_ssl )->request(
287 'POST',
288 $self->api_url,
289 {
290 headers => {
291 'Authorization' => 'Basic ' . MIME::Base64::encode($self->token_acesso.":".$self->chave_acesso,''),
292 'Content-Type' => 'application/x-www-form-urlencoded',
293 },
294 content => $conteudo,
295 }
296 );
297 warn p $res;
298  
299 =cut
300  
301  
302 =head1 ATTRIBUTES
303  
304 =head2 sandbox
305  
306 Indicates whether or not this module will use the sandbox url or production url.
307  
308 =cut
309  
310 has sandbox => (
311 is => 'rw',
312 default => sub { return 0 },
313 );
314  
315 =head2 api_url
316  
317 Holds the api_url. You DONT need to pass it, it will figure out its own url based on $self->sandbox
318  
319 =cut
320  
321 has 'api_url' => (
322 is => 'rw',
323 );
324  
325 =head2 token_acesso
326  
327 Moip token
328  
329 =cut
330  
331 has token_acesso => (
332 is => 'rw',
333 required => 1,
334 );
335  
336 =head2 chave_acesso
337  
338 Moip access-key
339  
340 =cut
341  
342 has chave_acesso => (
343 is => 'rw',
344 required => 1,
345 );
346  
347 =head2 id_proprio
348  
349 Your own internal transaction id.
350 ie. e39jd2390jd92d030000001
351  
352 =cut
353  
354 has id_proprio => (
355 is => 'rw',
356 );
357  
358 =head2 receiver_label
359  
360 Name that will receive this payment
361 ie. My Store Name
362  
363 =cut
364  
365 has receiver_label => ( #to print the store name on the paypment form
366 is => 'rw',
367 );
368  
369 =head2 receiver_email
370  
371 Email that will receive this payment
372 ie. sales@mystore.com
373  
374 =cut
375  
376 has receiver_email => ( #to print the sotre name on the paypment form
377 is => 'rw',
378 );
379  
380 =head2 ua
381  
382 Uses HTTP::Tiny as useragent
383  
384 =cut
385  
386 has ua => (
387 is => 'rw',
388 default => sub { HTTP::Tiny->new() },
389 );
390  
391 =head1 METHODS
392  
393 =cut
394  
395 sub BUILD {
396 my $self = shift;
397 if ( $self->sandbox ) {
398 $self->api_url('https://desenvolvedor.moip.com.br/sandbox/ws/alpha/EnviarInstrucao/Unica');
399 } else {
400 $self->api_url('https://www.moip.com.br/ws/alpha/EnviarInstrucao/Unica');
401 }
402 };
403  
404 =head2 make_xml_transaction
405  
406 Registers the transaction on the Moip servers.
407  
408 Receives an $cart, generates the XML and register the transaction on the Moip Server.
409  
410 Returns the moip transaction token upon success.
411  
412 Returns the full raw_error when fails.
413  
414 Return on success:
415  
416 {
417 code "SUCCESS",
418 id 201301231157322850000001500872,
419 token "C2R0A1V3K0P132J3Q1C1S5M7R3N2P2N8B5L0Q0M0J05070U1W5K0P018D7T2"
420 }
421  
422 Return on error:
423  
424 {
425 code "ERROR",
426 raw_error "<ns1:EnviarInstrucaoUnicaResponse xmlns:ns1="http://www.moip.com.br/ws/alpha/"><Resposta><ID>201301231158069350000001500908</ID><Status>Falha</Status><Erro Codigo="2">O valor do pagamento deverá ser enviado obrigator
427 iamente</Erro></Resposta></ns1:EnviarInstrucaoUnicaResponse>"
428 }
429  
430 =cut
431  
432 sub make_xml_transaction {
433 my ( $self, $cart ) = @_;
434 my $xml = $self->payment_to_xml( $cart );
435 #warn $xml;
436 $self->log->debug("moip-xml: " . $xml);
437 my $res = $self->ua->request(
438 'POST',
439 $self->api_url,
440 {
441 headers => {
442 'Authorization' =>
443 'Basic ' .
444 MIME::Base64::encode($self->token_acesso.":".$self->chave_acesso,''),
445 'Content-Type' => 'application/x-www-form-urlencoded',
446 },
447 content => $xml,
448 }
449 );
450 my $final_res = {};
451 if ( $res->{content} =~ m|\<Status\>Sucesso\</Status\>|mig ) {
452 $final_res->{ code } = 'SUCCESS';
453 #pega token:
454 my ( $token ) = $res->{content} =~ m|\<Token\>([^<]+)\</Token\>|mig;
455 $final_res->{ token } = $token if defined $token;
456 #pega id:
457 my ( $id ) = $res->{content} =~ m|\<ID\>([^<]+)\</ID\>|mig;
458 $final_res->{ id } = $id if defined $id;
459 } else {
460 $final_res->{ code } = 'ERROR';
461 $final_res->{ raw_error } = $res->{ content };
462 }
463 return $final_res;
464 }
465  
466 =head2 notify
467  
468 Not implemented yet for Moip
469  
470 =cut
471  
472 sub notify {
473 my ( $self, $req ) = @_;
474 }
475  
476 =head2 payment_to_xml
477  
478 Generates an XML with the information in $cart and other attributes ie. receiver_label, id_proprio, buyer email, etc
479  
480 returns the Moip XML format
481  
482 =cut
483  
484 sub payment_to_xml {
485 my ( $self, $cart ) = @_;
486 #TODO:
487 #http://labs.moip.com.br/parametro/Recebedor/
488 #é so implementar no CPI::Cart::Moip e incluir aqui no xml abaixo com as devidas validacoes
489  
490 $self->log->debug("\$cart: " . Dumper( $cart));
491 $self->log->debug("\$cart->buyer: " . Dumper( $cart->buyer));
492  
493 my $xml;
494  
495 $xml = "<EnviarInstrucao>
496 <InstrucaoUnica TipoValidacao=\"Transparente\">";
497  
498 $xml = $self->add_url_retorno ( $xml, $cart );
499 $xml = $self->add_url_notificacao ( $xml, $cart );
500 $xml = $self->add_formas_pagamento ( $xml, $cart );
501 $xml = $self->add_mensagens ( $xml, $cart );
502 $xml = $self->add_razao ( $xml, $cart );
503 $xml = $self->add_valores ( $xml, $cart );
504 $xml = $self->add_id_proprio ( $xml, $cart );
505 $xml = $self->add_pagador ( $xml, $cart );
506 $xml = $self->add_boleto ( $xml, $cart );
507 $xml = $self->add_parcelas ( $xml, $cart );
508 $xml = $self->add_comissoes ( $xml, $cart );
509 $xml = $self->add_entrega ( $xml, $cart );
510  
511 $xml .= "\n</InstrucaoUnica>
512 </EnviarInstrucao>";
513  
514 return $xml;
515 }
516  
517 sub add_url_retorno {
518 my ( $self, $xml , $cart ) = @_;
519 if ( defined $cart->url_retorno ) {
520 $xml .= "<URLRetorno>".$cart->url_retorno."</URLRetorno>";
521 }
522 return $xml;
523 }
524  
525 sub add_url_notificacao {
526 my ( $self, $xml , $cart ) = @_;
527 if ( defined $cart->url_notificacao ) {
528 $xml .= "<URLNotificacao>".$cart->url_notificacao."</URLNotificacao>";
529 }
530 return $xml;
531 }
532  
533 sub add_formas_pagamento {
534 my ( $self, $xml , $cart ) = @_;
535 if ( defined $cart->formas_pagamento and ref $cart->formas_pagamento eq ref [] ) {
536 $xml .= "<FormasPagamento>";
537 foreach my $forma ( @{ $cart->formas_pagamento } ) {
538 $xml .= "<FormaPagamento>".$forma."</FormaPagamento>";
539 }
540 $xml .= "</FormasPagamento>";
541 }
542 return $xml;
543 }
544  
545 sub add_entrega {
546 my ( $self, $xml, $cart ) = @_;
547 if ( defined $cart->entrega ) {
548 $xml .= "<Entrega>";
549 if ( exists $cart->entrega->{destino} ) {
550 $xml .= "<Destino>".$cart->entrega->{destino}."</Destino>";
551 }
552 foreach my $e ( @{ $cart->entrega->{ calculo_frete } } ) {
553 $xml .= "<CalculoFrete>";
554 if ( exists $e->{ tipo } ) {
555 $xml .= "<Tipo>Proprio</Tipo>" if $e->{ tipo } =~ m/proprio/ig;
556 $xml .= "<Tipo>Correios</Tipo>" if $e->{ tipo } =~ m/correio/ig;
557 }
558 if ( exists $e->{ valor_fixo } ) {
559 $xml .= "<ValorFixo>".$e->{ valor_fixo }."</ValorFixo>";
560 }
561 if ( exists $e->{ valor_percentual } ) {
562 $xml .= "<ValorPercentual>". $e->{ valor_percentual } ."</ValorPercentual>";
563 }
564 if ( exists $e->{ prazo } and
565 exists $e->{ prazo }->{ valor } and
566 exists $e->{ prazo }->{ tipo }
567 ) {
568 if ( $e->{ prazo }->{ tipo } =~ m/corridos/ig ) {
569 $xml .= '<Prazo Tipo="Corridos">'.$e->{ prazo }->{ valor }.'</Prazo>' ;
570 }
571 if ($e->{ prazo }->{ tipo } =~ m/uteis/ig ) {
572 $xml .= '<Prazo Tipo="Uteis">'. $e->{ prazo }->{ valor }.'</Prazo>' ;
573 }
574 }
575 if ( exists $e->{ correios } ) {
576 $xml .= "<Correios>";
577 if ( exists $e->{correios}->{peso_total} ) {
578 $xml .= "<PesoTotal>".$e->{correios}->{peso_total}."</PesoTotal>";
579 }
580 if ( exists $e->{correios}->{forma_entrega} ) {
581 $xml .= "<FormaEntrega>".$e->{correios}->{forma_entrega}."</FormaEntrega>";
582 }
583 if ( exists $e->{correios}->{mao_propria} ) {
584 $xml .= "<MaoPropria>".$e->{correios}->{mao_propria}."</MaoPropria>";
585 }
586 if ( exists $e->{correios}->{valor_delarado} ) {
587 $xml .= "<ValorDeclarado>".$e->{correios}->{valor_declarado}."</ValorDeclarado>";
588 }
589 if ( exists $e->{correios}->{aviso_recebimento} ) {
590 $xml .= "<AvisoRecebimento>".$e->{correios}->{aviso_recebimento}."</AvisoRecebimento>";
591 }
592 if ( exists $e->{correios}->{cep_origem} ) {
593 $xml .= "<CepOrigem>".$e->{correios}->{cep_origem}."</CepOrigem>";
594 }
595 $xml .= "</Correios>";
596 }
597 $xml .= "</CalculoFrete>";
598 }
599 $xml .= "</Entrega>";
600 }
601 return $xml;
602 }
603  
604 sub add_razao {
605 my ( $self, $xml, $cart ) = @_;
606 $xml .= "<Razao>Pagamento para loja ".$self->receiver_label." </Razao>";
607 return $xml;
608 }
609  
610 sub add_comissoes {
611 my ( $self, $xml, $cart ) = @_;
612 if ( defined $cart->comissoes || defined $cart->pagador_taxa ) {
613 $xml .= "\n<Comissoes>";
614 if ( defined $cart->comissoes ) {
615 foreach my $comissao ( @{ $cart->comissoes } ) {
616 $xml .= "\n<Comissionamento>";
617 if ( exists $comissao->{razao} ) {
618 $xml .= "\n<Razao>".$comissao->{razao}."</Razao>" if exists $comissao->{razao};
619 }
620 if ( exists $comissao->{login_moip} ) {
621 $xml .= "\n<Comissionado><LoginMoIP>".$comissao->{login_moip}."</LoginMoIP></Comissionado>"
622 }
623 if ( exists $comissao->{valor_percentual} ) {
624 $xml .= "\n<ValorPercentual>".$comissao->{valor_percentual}."</ValorPercentual>";
625 }
626 if ( exists $comissao->{valor_fixo} ) {
627 $xml .= "\n<ValorFixo>".$comissao->{valor_fixo}."</ValorFixo>";
628 }
629 $xml .= "\n</Comissionamento>";
630 }
631 }
632 if ( defined $cart->pagador_taxa ) {
633 $xml .= "\n<PagadorTaxa><LoginMoIP>".$cart->pagador_taxa."</LoginMoIP></PagadorTaxa>";
634 }
635 $xml .= "\n</Comissoes>";
636 }
637 return $xml;
638 }
639  
640 sub add_parcelas {
641 my ( $self, $xml, $cart ) = @_;
642 if ( defined $cart->parcelas and scalar @{ $cart->parcelas } > 0 ) {
643 $xml .= "\n<Parcelamentos>";
644 foreach my $parcela ( @{ $cart->parcelas } ) {
645 if ( defined $parcela->{parcelas_max} and defined $parcela->{parcelas_min} ) {
646 $xml .= "\n<Parcelamento>";
647 if ( defined $parcela->{parcelas_min} ) {
648 $xml .= "\n<MinimoParcelas>".$parcela->{parcelas_min}."</MinimoParcelas>";
649 }
650 if ( defined $parcela->{parcelas_max} ) {
651 $xml .= "\n<MaximoParcelas>".$parcela->{parcelas_max}."</MaximoParcelas>";
652 }
653 $xml .= "\n<Juros>"; $xml .= ( defined $parcela->{juros} )?$parcela->{juros}:'0'; $xml .= "</Juros>";
654 $xml .= "\n</Parcelamento>";
655 }
656 }
657 $xml .= "\n</Parcelamentos>";
658 }
659 return $xml;
660 }
661  
662 sub add_id_proprio {
663 my ( $self, $xml, $cart ) = @_;
664 # id proprio
665 if ( $self->id_proprio ) {
666 $xml .= "\n<IdProprio>". $self->id_proprio ."</IdProprio>";
667 }
668 return $xml;
669 }
670  
671 sub add_valores {
672 my ( $self, $xml, $cart ) = @_;
673 $xml .= "<Valores>";
674 # valores
675 foreach my $item ( @{$cart->_items} ) {
676 $xml .= "\n<Valor moeda=\"BRL\">".$item->price."</Valor>";
677 }
678 $xml .= "\n</Valores>";
679 return $xml;
680 }
681  
682 sub add_mensagens {
683 my ( $self, $xml, $cart ) = @_;
684 if ( defined $cart->mensagens and scalar @{ $cart->mensagens } > 0 ) {
685 $xml .= "<Mensagens>";
686 foreach my $msg ( @{ $cart->mensagens } ) {
687 $xml .= "<Mensagem>".$msg."</Mensagem>";
688 }
689 $xml .= "</Mensagens>";
690 }
691 return $xml;
692 }
693  
694 sub add_pagador {
695 my ( $self, $xml, $cart ) = @_;
696 # dados do pagador
697 if ( $cart->buyer ) {
698 $xml .= "\n<Pagador>";
699 if ( $cart->buyer->name ) {
700 $xml .= "\n<Nome>".$cart->buyer->name."</Nome>";
701 }
702 if ( $cart->buyer->email ) {
703 $xml .= "\n<Email>".$cart->buyer->email."</Email>";
704 }
705 if ( $cart->buyer->id_pagador ) {
706 $xml .= "\n<IdPagador>".$cart->buyer->id_pagador."</IdPagador>";
707 }
708 if (
709 defined $cart->buyer->address_district ||
710 defined $cart->buyer->address_number ||
711 defined $cart->buyer->address_country ||
712 defined $cart->buyer->address_district ||
713 defined $cart->buyer->address_state ||
714 defined $cart->buyer->address_street ||
715 defined $cart->buyer->address_zip_code
716 ) {
717 $xml .= "\n<EnderecoCobranca>";
718 if ( defined $cart->buyer->address_street ) {
719 $xml .= "\n<Logradouro>".$cart->buyer->address_street."</Logradouro>";
720 }
721 if ( defined $cart->buyer->address_number ) {
722 $xml .= "\n<Numero>".$cart->buyer->address_number."</Numero>";
723 }
724 if ( defined $cart->buyer->address_complement ) {
725 $xml .= "\n<Complemento>".$cart->buyer->address_complement."</Complemento>";
726 }
727 if ( defined $cart->buyer->address_district ) {
728 $xml .= "\n<Bairro>".$cart->buyer->address_district."</Bairro>";
729 }
730 if ( defined $cart->buyer->address_city ) {
731 $xml .= "\n<Cidade>".$cart->buyer->address_city."</Cidade>";
732 }
733 if ( defined $cart->buyer->address_state ) {
734 $xml .= "\n<Estado>".$cart->buyer->address_state."</Estado>";
735 }
736 if ( defined $cart->buyer->address_country ) {
737 warn $cart->buyer->address_country;
738 my $sigla = uc(
739 Locale::Country::country_code2code(
740 $cart->buyer->address_country, 'alpha-2', 'alpha-3'
741 )
742 );
743 $xml .= "\n<Pais>".$sigla."</Pais>";
744 }
745 if ( defined $cart->buyer->address_zip_code ) {
746 $xml .= "\n<CEP>".$cart->buyer->address_zip_code."</CEP>";
747 }
748 if ( defined $cart->buyer->phone ) {
749 $xml .= "\n<TelefoneFixo>".$cart->buyer->phone."</TelefoneFixo>";
750 }
751 $xml .= "\n</EnderecoCobranca>";
752 }
753 $xml .= "</Pagador>";
754 }
755 return $xml;
756 }
757  
758 sub add_boleto {
759 my ( $self, $xml, $cart ) = @_;
760 if (
761 defined $cart->boleto
762 ) {
763 $xml .= "\n<Boleto>";
764 if ( exists $cart->boleto->{ data_vencimento } ) {
765 $xml .= "\n<DataVencimento>".$cart->boleto->{ data_vencimento }."</DataVencimento>";
766 }
767 if ( exists $cart->boleto->{ instrucao1 } ) {
768 $xml .= "\n<Instrucao1>".$cart->boleto->{ instrucao1 }."</Instrucao1>";
769 }
770 if ( exists $cart->boleto->{ instrucao2 } ) {
771 $xml .= "\n<Instrucao2>".$cart->boleto->{ instrucao2 }."</Instrucao2>";
772 }
773 if ( exists $cart->boleto->{ instrucao3 } ) {
774 $xml .= "\n<Instrucao3>".$cart->boleto->{ instrucao3 }."</Instrucao3>";
775 }
776 if ( exists $cart->boleto->{ logo_url } ) {
777 $xml .= "\n<URLLogo>".$cart->boleto->{ logo_url }."</URLLogo>";
778 }
779 if ( exists $cart->boleto->{ expiracao } ) {
780 my $tipo='';
781 if ( exists $cart->boleto->{ expiracao }->{ tipo } ) {
782 $tipo = ' Tipo="Corridos"' if $cart->boleto->{ expiracao }->{ tipo } =~ m/corridos/gi;
783 $tipo = ' Tipo="Uteis"' if $cart->boleto->{ expiracao }->{ tipo } =~ m/uteis/gi;
784 }
785 $xml .= "\n<DiasExpiracao$tipo>".$cart->boleto->{ expiracao }->{ dias }."</DiasExpiracao>";
786 }
787 $xml .= "\n</Boleto>";
788 }
789 return $xml;
790 }
791  
792 =head2 query_transactions()
793  
794 TODO: http://labs.moip.com.br/blog/saiba-quais-foram-suas-ultimas-transacoes-no-moip-sem-sair-do-seu-site-com-o-moipstatus/
795  
796 TODO: https://github.com/moiplabs/moip-php/blob/master/lib/MoipStatus.php
797  
798 *** Não foi implementado pois o moip possúi api boa para transações mas não tem implementado meios para analisar transações entre período.
799 O único jeito é fazer login no site via lwp ou similar e pegar as informações direto do markup.. mas ao menos neste momento não há seletores que indicam quais os dados.
800  
801 =head2 query_transactions example
802  
803 *** NOT IMPLEMENTED... but this is what it would would like more or less.
804  
805 Thats how it can be done today... making login and parsing the welcome html screen (no good).
806 Not good because they dont have it on their api... and its not good to rely on markup to read
807 this sort of important values.
808  
809 moipstatus.php, on their github acc: https://github.com/moiplabs/moip-php/blob/master/lib/MoipStatus.php
810  
811 use HTTP::Tiny;
812 use MIME::Base64;
813 use Data::Printer;
814 use HTTP::Request::Common qw(POST);
815 use Mojo::DOM;
816 my $url_login = "https://www.moip.com.br/j_acegi_security_check";
817 my $login = 'XXXXXXXXXXX';
818 my $pass = "XXXXXXX";
819 my $url_transactions = 'https://www.moip.com.br/rest/reports/last-transactions';
820  
821 my $form_login = [
822 j_password => $pass,
823 j_username => $login,
824 ];
825  
826 my $res = HTTP::Tiny->new( verify_SSL => 0 )->request(
827 'POST',
828 $url_login,
829 {
830 headers => {
831 'Authorization' => 'Basic ' . MIME::Base64::encode($login.":".$pass,''),
832 'Content-Type' => 'application/x-www-form-urlencoded',
833 },
834 content => POST( $url_login, [], Content => $form_login )->content,
835 }
836 );
837 warn p $res;
838  
839 warn "login fail" and die if $res->{ headers }->{ location } =~ m/fail/ig;
840  
841 my $res2 = HTTP::Tiny->new( verify_SSL => 0 )->request(
842 'GET',
843 $res->{headers}->{location}
844 );
845 # warn p $res2;
846 my $dom = Mojo::DOM->new($res2->{content});
847  
848 SALDO_STATS: {
849 my $saldo = $dom->at('div.textoCinza11 b.textoAzul11:nth-child(3)');
850 my $a_receber = $dom->at('div.textoCinza11 b.textoAzul11:nth-child(10)');
851 my $stats = {
852 saldo => (defined $saldo) ? $saldo->text : undef,
853 saldo_a_receber => (defined $a_receber) ? $a_receber->text : undef,
854 };
855 warn p $stats;
856 }
857  
858 LAST_TRANSACTIONS:{
859 my $selector = 'div.conteudo>div:eq(1)>div:eq(1)>div:eq(1)>div:eq(0) div.box table[cellpadding=5]>tbody tr';
860 my $nenhuma = $dom->at( $selector );
861 warn p $nenhuma;
862 }
863  
864  
865 =cut
866  
867 sub query_transactions {}
868  
869 =head2 get_transaction_details()
870  
871 TODO: http://labs.moip.com.br/referencia/consulta-de-instrucao/
872  
873 =cut
874  
875 sub get_transaction_details {}
876  
877 =head1 AUTHOR
878  
879 Hernan Lopes
880 CPAN ID: HERNAN
881 -
882 hernan@cpan.org
883 http://github.com/hernan604
884  
885 =head1 COPYRIGHT
886  
887 This program is free software; you can redistribute
888 it and/or modify it under the same terms as Perl itself.
889  
890 The full text of the license can be found in the
891 LICENSE file included with this module.
892  
893 =head1 SPONSOR
894  
895 http://www.nixus.com.br
896  
897 =head1 SEE ALSO
898  
899 perl(1).
900  
901 =cut
902  
903 1;
904 # The preceding line will help the module return a true value
905