Coder Social home page Coder Social logo

sdk-php's Introduction

<img src=“https://travis-ci.org/brunosoab/maxipago.png?branch=1.0.0.rc1” alt=“Build Status” />

Adicionar a GEM na sua aplicação Rails 3 ou Rails 4

Adicione ao Gemfile da sua aplicação a seguinte linha:

gem "maxipago", :git => "git://github.com/brunosoab/maxipago.git", :branch => "1.0.0.rc1"

Instalar inicializador da GEM

rails generate maxipago:install

Maxipago

Usamos o maxipago.net (Maxipago) para relizar transações financeiras dentro do aplicativo da Liga das Torcidas.

A construção da biblioteca foi realizada em cima do manual da *API V1.3* e da API de transação V3.1.1.15. O histórico das revisões pode ser visto no manual. Atualmente cobre as funcionalidades até a versão *API V1.9.3*.

Para baixar o manual: www.maxipago.com/docs/maxiPago_API_Ultima.pdf

Para o ambiente de testes usamos as URLs fornecidas pelo Maxipago:

Cartões de teste:

  • American Express 378282246310005

  • American Express 371449635398431

  • MasterCard 5555555555554444

  • MasterCard 5105105105105100

  • Visa 4111111111111111

  • Visa 4012888888881881

O campo CVV pode ser preenchido com qualquer número entre *“3”* e *“4”* dígitos e a data de vencimento precisa ser válida. No futuro. Um cartão de teste já está adicionado ao arquivo de configuração da biblioteca. Veja mais detalhes sobre o uso nas seções posteriores.

  • No ambiente de testes nenhuma transação será de fato realizada. Todas as funcionalidades podem ser verificadas através dos testes da biblioteca na pasta:

    spects/

Credenciamento dos Estabelecimentos

Para realizar uma acão usando a bibioteca maxipago é preciso incluir as credenciais do estabelecimento. Qualquer requisição a API do Maxipago precisa ser autenticada.

O local para incluir essas credenciais bem como dados de teste ficam localizado em:

config/initializers/maxipago_config.rb

Aqui segue um exemplo do seu conteudo:

# Set your key and id
MP_APIKEY = ENV['MP_APIKEY'] #use uma variável de ambiente
MP_ID = ENV['MP_ID'] #use uma variável de ambiente

# Set the Maxipago API version: currently (3.1.1.15)
MP_APIVERSION = "3.1.1.15"

# Maxipago API Urls - production
MP_URL_TRANSACTION = "https://api.maxipago.net/UniversalAPI/postXML"
MP_URL_API = "https://api.maxipago.net/UniversalAPI/postAPI"
MP_URL_RAPI =  "https://api.maxipago.net/ReportsAPI/servlet/ReportsAPI"

# Maxipago API Urls - development and test
URL_TEST_TRANSACTION = "https://testapi.maxipago.net/UniversalAPI/postXML"
URL_TEST_API = "https://testapi.maxipago.net/UniversalAPI/postAPI"
URL_TEST_RAPI = "https://testapi.maxipago.net/ReportsAPI/servlet/ReportsAPI"

Use uma variável de ambiente para sua key do maxipago e seu id.

Tests (Rspec)

rspec spec

Como usar?

Crie um client onde podemos executar comandos:

mp = Maxipago::Client.new
=> #<Maxipago::Client:0x007fb1f3d171d8>

Crie um request do tipo da api que queremos usar (api, transaction ou rapi):

api = Maxipago::RequestBuilder::ApiRequest.new(MAX_ID, MAX_APIKEY)
=> #<Maxipago::RequestBuilder::ApiRequest:0x007fb1f3d2f440 @maxid="100", @apikey="21g8u6gh6szw1gywfs165vui", @api_version="3.1.1.15", @header={"Content-Type"=>"text/xml"}>

Faça o client carregar o request gerado no passo anterior:

mp.use(api)
=> #<Maxipago::RequestBuilder::ApiRequest:0x007fb1f3d2f440 @maxid="100", @apikey="21g8u6gh6szw1gywfs165vui", @api_version="3.1.1.15", @header={"Content-Type"=>"text/xml"}>

Execute um comando da api escolhida:

mp.execute({command: "add_consumer", customer_id_ext: "1", firstname: "Foo", lastname: "Bar"})
=> {:header=>#<Net::HTTPOK 200 OK readbody=true>, :body=>"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><api-response><errorCode>0</errorCode><errorMessage></errorMessage><command>add-consumer</command><time>1371687537124</time><result><customerId>14289</customerId></result></api-response>", :message=>"OK"}

Verifique os testes na pasta spec/ do repositório para ver mais exemplos de uso. Os testes cobrem todos os comandos suportados.

Licença de uso

Copyright 2012 Bonera Software e Participações S/A.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

sdk-php's People

Contributors

daneoshiga avatar jonatanmatschulat avatar pedrocasado avatar rquadling avatar tcanabarro avatar zanaca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk-php's Issues

Small typo issue

LEIAME.md

Line 127: Captura: creditCarcCapture() => creditCardCapture

Line 171: rsposta => resposta

"Kount IO error" - Servidor TEST

  • Servidor de testes retorna sempre "Kount IO error".
  • Esse comportamento foi detectado inicialmente há cerca de 3 semanas atrás. Antes disso estava funcionando normalmente.
  • Em ambiente de produção (LIVE), a biblioteca está funcionando corretamente.

PHP Version 7.3.25
Script para reprodução:

        $api = new maxiPago;
        $api->setCredentials(*****, ***********************);
        $api->setEnvironment("TEST");
        $api->setDebug(true);

        $data = array(
            "processorID"   => "1", // REQUIRED - Use '1' for testing. Contact our team for production values //
            "referenceNum"  => 1, // REQUIRED - Merchant internal order number //
            "chargeTotal"   => 20, // REQUIRED - Transaction amount in US format //
            "bname"         => "João da Silva Santos", // HIGHLY RECOMMENDED - Customer name //
            "number"        => "378282246310005", // REQUIRED - Full credit card number //
            "expMonth"      => 12, // REQUIRED - Credit card expiration month //
            "expYear"       => 2024, // REQUIRED - Credit card expiration year //
            "cvvNumber"     => 123, // HIGHLY RECOMMENDED - Credit card verification code //
        );

        $api->creditCardSale($data);
        echo $api->getMessage();

Resultado:

--------------------
[2022-11-07 13:11:00:32050] Target URL: https://testapi.maxipago.net/UniversalAPI/postXML
--------------------

--------------------
[2022-11-07 13:11:00:34400] XML Request: <?xml version="1.0" encoding="UTF-8"?> <transaction-request><version>3.1.1.15</version><verification><merchantId>****</merchantId><merchantKey>**********</merchantKey></verification><order><sale><processorID>1</processorID><referenceNum>1</referenceNum><billing><name>João da Silva Santos</name></billing><shipping/><transactionDetail><payType><creditCard><number>378282246310005</number><expMonth>12</expMonth><expYear>2024</expYear><cvvNumber>123</cvvNumber></creditCard></payType></transactionDetail><payment><chargeTotal>20</chargeTotal></payment></sale></order></transaction-request>
--------------------

--------------------
[2022-11-07 13:11:00:34403] XML Response: <?xml version="1.0" encoding="UTF-8"?><transaction-response><authCode>123456</authCode><orderID>0A0104B1:018452FD0FCC:D06E:01FD6D16</orderID><referenceNum>1</referenceNum><transactionID>13917869</transactionID><transactionTimestamp>1667839627</transactionTimestamp><responseCode>2</responseCode><responseMessage>VOIDED</responseMessage><avsResponseCode>YYY</avsResponseCode><cvvResponseCode>M</cvvResponseCode><processorCode>ERROR</processorCode><processorMessage>Kount IO error.</processorMessage><processorName>SIMULATOR</processorName><creditCardBin>378282</creditCardBin><creditCardLast4>0005</creditCardLast4><errorMessage>Unable to contact kount.</errorMessage><processorTransactionID>828683</processorTransactionID><processorReferenceNumber>1092462</processorReferenceNumber><creditCardCountry>US</creditCardCountry><creditCardScheme>Amex</creditCardScheme></transaction-response>
--------------------

--------------------
[2022-11-07 13:11:00:34403] Response time: 1.099 secs.
--------------------
Kount IO error.

API PIX - processor not found

Todas requisições PIX que enviamos para a API retornam processor not found.

ProcessorID
image

XML postado:

<?xml version="1.0" encoding="UTF-8"?>
<transaction-request>
	<version>3.1.1.15</version>
	<verification>
		<merchantId>****</merchantId>
		<merchantKey>****</merchantKey>
	</verification>
	<order>
		<sale>
			<processorID>206</processorID>
			<referenceNum>1</referenceNum>
			<fraudCheck>N</fraudCheck>
			<customerIdExt>37568256634</customerIdExt>
			<billing>
				<name>João da Silva</name>
				<address>Rua Território do Amapá</address>
				<address2>N 10, Apto 01</address2>
				<district>Pituba</district>
				<city>Salvador</city>
				<state>Bahia</state>
				<postalcode>41830-540</postalcode>
				<country>BR</country>
				<phone>71999908199</phone>
				<email>[email protected]</email>
				<documents>
					<document>
						<documentType>CPF</documentType>
						<documentValue>59603497010</documentValue>
					</document>
				</documents>
			</billing>
			<transactionDetail>
				<payType>
					<pix>
						<expirationTime>3600</expirationTime>
						<paymentInfo>Transação de Teste</paymentInfo>
						<extraInfo>
							<info>
								<name>Produto de Teste</name>
								<value>1</value>
							</info>
						</extraInfo>
					</pix>
				</payType>
			</transactionDetail>
			<payment>
				<chargeTotal>1</chargeTotal>
			</payment>
		</sale>
	</order>
</transaction-request>

Resposta Obtida
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><api-error><errorCode>1</errorCode><errorMsg><![CDATA[processor not found ]]></errorMsg></api-error>

Código para reprodução:

$xml = file_get_contents('path/to/xml/file.xml');

$curl = curl_init('https://api.maxipago.net/UniversalAPI/postXML');
$opt = array(
	CURLOPT_POST => 1,
	CURLOPT_HTTPHEADER => array('Content-Type: text/xml; charset=UTF-8'),
	CURLOPT_SSL_VERIFYHOST => 2,
	CURLOPT_SSL_VERIFYPEER => 1,
	CURLOPT_CONNECTTIMEOUT => 30,
	CURLOPT_RETURNTRANSFER => 1,
	CURLOPT_POSTFIELDS => $xml
);

curl_setopt_array($curl, $opt);
$xmlResponse = curl_exec($curl);

$curlInfo = curl_getinfo($curl);
curl_close($curl);

if ($xmlResponse) { 
	$xml = simplexml_load_string($xmlResponse, "SimpleXMLElement", LIBXML_NOCDATA);
	$json = json_encode($xml);
	
	print_r($json);

} else { 
	throw new UnexpectedValueException('[maxiPago Class] Connection error with maxiPago! server', 503); 
}

Retornando sempre: processor not found

Olá,

Estou fazendo o teste no endpoint https://testapi.maxipago.net/UniversalAPI/postXML e sempre recebo uma mensagem de erro:

XML Response: 1

Estou tirando como base o exemplo de vocês: https://github.com/maxipago/PHP-Integration-lib/blob/master/test/boleto-mandatory.php

Dados enviados:

    $maxiPago = new maxiPago;
    $maxiPago->setCredentials("XXXXX", "XXXXXXXXXXXXXXXXXXXXXXXX");
    $maxiPago->setEnvironment("TEST");
    $maxiPago->setDebug(true);

    $data = array(
      "processorID" => '12',
      "referenceNum" => $pedido_id,
      "chargeTotal" => number_format($valor_total, 2, '.', ''),
      "bname" => $cliente_nome . ' ' . $cliente_sobrenome,
      "number" => $pedido_id,
      "expirationDate" =>  date('Y-m-d', strtotime("+1 days")),
      "instructions" =>  "Não receber após vencimento.;Não receber pagamento com cheque."
    );

    $maxiPago->boletoSale($data);

    if ($maxiPago->isErrorResponse()) {
      echo 'ERRO: ' . $maxiPago->getMessage();
      die;
    } else {
      echo $maxiPago->getBoletoUrl();
      die;
    }

Tentei usar o test/boleto-mandatory.php e retornou o mesmo erro processor not found

DocBlock shows inappropriate return types.

The docblocks (and therefore any IDE that can process them) shows a return type for the all the methods in the maxiPago class. But there aren't any. A frustrating half hour whilst wondering why my code wasn't generating any output.

String could not be parsed as XML

Olá pessoal.

Uso a lib de vocês e alguns clientes estão reportando um erro intermitente no momento da transação. Nos logs, consegui capturar a seguinte mensagem:

"String could not be parsed as XML" - lib/Request.php:47

Na linha 47 existe o seguinte código:
$xmlResponse = new SimpleXMLElement($this->xmlResponse);

Acredito que os retornos de XML são diretos da Maxipago e a realização do parser talvez seja algo complicado de se fazer uma vez que não estava armazenando o log dessas transações.

Alguém está tendo esse tipo de problema ou poderia nos ajudar com isso?

Grato.

Transação de Zero Dollar

Olá pessoal,

Utilizo o sdk php e gostaria de saber se teria alguma documentação ou alguma forma para utilizar a Transação de Zero Dollar, se seria só mais um parâmetro e qual seria esse parâmetro.

Teria algum exemplo?

Obrigado

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.