The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Business::CPI::Gateway::Moip - Inteface para pagamentos Moip

SYNOPSIS

    use Data::Printer;
    use Business::CPI::Buyer::Moip;
    use Business::CPI::Cart::Moip;
    use Business::CPI::Gateway::Moip;

    my $cpi = Business::CPI::Gateway::Moip->new(
        currency        => 'BRL',
        sandbox         => 1,
        token_acesso    => 'YC110LQX7UQXEMQPLYOPZ1LV9EWA8VKD',
        chave_acesso    => 'K03JZXJLOKJNX0CNL0NPGGTHTMGBFFSKNX6IUUWV',
        receiver_email  => 'teste@oemail.com.br',
        receiver_label  => 'Nome Cliente ou Loja',
        id_proprio      => 'ID_INTERNO_'.int rand(int rand(99999999)),

    );

    my $cart = $cpi->new_cart({
        buyer => {
            name               => 'Mr. Buyer',
            email              => 'sender@andrewalker.net',
            address_street     => 'Rua das Flores',
            address_number     => '360',
            address_district   => 'Vila Mariana',
            address_complement => 'Ap 35',
            address_city       => 'São Paulo',
            address_state      => 'SP',
            address_country    => 'Brazil',
            address_zip_code   => '04363-040',
            phone              => '11-9911-0022',
            id_pagador         => 'O11O22X33X',
        },
        mensagens => [
            'Produto adquirido no site X',
            'Total pago + frete - Preço: R$ 144,10',
            'Mensagem linha3',
        ],
        boleto => {
            expiracao       => {
                dias => 7,
                tipo => 'corridos', #ou uteis
            },
            data_vencimento => '2012/12/30T24:00:00.0-03:00',
            instrucao1      => 'Primeira linha de instrução de pagamento do boleto bancário',#OPT
            instrucao2      => 'Segunda linha de instrução de pagamento do boleto bancário', #OPT
            instrucao3      => 'Terceira linha de instrução de pagamento do boleto bancário',#OPT
            logo_url        => 'http://www.nixus.com.br/img/logo_nixus.png',                 #OPT
        },
        formas_pagamento => [
            'BoletoBancario',
            'CartaoDeCredito',
            'DebitoBancario',
            'CartaoDeDebito',
            'FinanciamentoBancario',
            'CarteiraMoIP',
        ],
        url_retorno => 'http://www.url_retorno.com.br',
        url_notificacao => 'http://www.url_notificacao.com.br',
        entrega => {
            destino => 'MesmoCobranca',
            calculo_frete => [
                {
                    tipo => 'proprio', #ou correios
                    valor_fixo => 2.30, #ou valor_percentual
                    prazo => {
                        tipo  => 'corridos', #ou uteis
                        valor => 2,
                    }
                },
                {
                    tipo             => 'correios',
                    valor_percentual => 12.30,
                    prazo => {
                        tipo    => 'corridos',#ou uteis
                        valor   => 2,
                    },
                    correios => {
                        peso_total          => 12.00,
                        forma_entrega       => 'Sedex10', #ou sedex sedexacobrar sedexhoje
                        mao_propria         => 'PagadorEscolhe', #ou SIM ou NAO
                        valor_declarado     => 'PagadorEscolhe', #ou SIM ou NAO
                        aviso_recebimento   => 'PagadorEscolhe', # ou SIM ou NAO
                        cep_origem          => '01230-000',
                    },
                },
                {
                    tipo => 'correios',
                    valor_percentual => 12.30,
                    prazo => {
                        tipo    => 'corridos',#ou uteis
                        valor   => 2,
                    },
                    correios => {
                        peso_total          => 12.00,
                        forma_entrega       => 'Sedex10', #ou sedex sedexacobrar sedexhoje
                        mao_propria         => 'PagadorEscolhe', #ou SIM ou NAO
                        valor_declarado     => 'PagadorEscolhe', #ou SIM ou NAO
                        aviso_recebimento   => 'PagadorEscolhe', # ou SIM ou NAO
                        cep_origem          => '01230-000',
                    },
                },
            ]
        }
    },
    );

    my $item = $cart->add_item({
        id          => 2,
        quantity    => 1,
        price       => 222,
        description => 'produto2',
    });

    my $item = $cart->add_item({
        id          => 1,
        quantity    => 2,
        price       => 111,
        description => 'produto1',
    });

    my $res = $cpi->make_xml_transaction( $cart );

    Return on success:
        $res = {
            code    "SUCCESS",
            id      201301231157322850000001500872,
            token   "C2R0A1V3K0P132J3Q1C1S5M7R3N2P2N8B5L0Q0M0J05070U1W5K0P018D7T2"
        }

    Return on error:
        $res = {
            code    "ERROR",
            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
        iamente</Erro></Resposta></ns1:EnviarInstrucaoUnicaResponse>"
        }

EXAMPLE USING Business:CPI

The following example will use Business::CPI directly

    use Business::CPI;
    use Data::Printer;

    my $moip = Business::CPI->new(
        gateway        => "Moip",
        sandbox         => 1,
        token_acesso    => 'YC110LQX7UQXEMQPLYOPZ1LV9EWA8VKD',
        chave_acesso    => 'K03JZXJLOKJNX0CNL0NPGGTHTMGBFFSKNX6IUUWV',
        receiver_email  => 'teste@oemail.com.br',
        receiver_label  => 'Nome Cliente ou Loja',
        id_proprio      => 'ID_INTERNO_'.int rand(int rand(99999999)),
    );

    my $cart = $moip->new_cart({
        buyer => {
            name               => 'Mr. Buyer',
            email              => 'sender@andrewalker.net',
            address_street     => 'Rua das Flores',
            address_number     => '360',
            address_district   => 'Vila Mariana',
            address_complement => 'Ap 35',
            address_city       => 'São Paulo',
            address_state      => 'SP',
            address_country    => 'BRA',
            address_zip_code   => '04363-040',
            phone              => '11-9911-0022',
            id_pagador         => 'O11O22X33X',
        }
    });

    $cart->parcelas([
        {
            parcelas_min => 2,
            parcelas_max => 6,
            juros        => 2.99,
        },
        {
            parcelas_min => 7,
            parcelas_max => 12,
            juros        => 10.99,
        },
    ]);

    my $item = $cart->add_item({
        id          => 2,
        quantity    => 1,
        price       => 222,
        description => 'produto2',
    });

    my $item = $cart->add_item({
        id          => 1,
        quantity    => 2,
        price       => 111,
        description => 'produto1',
    });

    my $res = $moip->make_xml_transaction( $cart );
    warn p $res;

MOIP DOCUMENTATION REFERENCE

http://labs.moip.com.br

http://labs.moip.com.br/referencia/minuto/

http://labs.moip.com.br/referencia/pagamento_parcelado/

SANDBOX

Register yourself in the Moip sandbox: http://labs.moip.com.br/

DESCRIPTION

Business::CPI::Gateway::Moip allows you to make moip transactions using Business::CPI standards.

Currently, Moip uses XML format for transactions.

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:

    ->make_xml_transaction

and register your transaction within moip servers to obtain a moip transaction tokenid.

** make_xml_transaction will return a TOKEN and code SUCCESS upon success. You will need this info so your user can checkout afterwards.

* see the tests for examples

MOIP TRANSACTION FLOW

Here, ill try to describe how the moip transaction flow works:

    1. You post the paymentXML to the moip servers
    2. Moip returns a transaction token id upon success

Then, you have 2 options for checkout:

    - option1 (send the user to moip site to finish transaction):
    - 3. You redirect your client to moip servers passing the transaction token id

    - option2 (use the moip transaction id and some javascript for checkout):
    3. You use some javascript with the transaction token id

    4. Your client pays

CRUDE EXAMPLE

Ive prepared this example just in case you want to test the moip payment sistem without using any other module. The following snippet uses only HTTP::Tiny to register the moip transaction.

        my $conteudo = <<'XML';
    <EnviarInstrucao>
      <InstrucaoUnica>
            <Razao>Pagamento com HTTP Tiny</Razao>
            <Valores>
                <Valor moeda='BRL'>1.50</Valor>
            </Valores>
            <Pagador>
                <IdPagador>cliente_id</IdPagador>
            </Pagador>
      </InstrucaoUnica>
    </EnviarInstrucao>
    XML
        my $res = HTTP::Tiny->new( verify_SSL => $self->verify_ssl )->request(
            'POST',
            $self->api_url,
            {
                headers => {
                    'Authorization' => 'Basic ' . MIME::Base64::encode($self->token_acesso.":".$self->chave_acesso,''),
                    'Content-Type' => 'application/x-www-form-urlencoded',
                },
                content => $conteudo,
            }
        );
        warn p $res;

ATTRIBUTES

sandbox

Indicates whether or not this module will use the sandbox url or production url.

api_url

Holds the api_url. You DONT need to pass it, it will figure out its own url based on $self->sandbox

token_acesso

Moip token

chave_acesso

Moip access-key

id_proprio

Your own internal transaction id. ie. e39jd2390jd92d030000001

receiver_label

Name that will receive this payment ie. My Store Name

receiver_email

Email that will receive this payment ie. sales@mystore.com

ua

Uses HTTP::Tiny as useragent

METHODS

make_xml_transaction

Registers the transaction on the Moip servers.

Receives an $cart, generates the XML and register the transaction on the Moip Server.

Returns the moip transaction token upon success.

Returns the full raw_error when fails.

Return on success:

        {
            code    "SUCCESS",
            id      201301231157322850000001500872,
            token   "C2R0A1V3K0P132J3Q1C1S5M7R3N2P2N8B5L0Q0M0J05070U1W5K0P018D7T2"
        }

Return on error:

        {
            code    "ERROR",
            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
        iamente</Erro></Resposta></ns1:EnviarInstrucaoUnicaResponse>"
        }

notify

Not implemented yet for Moip

payment_to_xml

Generates an XML with the information in $cart and other attributes ie. receiver_label, id_proprio, buyer email, etc

returns the Moip XML format

query_transactions()

TODO: http://labs.moip.com.br/blog/saiba-quais-foram-suas-ultimas-transacoes-no-moip-sem-sair-do-seu-site-com-o-moipstatus/

TODO: https://github.com/moiplabs/moip-php/blob/master/lib/MoipStatus.php

*** 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. 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.

query_transactions example

*** NOT IMPLEMENTED... but this is what it would would like more or less.

Thats how it can be done today... making login and parsing the welcome html screen (no good). Not good because they dont have it on their api... and its not good to rely on markup to read this sort of important values.

moipstatus.php, on their github acc: https://github.com/moiplabs/moip-php/blob/master/lib/MoipStatus.php

    use HTTP::Tiny;
    use MIME::Base64;
    use Data::Printer;
    use HTTP::Request::Common qw(POST);
    use Mojo::DOM;
    my $url_login = "https://www.moip.com.br/j_acegi_security_check";
    my $login = 'XXXXXXXXXXX';
    my $pass = "XXXXXXX";
    my $url_transactions = 'https://www.moip.com.br/rest/reports/last-transactions';

    my $form_login = [
        j_password => $pass,
        j_username => $login,
    ];

    my $res = HTTP::Tiny->new( verify_SSL => 0 )->request(
        'POST',
        $url_login,
        {
            headers => {
                'Authorization' => 'Basic ' . MIME::Base64::encode($login.":".$pass,''),
                'Content-Type' => 'application/x-www-form-urlencoded',
            },
            content => POST( $url_login, [], Content => $form_login )->content,
        }
    );
    warn p $res;

    warn "login fail" and die if $res->{ headers }->{ location } =~ m/fail/ig;

    my $res2 = HTTP::Tiny->new( verify_SSL => 0 )->request(
        'GET',
        $res->{headers}->{location}
    );
    # warn p $res2;
    my $dom = Mojo::DOM->new($res2->{content});

    SALDO_STATS: {
        my $saldo       = $dom->at('div.textoCinza11 b.textoAzul11:nth-child(3)');
        my $a_receber   = $dom->at('div.textoCinza11 b.textoAzul11:nth-child(10)');
        my $stats = {
            saldo           => (defined $saldo)     ?   $saldo->text     : undef,
            saldo_a_receber => (defined $a_receber) ?   $a_receber->text : undef,
        };
        warn p $stats;
    }

    LAST_TRANSACTIONS:{
        my $selector = 'div.conteudo>div:eq(1)>div:eq(1)>div:eq(1)>div:eq(0) div.box table[cellpadding=5]>tbody tr';
        my $nenhuma = $dom->at( $selector );
        warn p $nenhuma;
    }

get_transaction_details()

TODO: http://labs.moip.com.br/referencia/consulta-de-instrucao/

AUTHOR

    Hernan Lopes
    CPAN ID: HERNAN
    -
    hernan@cpan.org
    http://github.com/hernan604

COPYRIGHT

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included with this module.

SPONSOR

http://www.nixus.com.br

SEE ALSO

perl(1).