Quellcode durchsuchen

first commit SDK PHP

Fernando Goetz vor 7 Jahren
Commit
d5a92831dd
7 geänderte Dateien mit 765 neuen und 0 gelöschten Zeilen
  1. 0 0
      .gitignore
  2. 257 0
      Pagopar.php
  3. 47 0
      classes/BuyerPagopar.php
  4. 62 0
      classes/ItemPagopar.php
  5. 215 0
      classes/OrderPagopar.php
  6. 84 0
      lib/DBPagopar.php
  7. 100 0
      readme.md

+ 0 - 0
.gitignore


+ 257 - 0
Pagopar.php

@@ -0,0 +1,257 @@
+<?php
+/**
+ * Archivo SDK de Pagopar
+ * @author "Pagopar" <desarrollo@pagopar.com>
+ * @version 1 27/4/2017
+ */
+
+require_once 'lib/DBPagopar.php';
+
+require_once 'classes/OrderPagopar.php';
+
+class Pagopar{
+    //Tokens del comercio //TODO(Quitar después)
+    const TOKEN_PRIVADO = 'dflghdf5458';
+    const TOKEN_PUBLICO = '123456abcdegf';
+    //URLs de configuración
+    const URL_BASE = 'https://api.pagopar.com/api/';
+    const URL_COMERCIOS = self::URL_BASE.'comercios/1.1/iniciar-transaccion';
+    const URL_PEDIDOS = self::URL_BASE.'pedidos/1.1/traer';
+    const URL_REDIRECT = 'https://pagopar.com/pagos/%s';
+
+    //Tipos de Tokens generados
+    const TOKEN_TIPO_CONSULTA = 'CONSULTA';
+    const TOKEN_TIPO_CIUDAD = 'CIUDADES';
+    const TOKEN_TIPO_CATEGORIA = 'CATEGORIA';
+    const TOKEN_TIPO_FLETE = 'CALCULAR-FLETE';
+
+    //Base de datos
+    protected $db;
+
+    //Datos del pedido del comercio
+    private $idOrder;
+    private $hashOrder;
+
+    public $order;
+
+    /**
+     * Constructor de la clase
+     * @param int $id Id del pedido
+     * @param $db
+     * @internal param Database $PDO $db Base de Datos (Basada en PDO)
+     */
+    public function __construct($id = null,$db) {
+        $this->db = $db;
+        $this->idOrder = $id;
+        $this->order = new OrderPagopar($id);
+    }
+
+    /**
+     * Invoca a la URL de acuerdo a los parámetros
+     * @param array $args Parámetros
+     * @param  string $url Url a invocar
+     * @return string Respuesta en formato JSON
+     */
+    private function runCurl($args, $url){
+        $args = json_encode($args);
+
+        $ch = curl_init();
+        $headers= array('Accept: application/json','Content-Type: application/json');
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
+
+        $response = curl_exec($ch);
+        $error = curl_error($ch);
+        $info = curl_getinfo($ch);
+        curl_close($ch);
+
+        return $response;
+    }
+
+    /**
+     * Inicia la transacción con Pagopar y si tiene éxito al generar el pedido,
+     * redirecciona a la página de pago de Pagopar.
+     * @throws Exception
+     */
+    public function newPagoparTransaction(){
+        $orderPagopar = $this->order->makeOrder($this->idOrder);
+
+        $response = $this->runCurl($orderPagopar, self::URL_COMERCIOS);
+        $arrayResponse = json_decode($response);
+
+        //Verificar si hay error
+        if(!$arrayResponse->respuesta){
+            throw new Exception($arrayResponse->resultado);
+        }
+
+        $this->hashOrder = $arrayResponse->resultado[0]->data;
+
+        $this->db->insertTransaction($orderPagopar['id_pedido_comercio'],
+            $orderPagopar['tipo_pedido'],
+            $orderPagopar['monto_total'],
+            $this->hashOrder,
+            $orderPagopar['fecha_maxima_pago'],
+            $orderPagopar['descripcion_resumen']
+        );
+
+        $this->redirectToPagopar($this->hashOrder);
+    }
+
+    /**
+     * Redirecciona a la página de Pagopar
+     * @param string $hash Hash del pedido
+     */
+    public function redirectToPagopar($hash){
+        $url = sprintf(self::URL_REDIRECT, $hash);
+        //Redireccionamos a Pagopar
+        header('Location: '. $url);
+        exit();
+    }
+
+    /**
+     * Inicia la transacción con Pagopar y si tiene éxito al generar el pedido con valores de prueba,
+     * redirecciona a la página de pago de Pagopar.
+     */
+    public function newTestPagoparTransaction(){
+        //Creamos el comprador
+        $buyer = new BuyerPagopar();
+        $buyer->name            = 'Juan Perez';
+        $buyer->email           = 'mihares@gmail.com';
+        $buyer->cityId          = 1;
+        $buyer->tel             = '0972200046';
+        $buyer->typeDoc         = 'CI';
+        $buyer->doc             = '352221';
+        $buyer->addr            = 'Mexico 840';
+        $buyer->addRef          = 'alado de credicentro';
+        $buyer->addrCoo         = '-25.2844638,-57.6480038';
+        $buyer->ruc             = null;
+        $buyer->socialReason    = null;
+
+        //Agregamos el comprador
+        $this->order->addPagoparBuyer($buyer);
+
+        //Creamos los productos
+        $item1 = new ItemPagopar();
+        $item1->name                = "Válido 1 persona";
+        $item1->qty                 = 1;
+        $item1->price               = 1000;
+        $item1->cityId              = 1;
+        $item1->desc                = "producto";
+        $item1->url_img             = "http://www.clipartkid.com/images/318/tickets-for-the-film-festival-are-for-the-two-day-event-admission-is-lPOEYl-clipart.png";
+        $item1->weight              = '0.1';
+        $item1->category            = 3;
+        $item1->sellerPhone         = '0985885487';
+        $item1->sellerEmail         = 'mihares@gmail.com';
+        $item1->sellerAddress       = 'dr paiva ca cssssom gaa';
+        $item1->sellerAddressRef    = '';
+        $item1->sellerAddressCoo    = '-28.75438,-57.1580038';
+
+        $item2 = new ItemPagopar();
+        $item2->name                = "Heladera";
+        $item2->qty                 = 1;
+        $item2->price               = 785000;
+        $item2->cityId              = 1;
+        $item2->desc                = "producto";
+        $item2->url_img             = "https://cdn1.hendyla.com/archivos/imagenes/2017/04/09/publicacion-564c19b86b235526160f43483c76a69ee1a85c96c976c33e3e21ce6a5f9009b9-234_A.jpg";
+        $item2->weight              = '5.0';
+        $item2->category            = 3;
+        $item2->sellerPhone         = '0985885487';
+        $item2->sellerEmail         = 'mihares@gmail.com';
+        $item2->sellerAddress       = 'dr paiva ca cssssom gaa';
+        $item2->sellerAddressRef    = '';
+        $item2->sellerAddressCoo    = '-28.75438,-57.1580038';
+
+        //Agregamos los productos al pedido
+        $this->order->addPagoparItem($item1);
+        $this->order->addPagoparItem($item2);
+
+        $this->order->publicKey = self::TOKEN_PUBLICO;
+        $this->order->privateKey = self::TOKEN_PRIVADO;
+        $this->order->typeOrder = 'VENTA-COMERCIO';
+        $this->order->desc = 'Entrada Retiro';
+        $this->order->periodDays = 1;
+        $this->order->periodDays = 0;
+
+        $this->newPagoparTransaction();
+    }
+
+    /**
+     * Obtiene un JSON con el estado del pedido
+     * @param int $id Id del pedido
+     * @throws Exception
+     */
+    public function getPagoparOrderStatus($id){
+        $this->idOrder = $id;
+        $orderData = $this->db->selectTransaction("id=$id");
+        if($orderData){
+            $this->hashOrder = $orderData['hash'];
+        }else{
+            throw new Exception("Hay un error con el hash");
+        }
+        $token = $this->generateToken(self::TOKEN_TIPO_CONSULTA);
+
+        $args = ['hash_pedido'=>$this->hashOrder, 'token'=>$token, 'token_publico'=> self::TOKEN_PUBLICO];
+        $arrayResponse = $this->runCurl($args, self::URL_PEDIDOS);
+
+        print_r($arrayResponse);
+    }
+
+    /**
+     * Genera un Token para el pedido
+     * @param string $typeOfToken Tipo de token generado
+     * @return string Token generado
+     */
+    private function generateToken($typeOfToken){
+        return sha1(self::TOKEN_PRIVADO.$typeOfToken);
+    }
+
+    /**
+     * Retorna las ciudades en forma de array
+     * @param string $typeOfToken Tipo de token generado
+     * @return string Token generado
+     */
+    public function consultarCiudades(){
+        $token = $this->generateToken(self::TOKEN_TIPO_CIUDAD);
+
+        $url = self::URL_BASE.'ciudades/1.1/traer';
+        $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO];
+        $arrayResponse = $this->runCurl($args, $url);
+
+        return $arrayResponse;
+    }
+
+
+    public function consultarCategorias(){
+        $token = $this->generateToken(self::TOKEN_TIPO_CATEGORIA);
+
+        $url = self::URL_BASE.'categorias/1.1/traer';
+        $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO];
+        $arrayResponse = $this->runCurl($args, $url);
+        return $arrayResponse;
+    }
+
+    #CALCULAR-FLETE
+    public function calcularFlete($json){
+        $token = $this->generateToken(self::TOKEN_TIPO_FLETE);
+
+        $url = self::URL_BASE.'calcular-flete/1.1/traer';
+        $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO, 'dato'=> $json];
+        $arrayResponse = $this->runCurl($args, $url);
+        return $arrayResponse;
+    }
+
+    #registrar usuario
+    public function registrarUsuario(array $json){
+        $url = self::URL_BASE.'usuario/1.1/registro';
+        $args = $json;
+        $arrayResponse = $this->runCurl($args, $url);
+        return $arrayResponse;
+    }
+
+}

+ 47 - 0
classes/BuyerPagopar.php

@@ -0,0 +1,47 @@
+<?php
+/**
+ * Clase del Item de Pagopar
+ * @author "Pagopar" <desarrollo@pagopar.com>
+ * @version 1 4/5/2017
+ */
+
+class BuyerPagopar{
+
+    public $name; //string (Obligatorio) Nombre del producto
+    public $email; //string (Obligatorio) Email del comprador
+    public $cityId; //int (Obligatorio) Id de la ciudad
+    public $tel; //string Teléfono del comprador
+    public $typeDoc; //string Tipo de documento del comprador
+    public $doc; //string Documento del comprador
+    public $addr; //string Dirección del comprador
+    public $addRef; //string Referencia de la dirección del comprador
+    public $addrCoo; //string Coordenadas  (latitud y longitud separadas por coma) de la dirección del comprador
+    public $ruc; //string RUC del comprador
+    public $socialReason; //string Razón social del comprador
+
+    /**
+     * Constructor de la clase
+     */
+    public function __construct() {
+    }
+
+    /**
+     * Devuelve el producto en forma de array
+     * @return array Array del Producto
+     */
+    public function formatToArray(){
+        return [
+            'nombre' => $this->name,
+            'email' => $this->email,
+            'ciudad' => $this->cityId,
+            'telefono' => $this->tel,
+            'tipo_documento' => $this->typeDoc,
+            'documento' => $this->doc,
+            'direccion' => $this->addr,
+            'direccion_referencia' => $this->addRef,
+            'coordenadas' => $this->addrCoo,
+            'ruc' => $this->ruc,
+            'razon_social' => $this->socialReason,
+        ];
+    }
+}

+ 62 - 0
classes/ItemPagopar.php

@@ -0,0 +1,62 @@
+<?php
+/**
+ * Clase del Item de Pagopar
+ * @author "Pagopar" <desarrollo@pagopar.com>
+ * @version 1 4/5/2017
+ */
+
+class ItemPagopar{
+
+    public $name; //string (Obligatorio) Nombre del producto
+    public $qty; //int (Obligatorio) Cantidad de unidades del producto
+    public $price; //int (Obligatorio) Suma total de los precios de los productos
+    public $cityId; //int (Obligatorio) Id de la ciudad
+    public $desc; //string Descripción del producto
+    public $url_img; //string Url de la imagen del producto
+    public $weight; //string Peso del producto
+    public $sellerPhone; //string Teléfono del vendedor
+    public $sellerEmail; //string Email del vendedor
+    public $sellerAddress; //string Dirección del vendedor
+    public $sellerAddressRef; //string Referencia de la dirección del vendedor
+    public $sellerAddressCoo; //string Coordenadas (latitud y longitud separados por coma) de la dirección del vendedor
+    public $category;
+    /*public $large;
+    public $width;
+    public $height;*/
+
+    /**
+     * Constructor de la clase
+     */
+    public function __construct() {
+    }
+
+    /**
+     * Devuelve el producto en forma de array
+     * @return array Array del Producto
+     */
+    public function formatToArray(){
+        $envioAEX1['costo'] = null;
+        $envioAEX1['tiempo_entrega'] = null;
+        return [
+            'nombre' => $this->name,
+            'cantidad' => $this->qty,
+            'precio_total' => $this->price,
+            'ciudad' => $this->cityId,
+            'descripcion' => $this->desc,
+            'url_imagen' => $this->url_img,
+            'peso' => $this->weight,
+            'vendedor_telefono' => $this->sellerPhone,
+            'vendedor_email' => $this->sellerEmail,
+            'vendedor_direccion' => $this->sellerAddress,
+            'vendedor_direccion_referencia' => $this->sellerAddressRef,
+            'vendedor_direccion_coordenadas' => $this->sellerAddressCoo,
+            'opciones_envio' => [
+                'metodo_aex' => $envioAEX1
+            ],
+            'categoria' => $this->category,
+            /*'largo' => $this->large,
+            'ancho' => $this->width,
+            'alto' => $this->height*/
+        ];
+    }
+}

+ 215 - 0
classes/OrderPagopar.php

@@ -0,0 +1,215 @@
+<?php
+/**
+ * Clase del pedido de Pagopar
+ * @author "Pagopar" <desarrollo@pagopar.com>
+ * @version 1 3/5/2017
+ */
+
+require_once 'ItemPagopar.php';
+require_once 'BuyerPagopar.php';
+
+class OrderPagopar{
+    public $order = [];
+
+    public $idOrder;
+    public $publicKey;
+    public $privateKey;
+    public $typeOrder;
+    public $desc;
+    public $periodOfDaysForPayment = null;
+    public $periodOfHoursForPayment = null;
+
+    /**
+     * Constructor de la clase
+     */
+    public function __construct($id){
+        $this->idOrder = $id;
+        $this->order = [
+            'tipo_pedido' => null,
+            'fecha_maxima_pago' => null,
+            'public_key' => null,
+            'id_pedido_comercio' => null,
+            'monto_total' => null,
+            'token' => null,
+            'descripcion_resumen' => null,
+            'comprador' => null,
+            'compras_items' => null
+        ];
+    }
+
+    /**
+     * Agrega un producto (item) al pedido
+     * @param object $item (Obligatorio) Producto
+     * @throws Exception
+     */
+    public function addPagoparItem($item){
+        $error = $this->validateItemAttributes($item->name, $item->qty, $item->price, $item->cityId);
+        if($error['status']){
+            throw new Exception($error['msg']);
+        }
+        $this->order['compras_items'][] = $item->formatToArray();
+    }
+
+    /**
+     * Valida los parámetros pasados al contructor del producto
+     * @param string $name (Obligatorio) Nombre del producto
+     * @param int $qty (Obligatorio) Cantidad de unidades del producto
+     * @param int $price (Obligatorio) Suma total de los precios de los productos
+     * @param int $cityId (Obligatorio) Id de la ciudad
+     * @return array $error Array con el status (true|false) y el mensaje de error
+     */
+    private function validateItemAttributes($name, $qty, $price, $cityId){
+        $error = ['status'=>false,'msg'=>''];
+        if(empty($name)){
+            $error['status'] = true; $error['msg'] = "Hay un error con el nombre de algún producto";
+            return $error;
+        }
+        if(empty($qty) || !is_numeric($qty) || $qty < 0){
+            $error['status'] = true; $error['msg'] = "Hay un error en la cantidad del producto con nombre '{$name}'";
+            return $error;
+        }
+        if(empty($price) || !is_numeric($price) || $price < 0){
+            $error['status'] = true; $error['msg'] = "Hay un error en el precio del producto con nombre '{$name}'";
+            return $error;
+        }
+        if(empty($cityId) || !is_numeric($cityId) || $cityId < 0){
+            $error['status'] = true; $error['msg'] = "Hay un error en el ID de la ciudad del producto con nombre '{$name}'";
+            return $error;
+        }
+        return $error;
+    }
+
+    /**
+     * Agrega un comprador al pedido
+
+     * @throws Exception
+     */
+    public function addPagoparBuyer($buyer){
+        $error = $this->validateBuyerAttributes($buyer->name,$buyer->email,$buyer->cityId);
+        if($error['status']){
+            throw new Exception($error['msg']);
+        }
+
+        $this->order['comprador'] = $buyer->formatToArray();
+    }
+
+    /**
+     * Valida los parámetros del comprador pasados a addPagoparBuyer
+     * @param string $name (Obligatorio) Nombre del producto
+     * @param string $email (Obligatorio) Email del comprador
+     * @param int $cityId (Obligatorio) Id de la ciudad
+     * @return array $error Array con el status (true|false) y el mensaje de error
+     */
+    private function validateBuyerAttributes($name,$email,$cityId){
+        $error = ['status'=>false,'msg'=>''];
+        if(empty($name)){
+            $error['status'] = true; $error['msg'] = "Hay un error con el nombre del comprador";
+            return $error;
+        }
+        if(empty($email)){
+            $error['status'] = true; $error['msg'] = "Hay un error con el email del comprador";
+            return $error;
+        }
+        if(empty($cityId) || !is_numeric($cityId) || $cityId < 0){
+            $error['status'] = true; $error['msg'] = "Hay un error en el ID de la ciudad del comprador";
+            return $error;
+        }
+        return $error;
+    }
+
+    /**
+     * Valida los parámetros del pedido pasados a makeOrder
+     * @param string $publicKey (Obligatorio) Clave pública del comercio
+     * @param string $privateKey (Obligatorio) Clave privada del comercio
+     * @param int $typeOrder (Obligatorio) Tipo de pedido
+     * @return array $error Array con el status (true|false) y el mensaje de error
+     */
+    public function validateOrderAttributes($publicKey,$privateKey,$typeOrder){
+        $error = ['status'=>false,'msg'=>''];
+        //Validamos los keys
+        if(empty($publicKey)){
+            $error['status'] = true;$error['msg'] = "Hay un error con la clave pública";
+        }
+        if(empty($privateKey)){
+            $error['status'] = true;$error['msg'] = "Hay un error con la clave privada";
+        }
+        //Validamos el tipo de Pedido
+        if(empty($typeOrder)){
+            $error['status'] = true;$error['msg'] = "Hay un error con el tipo de Pedido";
+        }
+        return $error;
+    }
+
+    /**
+     * Genera un hash del pedido
+     * @param int $id Id del pedido
+     * @param int $amount Monto total del pedido
+     * @return string Hash del pedido
+     */
+    private function generateOrderHash($id = null, $amount = 0, $private_token = null){
+        return sha1($private_token . $id . $amount);
+    }
+
+    /**
+     * Genera la máxima fecha de pago
+     * @return string Fecha en formato yyyy-mm-dd hh:mm:ss
+     */
+    private function makeMaxDateForPayment(){
+        //Transformamos el día a horas
+        $daysToHours = ($this->periodOfDaysForPayment)?($this->periodOfDaysForPayment*24):0;
+        return date("Y-m-d H:i:s",mktime(date("h")+$this->periodOfHoursForPayment+$daysToHours,
+            date("i"),date("s"),date("m"),date("d"),date("Y")));
+    }
+
+    /**
+     * Obtiene el precio total de la compra
+     * @return int Suma total del precio de los Items
+     */
+    private function getTotalAmount($items){
+        $totalAmount = 0;
+        foreach ($items as $item){
+            $totalAmount += $item['precio_total'];
+        }
+        return $totalAmount;
+    }
+
+    /**
+     * Genera el pedido
+     * @param int $idOrder Id del pedido
+     * @param string $publicKey (Obligatorio) Clave pública del comercio
+     * @param string $privateKey (Obligatorio) Clave privada del comercio
+     * @param int $typeOrder (Obligatorio) Tipo de pedido
+     * @param string $desc Descripción del pedido
+     * @param int $periodDays Periodo máximo de días para completar el pago
+     * @param int $periodHours Periodo máximo de horas para completar el pago
+     * @return array Array formado del pedido
+     * @throws Exception
+     */
+    public function makeOrder(){
+        //Validamos los periodos máximos de compra de días y horas.
+        //1 día por default
+        $this->periodOfDaysForPayment =
+            ($this->periodOfDaysForPayment>=0 && is_numeric($this->periodOfDaysForPayment))?$this->periodOfDaysForPayment:1;
+        //Solo días y no horas por default
+        $this->periodOfHoursForPayment =
+            ($this->periodOfHoursForPayment>=0 && is_numeric($this->periodOfHoursForPayment))?$this->periodOfHoursForPayment:0;
+
+        $error = $this->validateOrderAttributes($this->publicKey,$this->privateKey,$this->typeOrder);
+        if($error['status']){
+            throw new Exception($error['msg']);
+        }
+
+        $totalAmount = $this->getTotalAmount($this->order['compras_items']);
+
+        //Datos de configuración del pedido
+        $this->order['public_key'] = $this->publicKey;
+        $this->order['tipo_pedido'] = $this->typeOrder;
+        $this->order['fecha_maxima_pago'] = $this->makeMaxDateForPayment();
+        $this->order['id_pedido_comercio'] = $this->idOrder;
+        $this->order['monto_total'] = $totalAmount;
+        $this->order['token'] = $this->generateOrderHash($this->idOrder,$totalAmount,$this->privateKey);
+        $this->order['descripcion_resumen'] = $this->desc;
+
+        return $this->order;
+    }
+}

+ 84 - 0
lib/DBPagopar.php

@@ -0,0 +1,84 @@
+<?php
+/**
+ * Archivo de configuración de la base de datos de los pedidos
+ * @author "Pagopar" <desarrollo@pagopar.com>
+ * @version 1 8/5/2017
+ */
+
+class DBPagopar extends PDO{
+
+    /**
+     * Setea el atributo PDO con la instancia enviada por parámetro
+     * @param string $name Nombre de la base de Datos
+     * @param string $user Nombre del usuario de la BD.
+     * @param string $pass Contraseña de la BD.
+     */
+    public function __construct($name=null,$user=null,$pass=null) {
+        //Nueva conexión a la base de datos
+        parent::__construct('mysql:host=localhost;dbname='.$name,$user,$pass,
+            [PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+        //Cración de la tabla si no existe
+        $this->exec("CREATE TABLE IF NOT EXISTS transactions(
+                id integer primary key,
+                typeOrder varchar(120),
+                totalAmount decimal(15,2),
+                hash varchar(255),
+                maxDateForPayment varchar(120), 
+                buyerId integer,
+                orderItems integer,
+                description varchar(255), 
+                created datetime default current_timestamp
+            )");
+    }
+
+    /**
+     * Registra una nueva transacción en la tabla de transacciones y devuelve el ID del registro.
+     * @param int $id Id de la transacción
+     * @param string $typeOrder Tipo de orden,
+     * @param float $totalAmount Monto total de la compra
+     * @param string $hash Hash del pedido retornado por el webservice
+     * @param string $maxDateForPayment Fecha máxima para el pago del pedido (Formato dd:mm:yyyy hh:mm:ss)
+     * @param string $desc Descripción del pedido
+     * @return int el número de transacción
+     */
+    public function insertTransaction($id,$typeOrder,$totalAmount,$hash,$maxDateForPayment,$desc) {
+        $this->prepare("INSERT INTO transactions (id,typeOrder,totalAmount,hash,maxDateForPayment,description) VALUES(?,?,?,?,?,?)")
+            ->execute([$id,$typeOrder,$totalAmount,$hash,$maxDateForPayment,$desc]);
+        return $this->lastInsertId();
+    }
+
+    /**
+     * Retorna la transacción que cumpla con los requisitos del where
+     * @param string $where where statement
+     * @return array
+     */
+    public function selectTransaction($where = '') {
+        $sth = $this->prepare("SELECT * FROM transactions WHERE {$where} LIMIT 1");
+        $sth->execute();
+        $result = $sth->fetchAll();
+        if (empty($result)) {
+            return false;
+        }
+        return $result[0];
+    }
+
+    /**
+     * Actualiza una transacción, según los campos enviados por el parámetro.
+     * @param array key=>value de los campos retornados desde el gateway
+     * @param array key=>value para el where
+     */
+    public function updateTransaction(Array $data, Array $w) {
+        $set = array();
+        foreach (array_keys($data) as $key) {
+            $set[] = "$key = :$key";
+        }
+        $where = array();
+        foreach (array_keys($w) as $key) {
+            $where[] = "$key = :$key";
+        }
+
+        $this->prepare("UPDATE transactions SET  " . implode(",", $set)
+            . " where " . implode(" and ", $where) )
+            ->execute(array_merge($data, $w));
+    }
+}

+ 100 - 0
readme.md

@@ -0,0 +1,100 @@
+# SDK Pagopar
+
+## Primeros pasos
+
+#### 1. Usar una base de datos
+
+**Es necesario crear una base de datos MySQL o usar una ya existente** antes de usar el SDK de Pagopar.
+
+#### 2. Inicializar la base de datos
+
+Instanciamos la clase `DBPagopar` con los datos necesarios para inicializar la base de datos. El SDK automáticamente crea una tabla llamada `transactions` en la que se guardarán los pedidos.
+ Los parámetros a ser pasados son todas cadenas: `dbname` (el nombre de la base de datos), `dbuser` (el usuario) y `dbpass` (la contraseña).
+
+
+```php
+ $db = new DBPagopar( dbname , dbuser , dbpass );
+```
+
+#### 3. Elegir un nuevo id para un pedido
+
+Debemos elegir un id para realizar un nuevo pedido o consultar una transacción realizada anteriormente. **En ambos casos el id debe ser un entero mayor a cero**.
+
+En el caso de una **nueva transacción**, debemos elegir un **valor superior al id del último pedido realizado**.
+
+## Realizar un nuevo pedido
+
+## Código de ejemplo completo
+
+```php
+
+    $db = new DBPagopar( 'dbname' , 'dbuser' , 'dbpass' );
+
+    /*Generar nuevo pedido*/
+    //Id mayor al Id del último pedido, solo para pruebas
+    $idNuevoPedido = nuevo_id;
+    //Generamos el pedido
+    $pedidoPagoPar = new Pagopar($idNuevoPedido, $db);
+
+    //Creamos el comprador
+    $buyer = new BuyerPagopar();
+    $buyer->name            = 'Juan Perez';
+    $buyer->email           = 'correo_electrónico';
+    $buyer->cityId          = 1;
+    $buyer->tel             = '0972200046';
+    $buyer->typeDoc         = 'CI';
+    $buyer->doc             = '352221';
+    $buyer->addr            = 'Mexico 840';
+    $buyer->addRef          = 'alado de credicentro';
+    $buyer->addrCoo         = '-25.2844638,-57.6480038';
+    $buyer->ruc             = null;
+    $buyer->socialReason    = null;
+    //Agregamos el comprador
+    $this->order->addPagoparBuyer($buyer);
+
+    //Creamos los productos
+    $item1 = new ItemPagopar();
+    $item1->name                = "Válido 1 persona";
+    $item1->qty                 = 1;
+    $item1->price               = 10000;
+    $item1->cityId              = 1;
+    $item1->desc                = "producto";
+    $item1->url_img             = "https://www.hendyla.com/images/lazo_logo.png";
+    $item1->weight              = '0.1';
+    $item1->sellerPhone         = '0985885487';
+    $item1->sellerEmail         = 'correo_electrónico';
+    $item1->sellerAddress       = 'lorep ipsum';
+    $item1->sellerAddressRef    = '';
+    $item1->sellerAddressCoo    = '-28.75438,-57.1580038';
+
+    $item2 = new ItemPagopar();
+    $item2->name                = "Heladera";
+    $item2->qty                 = 1;
+    $item2->price               = 785000;
+    $item2->cityId              = 1;
+    $item2->desc                = "producto";
+    $item2->url_img             = "https://www.hendyla.com/images/lazo_logo.png";
+    $item2->weight              = '5.0';
+    $item2->sellerPhone         = '0985885487';
+    $item2->sellerEmail         = 'correo_electrónico';
+    $item2->sellerAddress       = 'lorep ipsum dolor';
+    $item2->sellerAddressRef    = '';
+    $item2->sellerAddressCoo    = '-28.75438,-57.1580038';
+
+    //Agregamos los productos al pedido
+    $this->order->addPagoparItem($item1);
+    $this->order->addPagoparItem($item2);
+
+    //Pasamos los parámetros para el pedido
+    $this->order->publicKey = 'clave pública';
+    $this->order->privateKey = 'clave privada';
+    $this->order->typeOrder = 'VENTA-COMERCIO';
+    $this->order->desc = 'Entrada Retiro';
+    $this->order->periodDays = 1;
+    $this->order->periodDays = 0;
+
+    //Hacemos el pedido
+    $this->newPagoparTransaction();
+
+
+  ```