Pagopar.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. /**
  3. * Archivo SDK de Pagopar
  4. * @author "Pagopar" <desarrollo@pagopar.com>
  5. * @version 1 27/4/2017
  6. */
  7. require_once 'lib/DBPagopar.php';
  8. require_once 'classes/OrderPagopar.php';
  9. class Pagopar{
  10. //Tokens del comercio //TODO(Quitar después)
  11. const TOKEN_PRIVADO = 'dflghdf5458';
  12. const TOKEN_PUBLICO = '123456abcdegf';
  13. //URLs de configuración
  14. const URL_BASE = 'https://api.pagopar.com/api/';
  15. const URL_COMERCIOS = self::URL_BASE.'comercios/1.1/iniciar-transaccion';
  16. const URL_PEDIDOS = self::URL_BASE.'pedidos/1.1/traer';
  17. const URL_REDIRECT = 'https://pagopar.com/pagos/%s';
  18. //Tipos de Tokens generados
  19. const TOKEN_TIPO_CONSULTA = 'CONSULTA';
  20. const TOKEN_TIPO_CIUDAD = 'CIUDADES';
  21. const TOKEN_TIPO_CATEGORIA = 'CATEGORIA';
  22. const TOKEN_TIPO_FLETE = 'CALCULAR-FLETE';
  23. //Base de datos
  24. protected $db;
  25. //Datos del pedido del comercio
  26. private $idOrder;
  27. private $hashOrder;
  28. public $order;
  29. /**
  30. * Constructor de la clase
  31. * @param int $id Id del pedido
  32. * @param $db
  33. * @internal param Database $PDO $db Base de Datos (Basada en PDO)
  34. */
  35. public function __construct($id = null,$db) {
  36. $this->db = $db;
  37. $this->idOrder = $id;
  38. $this->order = new OrderPagopar($id);
  39. }
  40. /**
  41. * Invoca a la URL de acuerdo a los parámetros
  42. * @param array $args Parámetros
  43. * @param string $url Url a invocar
  44. * @return string Respuesta en formato JSON
  45. */
  46. private function runCurl($args, $url){
  47. $args = json_encode($args);
  48. $ch = curl_init();
  49. $headers= array('Accept: application/json','Content-Type: application/json');
  50. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  51. curl_setopt($ch, CURLOPT_URL, $url);
  52. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  53. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  54. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  55. curl_setopt($ch, CURLOPT_POST, true);
  56. curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
  57. $response = curl_exec($ch);
  58. $error = curl_error($ch);
  59. $info = curl_getinfo($ch);
  60. curl_close($ch);
  61. return $response;
  62. }
  63. /**
  64. * Inicia la transacción con Pagopar y si tiene éxito al generar el pedido,
  65. * redirecciona a la página de pago de Pagopar.
  66. * @throws Exception
  67. */
  68. public function newPagoparTransaction(){
  69. $orderPagopar = $this->order->makeOrder($this->idOrder);
  70. $response = $this->runCurl($orderPagopar, self::URL_COMERCIOS);
  71. $arrayResponse = json_decode($response);
  72. //Verificar si hay error
  73. if(!$arrayResponse->respuesta){
  74. throw new Exception($arrayResponse->resultado);
  75. }
  76. $this->hashOrder = $arrayResponse->resultado[0]->data;
  77. $this->db->insertTransaction($orderPagopar['id_pedido_comercio'],
  78. $orderPagopar['tipo_pedido'],
  79. $orderPagopar['monto_total'],
  80. $this->hashOrder,
  81. $orderPagopar['fecha_maxima_pago'],
  82. $orderPagopar['descripcion_resumen']
  83. );
  84. $this->redirectToPagopar($this->hashOrder);
  85. }
  86. /**
  87. * Redirecciona a la página de Pagopar
  88. * @param string $hash Hash del pedido
  89. */
  90. public function redirectToPagopar($hash){
  91. $url = sprintf(self::URL_REDIRECT, $hash);
  92. //Redireccionamos a Pagopar
  93. header('Location: '. $url);
  94. exit();
  95. }
  96. /**
  97. * Inicia la transacción con Pagopar y si tiene éxito al generar el pedido con valores de prueba,
  98. * redirecciona a la página de pago de Pagopar.
  99. */
  100. public function newTestPagoparTransaction(){
  101. //Creamos el comprador
  102. $buyer = new BuyerPagopar();
  103. $buyer->name = 'Juan Perez';
  104. $buyer->email = 'mihares@gmail.com';
  105. $buyer->cityId = 1;
  106. $buyer->tel = '0972200046';
  107. $buyer->typeDoc = 'CI';
  108. $buyer->doc = '352221';
  109. $buyer->addr = 'Mexico 840';
  110. $buyer->addRef = 'alado de credicentro';
  111. $buyer->addrCoo = '-25.2844638,-57.6480038';
  112. $buyer->ruc = null;
  113. $buyer->socialReason = null;
  114. //Agregamos el comprador
  115. $this->order->addPagoparBuyer($buyer);
  116. //Creamos los productos
  117. $item1 = new ItemPagopar();
  118. $item1->name = "Válido 1 persona";
  119. $item1->qty = 1;
  120. $item1->price = 1000;
  121. $item1->cityId = 1;
  122. $item1->desc = "producto";
  123. $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";
  124. $item1->weight = '0.1';
  125. $item1->category = 3;
  126. $item1->sellerPhone = '0985885487';
  127. $item1->sellerEmail = 'mihares@gmail.com';
  128. $item1->sellerAddress = 'dr paiva ca cssssom gaa';
  129. $item1->sellerAddressRef = '';
  130. $item1->sellerAddressCoo = '-28.75438,-57.1580038';
  131. $item2 = new ItemPagopar();
  132. $item2->name = "Heladera";
  133. $item2->qty = 1;
  134. $item2->price = 785000;
  135. $item2->cityId = 1;
  136. $item2->desc = "producto";
  137. $item2->url_img = "https://cdn1.hendyla.com/archivos/imagenes/2017/04/09/publicacion-564c19b86b235526160f43483c76a69ee1a85c96c976c33e3e21ce6a5f9009b9-234_A.jpg";
  138. $item2->weight = '5.0';
  139. $item2->category = 3;
  140. $item2->sellerPhone = '0985885487';
  141. $item2->sellerEmail = 'mihares@gmail.com';
  142. $item2->sellerAddress = 'dr paiva ca cssssom gaa';
  143. $item2->sellerAddressRef = '';
  144. $item2->sellerAddressCoo = '-28.75438,-57.1580038';
  145. //Agregamos los productos al pedido
  146. $this->order->addPagoparItem($item1);
  147. $this->order->addPagoparItem($item2);
  148. $this->order->publicKey = self::TOKEN_PUBLICO;
  149. $this->order->privateKey = self::TOKEN_PRIVADO;
  150. $this->order->typeOrder = 'VENTA-COMERCIO';
  151. $this->order->desc = 'Entrada Retiro';
  152. $this->order->periodDays = 1;
  153. $this->order->periodDays = 0;
  154. $this->newPagoparTransaction();
  155. }
  156. /**
  157. * Obtiene un JSON con el estado del pedido
  158. * @param int $id Id del pedido
  159. * @throws Exception
  160. */
  161. public function getPagoparOrderStatus($id){
  162. $this->idOrder = $id;
  163. $orderData = $this->db->selectTransaction("id=$id");
  164. if($orderData){
  165. $this->hashOrder = $orderData['hash'];
  166. }else{
  167. throw new Exception("Hay un error con el hash");
  168. }
  169. $token = $this->generateToken(self::TOKEN_TIPO_CONSULTA);
  170. $args = ['hash_pedido'=>$this->hashOrder, 'token'=>$token, 'token_publico'=> self::TOKEN_PUBLICO];
  171. $arrayResponse = $this->runCurl($args, self::URL_PEDIDOS);
  172. print_r($arrayResponse);
  173. }
  174. /**
  175. * Genera un Token para el pedido
  176. * @param string $typeOfToken Tipo de token generado
  177. * @return string Token generado
  178. */
  179. private function generateToken($typeOfToken){
  180. return sha1(self::TOKEN_PRIVADO.$typeOfToken);
  181. }
  182. /**
  183. * Retorna las ciudades en forma de array
  184. * @param string $typeOfToken Tipo de token generado
  185. * @return string Token generado
  186. */
  187. public function consultarCiudades(){
  188. $token = $this->generateToken(self::TOKEN_TIPO_CIUDAD);
  189. $url = self::URL_BASE.'ciudades/1.1/traer';
  190. $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO];
  191. $arrayResponse = $this->runCurl($args, $url);
  192. return $arrayResponse;
  193. }
  194. public function consultarCategorias(){
  195. $token = $this->generateToken(self::TOKEN_TIPO_CATEGORIA);
  196. $url = self::URL_BASE.'categorias/1.1/traer';
  197. $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO];
  198. $arrayResponse = $this->runCurl($args, $url);
  199. return $arrayResponse;
  200. }
  201. #CALCULAR-FLETE
  202. public function calcularFlete($json){
  203. $token = $this->generateToken(self::TOKEN_TIPO_FLETE);
  204. $url = self::URL_BASE.'calcular-flete/1.1/traer';
  205. $args = ['token'=>$token,'token_publico'=> self::TOKEN_PUBLICO, 'dato'=> $json];
  206. $arrayResponse = $this->runCurl($args, $url);
  207. return $arrayResponse;
  208. }
  209. #registrar usuario
  210. public function registrarUsuario(array $json){
  211. $url = self::URL_BASE.'usuario/1.1/registro';
  212. $args = $json;
  213. $arrayResponse = $this->runCurl($args, $url);
  214. return $arrayResponse;
  215. }
  216. }