Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá pessoal,
Como vimos na documentação da API, precisamos enviar um XML com a seguinte estrutura:
<?xml version="1.0" encoding="UTF-8"?>
<carrinho>
<recebedor>
<api_key>API_KEY_GERADO</api_key>
<email>EMAIL_DA_CONTA_AKATUS</email>
</recebedor>
<pagador>
<nome>Jose Antonio</nome>
<email>ze@antonio.com.br</email>
<enderecos>
<endereco>
<tipo>entrega</tipo>
<logradouro>Rua Labib Marrar</logradouro>
<numero>129</numero>
<bairro>Jardim Santa Cruz</bairro>
<cidade>São Paulo</cidade>
<estado>SP</estado>
<pais>BRA</pais>
<cep>04182-040</cep>
</endereco>
</enderecos>
<telefones>
<telefone>
<tipo>residencial</tipo>
<numero>1433019799</numero>
</telefone>
</telefones>
</pagador>
<produtos>
<produto>
<codigo>UFC1403</codigo>
<descricao>Luva de box com ferradura dentro</descricao>
<quantidade>1</quantidade>
<preco>148.99</preco>
<peso>8.5</peso>
<frete>16.45</frete>
<desconto>10.00</desconto>
</produto>
<produto>
<codigo>UFC1403</codigo>
<descricao>Luva de box com ferradura dentro</descricao>
<quantidade>1</quantidade>
<preco>148.99</preco>
<peso>8.5</peso>
<frete>16.45</frete>
<desconto>10.00</desconto>
</produto>
</produtos>
<transacao>
<desconto_total>20.00</desconto_total>
<peso_total>17.0</peso_total>
<frete_total>32.90</frete_total>
<moeda>BRL</moeda>
<referencia>abc1234</referencia>
<meio_de_pagamento>boleto</meio_de_pagamento>
</transacao>
</carrinho>
Como podemos ver nesse XML, temos um nó principal chamado carrinho, e alguns nós filhos:
-
recebedor: Esse nó conterá os dados da entidade (pessoa física ou jurídica) que receberá o pagamento. Ele será preenchido com o email da conta Akatus e a chave da API.
-
pagador: Esse nó conterá os dados do cliente que está fazendo o pagamento, seja via cartão de crédito, ou via boleto bancário. Ele será preenchido com o nome, email, lista de endereços e lista de telefones do cliente.
-
produtos: Esse nó representa o carrinho de compras do cliente. Todos os produtos, seus preços e suas respectivas quantidades serão colocados aqui.
-
transacao: Esse nó é o fechamento do carrinho. Ele será preenchido com o total da transação, desconto, frete e o meio de pagamento que será utilizado.
Estruturalmente, o carrinho se parecerá com o seguinte:
/applications/core/interface/imageproxy/imageproxy.php?img=http://conteudo.imasters.com.br/24690/47656.png&key=baa237c86d09a00216c6976a2c7bb6164a83fa1bd75247e325d6a03ed51a0ec7" />Então:
Pagador, Telefone e Endereço:
Address.php
<?php
/**
* Representação do endereço do comprador na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Address {
/**
* @var string
*/
private $city;
/**
* @var string
*/
private $country;
/**
* @var string
*/
private $neighborhood;
/**
* @var integer
*/
private $number;
/**
* @var string
*/
private $state;
/**
* @var string
*/
private $street;
/**
* @var string
*/
private $type;
/**
* @var string
*/
private $zip;
/**
* @return string
*/
public function getCity() {
return $this->city;
}
/**
* @return string
*/
public function getCountry() {
return $this->country;
}
/**
* @return string
*/
public function getNeighborhood() {
return $this->neighborhood;
}
/**
* @return integer
*/
public function getNumber() {
return $this->number;
}
/**
* @return string
*/
public function getState() {
return $this->state;
}
/**
* @return string
*/
public function getStreet() {
return $this->street;
}
/**
* @return string
*/
public function getType() {
return $this->type;
}
/**
* @return string
*/
public function getZip() {
return $this->zip;
}
/**
* @param string $city
*/
public function setCity($city) {
$this->city = $city;
}
/**
* @param string $country
*/
public function setCountry($country) {
$this->country = $country;
}
/**
* @param string $neighborhood
*/
public function setNeighborhood($neighborhood) {
$this->neighborhood = $neighborhood;
}
/**
* @param integer $number
*/
public function setNumber($number) {
$this->number = $number;
}
/**
* @param string $state
*/
public function setState($state) {
$this->state = $state;
}
/**
* @param string $street
*/
public function setStreet($street) {
$this->street = $street;
}
/**
* @param string $type
*/
public function setType($type) {
$this->type = $type;
}
/**
* @param string $zip
*/
public function setZip($zip) {
$this->zip = $zip;
}
}
Phone.php
<?php
/**
* Representação de um telefone na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Phone {
/**
* @var string
*/
private $number;
/**
* @var string
*/
private $type;
/**
* @param string $type
* @param string $number
*/
public function __construct($type, $number) {
$this->setType($type);
$this->setNumber($number);
}
/**
* @return string
*/
public function getNumber() {
return $this->number;
}
/**
* @return string
*/
public function getType() {
return $this->type;
}
/**
* @param string $number
*/
public function setNumber($number) {
$this->number = $number;
}
/**
* @param string $type
*/
public function setType($type) {
$this->type = $type;
}
}
Buyer.php
<?php
require_once 'Address.php';
require_once 'Phone.php';
/**
* Representação do comprador na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Buyer {
/**
* @var array[Address]
*/
private $addresses = array();
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $name;
/**
* @var array[Phone]
*/
private $phones = array();
/**
* @param string $name
*/
public function __construct( $name, $email ) {
$this->setName( $name );
$this->setEmail( $email );
}
/**
* @param Address $address
*/
public function addAddress( Address $address ) {
$this->addresses[] = $address;
}
/**
* Cria uma instância de Phone e já adiciona na lista de telefones do
* comprador.
* @param string $type
* @param string $number
*/
public function addNewPhone($type, $number) {
$this->addPhone( new Phone($type, $number));
}
/**
* @param Phone $phone
*/
public function addPhone( Phone $phone ) {
$this->phones[] = $phone;
}
/**
* Cria uma instância de Address e já adiciona na lista de endereços do
* comprador.
* @param string $type
* @return Address
*/
public function createAddress( $type ) {
$address = new Address();
$address->setType($type);
$this->addAddress($address);
return $address;
}
/**
* @return Iterator
*/
public function getAddressIterator() {
return new ArrayIterator( $this->addresses );
}
/**
* @return string
*/
public function getEmail() {
return $this->email;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @return Iterator
*/
public function getPhoneIterator() {
return new ArrayIterator( $this->phones );
}
/**
* @param string $email
*/
public function setEmail( $email ) {
$this->email = $email;
}
/**
* @param string $name
*/
public function setName( $name ) {
$this->name = $name;
}
}
Agora, a classe que representa o recebedor:
Recebedor
<?php
/**
* Representação do recebedor na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Receiver {
/**
* @var string
*/
private $apiKey;
/**
* @var string
*/
private $email;
/**
* @param string $apiKey
* @param string $email
*/
public function __construct( $apiKey, $email ) {
$this->setApiKey($apiKey);
$this->setEmail($email);
}
/**
* @return string
*/
public function getApiKey() {
return $this->apiKey;
}
/**
* @return string
*/
public function getEmail() {
return $this->email;
}
/**
* @param string $apiKey
*/
public function setApiKey($apiKey) {
$this->apiKey = $apiKey;
}
/**
* @param string $email
*/
public function setEmail($email) {
$this->email = $email;
}
}
Com o pagador e recebedor, vamos ver o produto:
Product.php
<?php
/**
* Representação de um produto na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Product {
/**
* @var string
*/
private $description;
/**
* @var float
*/
private $discount = 0;
/**
* @var string
*/
private $id;
/**
* @var float
*/
private $price;
/**
* @var integer
*/
private $quantity;
/**
* @var float
*/
private $shipping = 0;
/**
* @var float
*/
private $weight;
/**
* @param string $description
* @param float $price
* @param float $weight
* @param integer $quantity
*/
public function __construct( $description, $price, $weight, $quantity = 1 ) {
$this->setDescription($description);
$this->setPrice($price);
$this->setQuantity($quantity);
$this->setWeight($weight);
}
/**
* @return string
*/
public function getDescription() {
return $this->description;
}
/**
* @return float
*/
public function getDiscount() {
return $this->discount;
}
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @return float
*/
public function getPrice() {
return $this->price;
}
/**
* @return integer
*/
public function getQuantity() {
return $this->quantity;
}
/**
* @return float
*/
public function getShipping() {
return $this->shipping;
}
/**
* @return float
*/
public function getWeight() {
return $this->weight;
}
/**
* @param string $description
*/
public function setDescription($description) {
$this->description = $description;
}
/**
* @param float $discount
*/
public function setDiscount($discount) {
$this->discount = (float) $discount;
}
/**
* @param string $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param float $price
*/
public function setPrice($price) {
$this->price = (float) $price;
}
/**
* @param integer $quantity
*/
public function setQuantity($quantity) {
$this->quantity = (int) $quantity;
}
/**
* @param float $shipping
*/
public function setShipping($shipping) {
$this->shipping = (float) $shipping;
}
/**
* @param float $weight
*/
public function setWeight($weight) {
$this->weight = (float) $weight;
}
}
E agora o carrinho:
Cart.php
<?php
require_once 'Transaction.php';
require_once 'Product.php';
/**
* Representação do carrinho na integração com a API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Cart implements Countable, IteratorAggregate {
/**
* @var Buyer
*/
private $buyer;
/**
* @var array[Product]
*/
private $products;
/**
* @var Receiver
*/
private $receiver;
/**
* @var Transaction
*/
private $transaction;
/**
* @param Buyer $buyer
* @param Receiver $receiver
*/
public function __construct( Buyer $buyer, Receiver $receiver ) {
$this->buyer = $buyer;
$this->products = array();
$this->receiver = $receiver;
$this->transaction = new Transaction();
}
/**
* Adiciona um novo produto ao carrinho.
* @param string $description
* @param float $price
* @param float $weight
* @param integer $quantity
* @param float $shipping
* @param float $discount
* @return Product
*/
public function addNewProduct($description,
$price,
$weight,
$quantity = 1,
$shipping = 0,
$discount = 0) {
$product = new Product($description, $price, $weight,$quantity);
$product->setDiscount((float) $discount);
$product->setShipping((float) $shipping);
$this->addProduct($product);
return $product;
}
/**
* @param Product $product
*/
public function addProduct( Product $product ) {
$this->products[] = $product;
$this->transaction->setDiscount(
$this->transaction->getDiscount() + $product->getDiscount()
);
$this->transaction->setShipping(
$this->transaction->getShipping() + $product->getShipping()
);
$this->transaction->setWeight(
$this->transaction->getWeight() +
($product->getWeight() * $product->getQuantity())
);
}
/* (non-PHPdoc)
* @see Countable::count()
*/
public function count() {
return count( $this->products );
}
/**
* @return Buyer
*/
public function getBuyer() {
return $this->buyer;
}
/* (non-PHPdoc)
* @see IteratorAggregate::getIterator()
*/
public function getIterator() {
return new ArrayIterator( $this->products );
}
/**
* @return Receiver
*/
public function getReceiver() {
return $this->receiver;
}
/**
* @return Transaction
*/
public function getTransaction() {
return $this->transaction;
}
}
Como podemos ver, o carrinho já cria a instância de Transaction. Ela também ajusta alguns valores dessa instância, conforme produtos vão sendo adicionados ao carrinho.
Transaction.php
<?php
/**
* Representação de uma transação na API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class Transaction {
/**
* Método de pagamento padrão
* @var string
*/
const DEFAULT_PAYMENT_METHOD = 'boleto';
/**
* Moeda padrão.
* @var string
*/
const DEFAULT_CURRENCY = 'BRL';
/**
* @var string
*/
private $currency = Transaction::DEFAULT_CURRENCY;
/**
* @var float
*/
private $discount = 0;
/**
* @var string
*/
private $paymentMethod = Transaction::DEFAULT_PAYMENT_METHOD;
/**
* @var string
*/
private $reference;
/**
* @var float
*/
private $shipping = 0;
/**
* @var float
*/
private $weight = 0;
/**
* @return string
*/
public function getCurrency() {
return $this->currency;
}
/**
* @return float
*/
public function getDiscount() {
return $this->discount;
}
/**
* @return string
*/
public function getPaymentMethod() {
return $this->paymentMethod;
}
/**
* @return string
*/
public function getReference() {
return $this->reference;
}
/**
* @return float
*/
public function getShipping() {
return $this->shipping;
}
/**
* @return float
*/
public function getWeight() {
return $this->weight;
}
/**
* @param string $currency
*/
public function setCurrency($currency) {
$this->currency = $currency;
}
/**
* @param float $discount
*/
public function setDiscount($discount) {
$this->discount = $discount;
}
/**
* @param string $paymentMethod
*/
public function setPaymentMethod($paymentMethod) {
$this->paymentMethod = $paymentMethod;
}
/**
* @param string $reference
*/
public function setReference($reference) {
$this->reference = $reference;
}
/**
* @param float $shipping
*/
public function setShipping($shipping) {
$this->shipping = $shipping;
}
/**
* @param float $weight
*/
public function setWeight($weight) {
$this->weight = $weight;
}
}
Nesse instante temos algumas classes que representam a estrutura hierárquica do XML que devemos enviar para a Akatus. Precisamos agora de um participante responsável por receber essa estrutura e escrever o XML:
AkatusCartMarshaller.php
<?php
/**
* Serialização do carrinho para XML para integração com a API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class AkatusCartMarshaller {
/**
* @return string
*/
public function marshall( Cart $cart ) {
$dom = new DOMDocument('1.0','UTF-8');
$carrinho = $dom->createElement('carrinho');
$carrinho->appendChild($this->createReceiverElement($dom, $cart));
$carrinho->appendChild($this->createBuyerElement($dom, $cart));
$carrinho->appendChild($this->createProductsElement($dom, $cart));
$carrinho->appendChild($this->createTransactionElement($dom, $cart));
$dom->appendChild($carrinho);
return $dom->saveXML();
}
private function createReceiverElement(DOMDocument $dom, Cart $cart) {
$receiver = $cart->getReceiver();
$receiverElement = $dom->createElement('recebedor');
$receiverElement->appendChild(
$dom->createElement('api_key', $receiver->getApiKey())
);
$receiverElement->appendChild(
$dom->createElement('email', $receiver->getEmail())
);
return $receiverElement;
}
private function createBuyerElement(DOMDocument $dom, Cart $cart) {
$buyer = $cart->getBuyer();
$buyerElement = $dom->createElement('pagador');
$buyerElement->appendChild(
$dom->createElement('nome', $buyer->getName())
);
$buyerElement->appendChild(
$dom->createElement('email', $buyer->getEmail())
);
$addressesElement = $dom->createElement('enderecos');
$buyerElement->appendChild($addressesElement);
foreach ( $buyer->getAddressIterator() as $address ) {
$addressesElement->appendChild(
$this->createAddressElement($dom, $address)
);
}
$phonesElement = $dom->createElement('telefones');
$buyerElement->appendChild($phonesElement);
foreach ($buyer->getPhoneIterator() as $phone ) {
$phonesElement->appendChild(
$this->createPhoneElement($dom, $phone)
);
}
return $buyerElement;
}
private function createAddressElement(DOMDocument $dom, Address $address) {
$addressElement = $dom->createElement('endereco');
$addressElement->appendChild(
$dom->createElement('tipo', $address->getType())
);
$addressElement->appendChild(
$dom->createElement('logradouro', $address->getStreet())
);
$addressElement->appendChild(
$dom->createElement('numero', $address->getNumber())
);
$addressElement->appendChild(
$dom->createElement('bairro', $address->getNeighborhood())
);
$addressElement->appendChild(
$dom->createElement('cidade', $address->getCity())
);
$addressElement->appendChild(
$dom->createElement('estado', $address->getState())
);
$addressElement->appendChild(
$dom->createElement('pais', $address->getCountry())
);
$addressElement->appendChild(
$dom->createElement('cep', $address->getZip())
);
return $addressElement;
}
private function createPhoneElement(DOMDocument $dom, Phone $phone) {
$phoneElement = $dom->createElement('phone');
$phoneElement->appendChild(
$dom->createElement('tipo', $phone->getType())
);
$phoneElement->appendChild(
$dom->createElement('numero', $phone->getNumber())
);
return $phoneElement;
}
private function createProductsElement(DOMDocument $dom, Cart $cart) {
$productsElement = $dom->createElement('produtos');
foreach ($cart->getIterator() as $product) {
$productsElement->appendChild(
$this->createProductElement($dom, $product)
);
}
return $productsElement;
}
private function createProductElement(DOMDocument $dom, Product $product) {
$productElement = $dom->createElement('produto');
$productElement->appendChild(
$dom->createElement('codigo', $product->getId())
);
$productElement->appendChild(
$dom->createElement('descricao', $product->getDescription())
);
$productElement->appendChild(
$dom->createElement('quantidade', $product->getQuantity())
);
$productElement->appendChild(
$dom->createElement('preco', $product->getPrice())
);
$productElement->appendChild(
$dom->createElement('peso', $product->getWeight())
);
$productElement->appendChild(
$dom->createElement('frete', $product->getShipping())
);
$productElement->appendChild(
$dom->createElement('desconto', $product->getDiscount())
);
return $productElement;
}
private function createTransactionElement(DOMDocument $dom, Cart $cart) {
$transaction = $cart->getTransaction();
$transactionElement = $dom->createElement('transacao');
$transactionElement->appendChild(
$dom->createElement('desconto_total', $transaction->getDiscount())
);
$transactionElement->appendChild(
$dom->createElement('peso_total', $transaction->getWeight())
);
$transactionElement->appendChild(
$dom->createElement('frete_total', $transaction->getShipping())
);
$transactionElement->appendChild(
$dom->createElement('moeda', $transaction->getCurrency())
);
$transactionElement->appendChild(
$dom->createElement('referencia', $transaction->getReference())
);
$transactionElement->appendChild(
$dom->createElement('meio_de_pagamento', $transaction->getPaymentMethod())
);
return $transactionElement;
}
}
O método marshall() vai receber o carrinho e retornar um XML. Com esse XML faremos o POST para a Akatus:
AkatusCartApi.php
<?php
require_once 'AkatusCartMarshaller.php';
require_once 'AkatusCartResponseUnMarshaller.php';
/**
* Integração com a API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class AkatusCartApi {
/**
* Endpoint de produção
* @var string
*/
const ENDPOINT = 'https://www.akatus.com/api/v1/carrinho.xml';
/**
* Endpoint de testes
* @var string
*/
const TEST_ENDPOINT = 'https://dev.akatus.com/api/v1/carrinho.xml';
/**
* @var AkatusCartMarshaller
*/
private $marshaller;
/**
* @var AkatusCartResponseUnMarshaller
*/
private $unmarshaller;
/**
* @var boolean
*/
private $test = false;
/**
* @param AkatusCartMarshaller $marshaller
*/
public function __construct(AkatusCartMarshaller $marshaller = null,
AkatusCartResponseUnMarshaller $unmarshaller = null ) {
if ( $marshaller == null ) {
$marshaller = new AkatusCartMarshaller();
}
if ( $unmarshaller == null ) {
$unmarshaller = new AkatusCartResponseUnMarshaller();
}
$this->marshaller = $marshaller;
$this->unmarshaller = $unmarshaller;
}
/**
* Executa a operação.
* @param Cart $cart O carrinho que será enviado.
* @return AkatusCartResponse A resposta do serviço.
* @throws RuntimeException
*/
public function execute( Cart $cart ) {
$endpoint = $this->test ? self::TEST_ENDPOINT: self::ENDPOINT;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $endpoint );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_POST, true );
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->marshaller->marshall($cart));
$response = curl_exec( $curl );
$errno = curl_errno($curl);
$error = curl_error($curl);
curl_close($curl);
if ($errno != 0) {
throw new RuntimeException($error, $errno);
}
libxml_use_internal_errors(false);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadXML($response);
$libxmlErrors = libxml_get_errors();
if (count($libxmlErrors) != 0) {
$e = null;
foreach ( $libxmlErrors as $libxmlError ) {
$e = new UnexpectedValueException($libxmlError->message,
$libxmlError->code, $e);
}
libxml_clear_errors();
throw new RuntimeException( 'XML error', null, $e );
} else {
try {
$response = $this->unmarshaller->unmarshall($dom);
if ($response->getStatus()=='erro') {
throw new RuntimeException($response->getDescription());
}
return $response;
} catch (UnexpectedValueException $e) {
throw new RuntimeException('Unmarshall problem', null, $e);
}
}
}
/**
* Define a execução da operação no ambiente de testes.
* @return AkatusCartApi
*/
public function test() {
$this->test = true;
return $this;
}
}
O método execute fará todo o trabalho, receberá a instância de Cart, usará nosso serializador para criar o XML, enviará o POST para a Akatus e usará o deserializador para criar uma instância de AkatusCartResponse, que conterá a representação do seguinte XML:
XML em caso de sucesso
<?xml version="1.0" encoding="UTF-8"?>
<resposta>
<carrinho>37b4529f-6982-4c77-ba7d-f925113f55e2</carrinho>
<status>Aguardando Pagamento</status>
<transacao>1f5cbb15-9695-4947-9154-19d6b08cf816</transacao>
<url_retorno>[http://www.akatus.com/boleto/MWY1Y2JiMTUtOTY5NS00OTQ3LTkxNTQtMTlkNmIwOGNmODE2.html](http://www.akatus.com/boleto/MWY1Y2JiMTUtOTY5NS00OTQ3LTkxNTQtMTlkNmIwOGNmODE2.html)
</resposta>
XML em caso de falha
<?xml version="1.0" encoding="UTF-8"?>
<resposta>
<status>erro</status>
<descricao>descrição do erro</descricao>
</resposta>
Para poder criar a instância de AkatusCartResponse, precisamos do serializador, que segue abaixo:
AkatusCartResponseUnMarshaller.php
<?php
require_once 'AkatusCartResponse.php';
**
* Deserialização da resposta XML da integração com a API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class AkatusCartResponseUnMarshaller {
/**
* @param DOMDocument $dom
* @return AkatusCartResponse
* @throws UnexpectedValueException
*/
public function unMarshall(DOMDocument $dom) {
$akatusCartResponse = new AkatusCartResponse();
$akatusCartResponse->setStatus($this->getStatus($dom));
$akatusCartResponse->setDescription($this->getDescription($dom));
$akatusCartResponse->setCart($this->getCart($dom));
$akatusCartResponse->setTransaction($this->getTransaction($dom));
$akatusCartResponse->setReturnUrl($this->getReturnUrl($dom));
return $akatusCartResponse;
}
private function getNodeValue(DOMDocument $dom, $tagName) {
$element = $dom->getElementsByTagName($tagName)->item(0);
return $element == null ? null : $element->nodeValue;
}
private function getStatus(DOMDocument $dom) {
$status = $this->getNodeValue($dom, 'status');
if ( $status == null ) {
throw new UnexpectedValueException('Invalid XML');
}
return $status;
}
private function getCart(DOMDocument $dom) {
return $this->getNodeValue($dom, 'carrinho');
}
private function getDescription(DOMDocument $dom) {
return $this->getNodeValue($dom,'descricao');
}
private function getTransaction(DOMDocument $dom) {
return $this->getNodeValue($dom,'transacao');
}
private function getReturnUrl(DOMDocument $dom) {
return $this->getNodeValue($dom,'url_retorno');
}
}
O método unMarshall receberá uma instância de DOMDocument, que contém os nós do XML de resposta, ela retornará a instância de AkatusCartResponse, cuja classe segue abaixo:
AkatusCartResponse.php
<?php
/**
* Resposta da API da Akatus
* @author João Batista Neto <neto.joaobatista@gmail.com.br>
*/
class AkatusCartResponse {
/**
* @var string
*/
private $cart;
/**
* @var string
*/
private $description;
/**
* @var string
*/
private $returnUrl;
/**
* @var string
*/
private $status;
/**
* @var string
*/
private $transaction;
/**
* @return string
*/
public function getCart() {
return $this->cart;
}
/**
* @return string
*/
public function getDescription() {
return $this->description;
}
/**
* @return string
*/
public function getReturnUrl() {
return $this->returnUrl;
}
/**
* @return string
*/
public function getStatus() {
return $this->status;
}
/**
* @return string
*/
public function getTransaction() {
return $this->transaction;
}
/**
* @param string $cart
*/
public function setCart($cart) {
$this->cart = $cart;
}
/**
* @param string $description
*/
public function setDescription($description) {
$this->description = $description;
}
/**
* @param string $returnUrl
*/
public function setReturnUrl($returnUrl) {
$this->returnUrl = $returnUrl;
}
/**
* @param string $status
*/
public function setStatus($status) {
$this->status = $status;
}
/**
* @param string $transaction
*/
public function setTransaction($transaction) {
$this->transaction = $transaction;
}
}
Nesse instante, temos todos os participantes para fazer a integração, para usar tudo isso basta fazer o seguinte:
<?php
require 'AkatusCartApi.php';
require 'Receiver.php';
require 'Buyer.php';
require 'Cart.php';
receiver = new Receiver('XXX', 'user@domain.com');
//dados do comprador
$buyer = new Buyer('Jose Antonio', 'ze@antonio.com.br');
//telefone do comprador
$buyer->addNewPhone('residencial','1699999999');
//endereço do comprador
$address = $buyer->createAddress('entrega');
$address->setCity('Cidade');
$address->setCountry('Brasil');
$address->setNeighborhood('Bairro');
$address->setNumber(0);
$address->setState('estado');
$address->setStreet('Rua dos bobos');
$address->setZip('00000000');
//carrinho e os produtos comprados
$cart = new Cart($buyer, $receiver);
$cart->addNewProduct('Produto 1', 148.99, 8.5, 1, 16.45, 10)->setId('UFC1403');
$cart->addNewProduct('Produto 3', 148.99, 8.5, 1, 16.45, 10)->setId('UFC1403');
cart->getTransaction()->setReference('abc1234');
try {
$akatusCartApi = new AkatusCartApi();
//o método test() indica que estamos usando o ambiente de testes,
//para usar o ambiente de produção, basta não suar o método test.
var_dump( $akatusCartApi->test()->execute($cart) );
} catch (RuntimeException $e) {
//opz, alguma coisa saiu errada.
//log...
echo $e->getMessage();
}
E pronto, o método execute() retornará a instância de AkatusCartResponse que, se tudo estiver okay, podemos usar o método getReturnUrl() para redirecionar o cliente.
O código foi colocado no github: https://github.com/A.../codesample_api
Para clonar:
git clone git://github.com/Akatus/codesample_api.git
Carregando comentários...