easy_pay_u_latam 0.1.15 → 0.1.16

Sign up to get free protection for your applications and to get access to all the features.
Files changed (38) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +15 -0
  3. data/app/assets/javascripts/easy_pay_u_latam/application.js +2 -0
  4. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/angular-card.js +222 -0
  5. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/application.js +8 -0
  6. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/card.js +2533 -0
  7. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/controllers/Main.js +158 -0
  8. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/controllers/Subscriptions.js +368 -0
  9. data/app/assets/javascripts/easy_pay_u_latam/subscriptions/country-picker.min.js +1 -0
  10. data/app/assets/stylesheets/easy_pay_u_latam/styles.css +4 -0
  11. data/app/assets/stylesheets/easy_pay_u_latam/subscriptions/application.scss +1 -0
  12. data/app/assets/stylesheets/easy_pay_u_latam/subscriptions/card.css +1 -0
  13. data/app/controllers/easy_pay_u_latam/api/v1/pay_u_cards_controller.rb +80 -0
  14. data/app/controllers/easy_pay_u_latam/api/v1/pay_u_clients_controller.rb +18 -0
  15. data/app/controllers/easy_pay_u_latam/api/v1/pay_u_subscriptions_controller.rb +56 -0
  16. data/app/views/easy_pay_u_latam/pay_u_payments/_dashboard.html.erb +15 -0
  17. data/app/views/easy_pay_u_latam/pay_u_payments/cards/_form.html.erb +81 -0
  18. data/app/views/easy_pay_u_latam/pay_u_payments/cards/_list.html.erb +54 -0
  19. data/app/views/easy_pay_u_latam/pay_u_payments/plans/_list.html.erb +30 -0
  20. data/app/views/easy_pay_u_latam/pay_u_payments/subscriptions/_actual.html.erb +54 -0
  21. data/app/views/easy_pay_u_latam/pay_u_payments/{index.html.erb → subscriptions/_form.html.erb} +0 -0
  22. data/app/views/easy_pay_u_latam/pay_u_payments/subscriptions/_list.html.erb +49 -0
  23. data/app/views/easy_pay_u_latam/pay_u_payments/subscriptions/_none.html.erb +0 -0
  24. data/app/views/easy_pay_u_latam/pay_u_payments/subscriptions/_show.html.erb +0 -0
  25. data/config/routes.rb +5 -0
  26. data/lib/easy_pay_u_latam.rb +6 -0
  27. data/lib/easy_pay_u_latam/r_api.rb +47 -0
  28. data/lib/easy_pay_u_latam/r_api/card.rb +102 -0
  29. data/lib/easy_pay_u_latam/r_api/client.rb +28 -0
  30. data/lib/easy_pay_u_latam/r_api/invoice.rb +53 -0
  31. data/lib/easy_pay_u_latam/r_api/invoice_service.rb +48 -0
  32. data/lib/easy_pay_u_latam/r_api/plan.rb +71 -0
  33. data/lib/easy_pay_u_latam/r_api/request.rb +133 -0
  34. data/lib/easy_pay_u_latam/r_api/subscription.rb +41 -0
  35. data/lib/easy_pay_u_latam/r_api/subscription_interceptor.rb +51 -0
  36. data/lib/easy_pay_u_latam/r_api/subscription_service.rb +208 -0
  37. data/lib/easy_pay_u_latam/version.rb +1 -1
  38. metadata +83 -30
data/config/routes.rb CHANGED
@@ -9,6 +9,11 @@ EasyPayULatam::Engine.routes.draw do
9
9
  get "get_status"
10
10
  end
11
11
  end
12
+
13
+ resources :pay_u_cards, only: [:index, :create, :update, :destroy]
14
+ resources :pay_u_clients, only: [:create]
15
+ resources :pay_u_plans, only: [:index]
16
+ resources :pay_u_subscriptions, only: [:index, :show, :create, :update, :destroy]
12
17
  end
13
18
  end
14
19
 
@@ -1,5 +1,11 @@
1
1
  require "easy_pay_u_latam/engine"
2
2
  require "easy_pay_u_latam/Configuration"
3
+ require "easy_pay_u_latam/r_api"
4
+ require "easy_pay_u_latam/r_api/request"
5
+ require "easy_pay_u_latam/r_api/plan"
6
+ require "easy_pay_u_latam/r_api/card"
7
+ require "easy_pay_u_latam/r_api/client"
8
+ require "easy_pay_u_latam/r_api/subscription"
3
9
 
4
10
  module EasyPayULatam
5
11
  class << self
@@ -0,0 +1,47 @@
1
+ module EasyPayULatam
2
+ module RApi
3
+ class << self
4
+ require "base64"
5
+ # NOTA: definir si dejar estos campos como accessors
6
+ attr_accessor :api_login, :api_key, :account_id, :sandbox
7
+ attr_reader :base_url
8
+
9
+ # recibe un bloque inicializador de variables de configuración de payu como la
10
+ # api_key, api_login
11
+ def configure(&block)
12
+ block.call(self)
13
+ end
14
+
15
+ # retorna la url de api de payu dependiendo del ambiente, development o production
16
+ def base_url
17
+ if RApi.sandbox == true
18
+ @base_url = 'https://sandbox.api.payulatam.com/payments-api'
19
+ else
20
+ @base_url = 'https://api.payulatam.com/payments-api'
21
+ end
22
+ end
23
+
24
+ # genera el codigo de autenticación que será enviado en los header de todas las peticiones a la api
25
+ def authorization
26
+ @authorization ||= "Basic " + Base64.strict_encode64("#{api_login}:#{api_key}").to_s
27
+ end
28
+ end
29
+ end
30
+
31
+ # #development
32
+ # RApi.configure do |config|
33
+ # config.api_login = 'pRRXKOl8ikMmt9u'
34
+ # config.api_key = '4Vj8eK4rloUd272L48hsrarnUA'
35
+ # config.account_id = '512321'
36
+ # config.sandbox = true
37
+ # end
38
+
39
+ # production
40
+ # RApi.configure do |config|
41
+ # config.api_login = 'BtHXV5p7b1a74Za'
42
+ # config.api_key = 'ZNl7g0L2H54Y9ZVn51keXS2l07'
43
+ # config.account_id = '762507'
44
+ # config.sandbox = false
45
+ # end
46
+
47
+ end
@@ -0,0 +1,102 @@
1
+ module EasyPayULatam
2
+ module RApi
3
+ class Card < Request
4
+ attr_reader :url, :customer_url, :customer
5
+ attr_accessor :resource, :params
6
+
7
+ # creación de instancia de la clase
8
+ # recibe un customer(cliente en payu) para asociar una tarjeta de crédito
9
+ # customer = PayuLatam::Client.new
10
+ def initialize(customer={})
11
+ @params = empty_object # inicializa los params de card con datos de prueba
12
+ @customer = customer.response if !customer.nil?
13
+ customer_url # llenar la @url con la de la api de cards
14
+ return if @customer.nil?
15
+ load("") # si llega id buscarlo
16
+ end
17
+
18
+ def customer
19
+ @customer ||= { id: nil }
20
+ end
21
+
22
+ # llena la variable local y super con la url de este recurso
23
+ def url
24
+ @url ||= RApi.base_url + "/rest/v4.9/creditCards/"
25
+ end
26
+
27
+ # el recurso de tarjeta necesita en algunos casos alterar la URL para incluir información
28
+ # del customer, por eso se crea este metodo con la url necesario
29
+ def customer_url
30
+ @url = RApi.base_url + "/rest/v4.9/customers/#{@customer['id']}/creditCards/"
31
+ end
32
+
33
+ # se sobreescribe el metodo crear de request
34
+ # el metodo crear necesita en la url información del customer por eso se llena la @url con la url
35
+ # necesaria luego que continue con su flujo llamando super
36
+ def create!
37
+ customer_url
38
+ super
39
+ end
40
+
41
+ # se sobreescribe el metodo load de request
42
+ # obtener detalle de una tarjeta, para esto reestablecemos la url simple
43
+ # continuar con el flujo normal llamando super
44
+ def load(id)
45
+ customer_url
46
+ super
47
+ end
48
+
49
+ # se sobreescribe el metodo delete de request
50
+ # eliminar tarjeta, para esto, para esto usar la url con la info del customer
51
+ # continuar con el flujo normal llamando super
52
+ def delete(token)
53
+ customer_url
54
+ super
55
+ end
56
+
57
+ # se sobreescribe el metodo update de request
58
+ # recibe los parametros a editar y el id objetivo a editar
59
+ def update(params={})
60
+ reset_url
61
+ @http_verb = 'Put'
62
+ @url += id.to_s
63
+ @params = params if !params.empty?
64
+ http
65
+ @response
66
+ end
67
+
68
+ # override from request
69
+ def id
70
+ raise ArgumentError, 'Card is nil' if @resource.nil?
71
+ @resource['token'] if @resource
72
+ end
73
+
74
+ private
75
+
76
+ # restablece url a su estado base
77
+ def reset_url
78
+ @url = RApi.base_url + "/rest/v4.9/creditCards/"
79
+ end
80
+
81
+ # ejemplo de parametro
82
+ def empty_object
83
+ {
84
+ "name": "Sample User Name",
85
+ "document": "1020304050",
86
+ "number": "4242424242424242",
87
+ "expMonth": "01",
88
+ "expYear": "2020",
89
+ "type": "VISA",
90
+ "address": {
91
+ "line1": "Address Name",
92
+ "postalCode": "00000",
93
+ "city": "City Name",
94
+ "state": "State Name",
95
+ "country": "CO",
96
+ "phone": "300300300"
97
+ }
98
+ }
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,28 @@
1
+ module EasyPayULatam
2
+ module RApi
3
+ class Client < Request
4
+ attr_reader :url, :cards
5
+ attr_accessor :resource, :params, :exists
6
+
7
+ # puede recibir el id de un cliente, para obtener el detalle en la inicializacion de la clase
8
+ def initialize(id=nil)
9
+ url
10
+ @params = empty_object
11
+ @cards = []
12
+ return if id.nil?
13
+ load(id)
14
+ end
15
+
16
+ # url base
17
+ def url
18
+ @url = RApi.base_url + '/rest/v4.9/customers/'
19
+ end
20
+
21
+ private
22
+
23
+ def empty_object
24
+ { 'fullName'=> '', 'email'=> '' }
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,53 @@
1
+ module PayuLatam
2
+ class Invoice < Request
3
+ attr_reader :url, :data
4
+ attr_accessor :resource, :params
5
+
6
+ # in order to take the correct url
7
+ def initialize(data = {})
8
+ @data = data
9
+ @params = @data
10
+ url
11
+ _id
12
+ load(@id)
13
+ end
14
+
15
+ def _id
16
+ @id = @data[:customerId] if !@data[:customerId].nil?
17
+ @id = @data[:subscriptionId] if !@data[:subscriptionId].nil?
18
+ end
19
+
20
+ def load(id)
21
+ raise ArgumentError, 'params are nil' if @data.nil?
22
+ customer_url if !@data[:customerId].nil?
23
+ subscription_url if !@data[:subscriptionId].nil?
24
+
25
+ if !@data[:customerId].nil? && !@data[:start_date].nil? && !@data[:end_date].nil?
26
+ @dateBegin = @data[:start_date]
27
+ @dateFinal = @data[:end_date]
28
+ range_url
29
+ end
30
+
31
+ return if @id.nil?
32
+
33
+ super
34
+ end
35
+
36
+ def url
37
+ @url = PayuLatam.base_url + '/rest/v4.9/recurringBill'
38
+ end
39
+
40
+ def customer_url
41
+ @url = url + '?customerId='
42
+ end
43
+
44
+ def subscription_url
45
+ @url = url + '?subscriptionId='
46
+ end
47
+
48
+ # año día mes
49
+ def range_url
50
+ @url = url "?customerId=#{@id}&dateBegin=#{@dateBegin}&dateFinal=#{@dateFinal}"
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,48 @@
1
+ module PayuLatam
2
+ class InvoiceService < Request
3
+ attr_accessor :start_date, :end_date
4
+ attr_reader :current_user, :invoices
5
+
6
+ def initialize(current_user)
7
+ @current_user = current_user
8
+ end
9
+
10
+ def current
11
+ if @invoices.nil?
12
+ @start_date.nil? && @end_date.nil? ? historical : range_dates
13
+ end
14
+ @invoices['recurringBillList'].last
15
+ end
16
+
17
+ private
18
+
19
+ def historical
20
+ @invoices = PayuLatam::Invoice.new(customerId: @current_user.payu_customer_id).resource
21
+ end
22
+
23
+ def range_dates
24
+ raise ArgumentError, 'dates are nil' if @start_date.nil? && @end_date.nil?
25
+
26
+ @invoices = PayuLatam::Invoice.new(customerId: @current_user.payu_customer_id,
27
+ start_date: @start_date, end_date: @end_date).resource
28
+ end
29
+ end
30
+ end
31
+ =begin
32
+ # Ejemplo de respuesta
33
+ # <PayuLatam::Invoice:0x007fe1e41b54b8
34
+ @data={:customerId=>"3a097xfyjj8y", :start_date=>"2018-16-10", :end_date=>"2018-16-11"},
35
+ @dateBegin="2018-16-10",
36
+ @dateFinal="2018-16-11",
37
+ @error=nil,
38
+ @http_verb="Get",
39
+ @id="3a097xfyjj8y",
40
+ @params={:customerId=>"3a097xfyjj8y", :start_date=>"2018-16-10", :end_date=>"2018-16-11"},
41
+ @resource=
42
+ {"recurringBillList"=>
43
+ [{"id"=>"841c254e-8c6e-45d5-93f1-0fe33fb2bf55", "orderId"=>7341246, "subscriptionId"=>"4627edvl1je2", "state"=>"PAID", "amount"=>49, "currency"=>"MXN", "dateCharge"=>1461992400000},
44
+ {"id"=>"a473e716-7839-4b4d-b20a-583797c737e0", "orderId"=>7344250, "subscriptionId"=>"0906e8zysve", "state"=>"PAID", "amount"=>10000, "currency"=>"COP", "dateCharge"=>1462424400000},
45
+ ]
46
+ }
47
+
48
+ =end
@@ -0,0 +1,71 @@
1
+ module EasyPayULatam
2
+ module RApi
3
+ class Plan < Request
4
+ attr_reader :url
5
+ attr_accessor :resource, :params
6
+
7
+ # in order to take the correct url
8
+ def initialize(id=nil)
9
+ url
10
+ @params = empty_object
11
+ return if id.nil?
12
+ load(id)
13
+ end
14
+
15
+ def update(params={})
16
+ @http_verb = 'Put'
17
+ @url += id.to_s
18
+
19
+ @params = params if !params.empty?
20
+ http
21
+ @resource = @response if @response
22
+ end
23
+
24
+ # override from request
25
+ def id
26
+ raise ArgumentError, 'plan is nil' if @resource.nil?
27
+ @resource['planCode'] if @resource
28
+ end
29
+
30
+ def url
31
+ @url = RApi.base_url + '/rest/v4.9/plans/'
32
+ end
33
+
34
+ private
35
+
36
+ def empty_object
37
+ {
38
+ "accountId": RApi.account_id,
39
+ "planCode": "Utopicko-plan01",
40
+ "description": "Suscripción Utopicko",
41
+ "interval": "MONTH",#MONTH
42
+ "intervalCount": "1",
43
+ "maxPaymentsAllowed": "12",
44
+ "paymentAttemptsDelay": "1",
45
+ "trialDays": "0",
46
+ "additionalValues": [
47
+ {
48
+ "name": "PLAN_VALUE",
49
+ "value": "20000",
50
+ "currency": "COP"
51
+ }
52
+ ]
53
+ }
54
+ end
55
+ end
56
+ end
57
+ end
58
+
59
+ # {"id"=>"f7bad364-29f9-4cc2-b0c1-c92e271803a1",
60
+ # "planCode"=>"Utopicko-plan01",
61
+ # "description"=>"Suscripci&oacute;n Utopicko",
62
+ # "accountId"=>"512321",
63
+ # "intervalCount"=>1,
64
+ # "interval"=>"MONTH",
65
+ # "maxPaymentsAllowed"=>12,
66
+ # "maxPaymentAttempts"=>0,
67
+ # "paymentAttemptsDelay"=>1,
68
+ # "maxPendingPayments"=>0,
69
+ #
70
+ # "trialDays"=>0,
71
+ # "additionalValues"=>[{"name"=>"PLAN_VALUE", "value"=>20000, "currency"=>"COP"}]}
@@ -0,0 +1,133 @@
1
+
2
+ module EasyPayULatam
3
+ module RApi
4
+ class Request
5
+
6
+ require 'uri'
7
+ require 'net/https'
8
+ require 'json'
9
+
10
+ # lectura y escritura
11
+ attr_accessor :url, :_url, :params
12
+ # solo lectura
13
+ attr_reader :response, :http_verb, :error
14
+
15
+ #
16
+ # VARIABLES:
17
+ #
18
+ # @url -> su valor es asignado por cada clase hija que use algún método de la clase request
19
+ # @_url -> url auxiliar, por ahora no tiene un uso
20
+ # @params -> objeto con los parametros que serán enviados en el body de la petición
21
+ # @response -> objeto con la respuesta json obtenida de la api de PAYU
22
+ # @http_verb -> indica el verbo http a usar en la petición, GET, PUT, DELETE...
23
+ # @error -> objeto con la respuesta json del ERROR devuelto por payu
24
+ #
25
+
26
+ # POST Creación de registro
27
+ # 'create' es un metodo POST en la api de PAYU para todos sus modulos. Card, Client, Plan, ...
28
+ # ejecuta la petición y en caso de existir respuesta la guarda en la variable response
29
+ def create!
30
+ @http_verb = 'Post'
31
+ http
32
+ @response
33
+ end
34
+
35
+ # PUT Edición de registro
36
+ # 'update' es un metodo PUT en la api de PAYU para todos sus modulos. Card, Client, Plan, ...
37
+ # ejecuta la petición y en caso de existir respuesta la guarda en la variable response
38
+ #
39
+ # recibe como parametros los valores a enviar en el cuerpo de la petición, es decir los campos
40
+ # del recurso que se desea editar con su respectivo valor
41
+ def update(params={})
42
+ @http_verb = 'Put'
43
+ @url += id.to_s
44
+
45
+ @params = params if !params.empty? # si llegan parametros se enviaran y editaran esos params
46
+ @params.merge!({id: id}) if id
47
+
48
+ http
49
+ @response
50
+ end
51
+
52
+ # GET Detalle del registro
53
+ # necesita el id del recurso en payu para obtener info
54
+ def load(id)
55
+ @http_verb = 'Get'
56
+ @url += id.to_s
57
+ http
58
+ @response
59
+ end
60
+
61
+ # DELETE Eliminar recurso
62
+ # necesita el id del recurso en payu
63
+ def delete(id)
64
+ @http_verb = 'Delete'
65
+ @url += id.to_s
66
+ http
67
+ @response
68
+ end
69
+
70
+ # indica si la última petición realizada fué exitosa
71
+ def success?
72
+ @error.nil? && !@response.nil?
73
+ end
74
+
75
+ # indica si la última petición fallida
76
+ def fail?
77
+ !@error.nil?
78
+ end
79
+
80
+ # retorna el id del último recurso trabajado
81
+ def id
82
+ raise ArgumentError, 'customer is nil' if @resource.nil?
83
+ @resource['id'] if @resource
84
+ end
85
+
86
+ private
87
+
88
+ def url
89
+ @url ||= _url
90
+ end
91
+
92
+ # reestablece la url en caso de ser necesario
93
+ def reset_url
94
+ @url = url
95
+ end
96
+
97
+ # ejecución de la petición
98
+ def http
99
+ puts "#{http_verb} #{@url}"
100
+ uri = URI.parse(@url)
101
+ https = Net::HTTP.new(uri.host,uri.port)
102
+
103
+ https.use_ssl = true
104
+ https.verify_mode = OpenSSL::SSL::VERIFY_NONE
105
+
106
+ net_class = Object.const_get("Net::HTTP::#{http_verb}")
107
+ request = net_class.new(uri.path, initheader = {'Content-Type' =>'application/json'})
108
+
109
+ request['Accept'] = 'application/json'
110
+ request['Accept-language'] = 'es'
111
+ request['Authorization'] = RApi.authorization
112
+
113
+ request.body = @params.to_json
114
+ request = https.request(request)
115
+
116
+ reset_url
117
+
118
+ # llena @response ó @error
119
+ if request.is_a?(Net::HTTPSuccess)
120
+ begin
121
+ @response = JSON.parse(request.body)
122
+ rescue
123
+ @response = request.body
124
+ end
125
+ @error = nil
126
+ else
127
+ @response = nil
128
+ @error = JSON.parse(request.body)
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end