bb_payments 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (140) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +11 -0
  3. data/Gemfile.lock +82 -0
  4. data/README.md +391 -0
  5. data/Rakefile +8 -0
  6. data/bb_payments.gemspec +30 -0
  7. data/docs/BankSlipsApi.md +178 -0
  8. data/docs/BarcodeCollectionFormsIDResponseObject.md +6 -0
  9. data/docs/BarcodeCollectionFormsIDResponseObjectListaGuiaCodigoBarra.md +10 -0
  10. data/docs/BarcodeCollectionFormsIDResponseObjectListaOcorrencia.md +9 -0
  11. data/docs/BarcodeCollectionFormsRequestObject.md +12 -0
  12. data/docs/BarcodecollectionformsCollectionFormDetailsList.md +12 -0
  13. data/docs/BatchtransfersPaymentsList.md +22 -0
  14. data/docs/BatchtransferscancelPaymentIds.md +7 -0
  15. data/docs/Body.md +13 -0
  16. data/docs/CancelApi.md +63 -0
  17. data/docs/CollectionFormsApi.md +184 -0
  18. data/docs/Error.md +7 -0
  19. data/docs/ErrorErrors.md +8 -0
  20. data/docs/ErrorOAuthUnauthorized.md +10 -0
  21. data/docs/ErrorOAuthUnauthorizedAttributes.md +7 -0
  22. data/docs/InlineResponse200.md +13 -0
  23. data/docs/InlineResponse2001.md +29 -0
  24. data/docs/InlineResponse2001OcurrencesList.md +9 -0
  25. data/docs/InlineResponse2002.md +12 -0
  26. data/docs/InlineResponse2002PaymentsList.md +26 -0
  27. data/docs/InlineResponse2003.md +26 -0
  28. data/docs/InlineResponse2003ListaBoleto.md +24 -0
  29. data/docs/InlineResponse2003ListaDevolucao.md +9 -0
  30. data/docs/InlineResponse200PaymentsList.md +15 -0
  31. data/docs/InlineResponse201.md +13 -0
  32. data/docs/InlineResponse2011.md +13 -0
  33. data/docs/InlineResponse2011PaymentsList.md +16 -0
  34. data/docs/InlineResponse201PaymentsList.md +26 -0
  35. data/docs/InlineResponse400.md +7 -0
  36. data/docs/InlineResponse401.md +10 -0
  37. data/docs/ReturnedsApi.md +78 -0
  38. data/docs/RootTypeForBankSlipList.md +29 -0
  39. data/docs/RootTypeForBankSlipsBatchPayment.md +12 -0
  40. data/docs/RootTypeForBankSlipsBatchPaymentResponseObject.md +12 -0
  41. data/docs/RootTypeForBatchTransferGETResponseObject.md +9 -0
  42. data/docs/RootTypeForBatchTransferPaymentsListGET.md +21 -0
  43. data/docs/RootTypeForBatchTransfersCancelPaymentsListObject.md +10 -0
  44. data/docs/RootTypeForBatchTransfersCancelRequestObject.md +12 -0
  45. data/docs/RootTypeForBatchTransfersCancelResponseObject.md +7 -0
  46. data/docs/RootTypeForReturnedPaymentsDetails.md +33 -0
  47. data/docs/RootTypeForReturnedPaymentsResponseObject.md +10 -0
  48. data/docs/RootTypeForSlipsDetailsObject.md +23 -0
  49. data/docs/TransfersApi.md +309 -0
  50. data/lib/bb_payments/api/base.rb +10 -0
  51. data/lib/bb_payments/api/base_api.rb +63 -0
  52. data/lib/bb_payments/api/batch_payments_api.rb +50 -0
  53. data/lib/bb_payments/api/payments.rb +114 -0
  54. data/lib/bb_payments/api/transfers.rb +33 -0
  55. data/lib/bb_payments/api/transfers_pix.rb +52 -0
  56. data/lib/bb_payments/api_client.rb +414 -0
  57. data/lib/bb_payments/api_error.rb +57 -0
  58. data/lib/bb_payments/configuration.rb +246 -0
  59. data/lib/bb_payments/models/base_model.rb +177 -0
  60. data/lib/bb_payments/models/batch_pix_body.rb +30 -0
  61. data/lib/bb_payments/models/batch_pix_response.rb +69 -0
  62. data/lib/bb_payments/models/batch_transfers_body.rb +30 -0
  63. data/lib/bb_payments/models/batch_transfers_response.rb +64 -0
  64. data/lib/bb_payments/models/batchtransfers_payments_list.rb +362 -0
  65. data/lib/bb_payments/models/batchtransferscancel_payment_ids.rb +212 -0
  66. data/lib/bb_payments/models/body.rb +274 -0
  67. data/lib/bb_payments/models/error.rb +210 -0
  68. data/lib/bb_payments/models/error_errors.rb +227 -0
  69. data/lib/bb_payments/models/error_o_auth_unauthorized.rb +257 -0
  70. data/lib/bb_payments/models/error_o_auth_unauthorized_attributes.rb +213 -0
  71. data/lib/bb_payments/models/find_batch_payment.rb +93 -0
  72. data/lib/bb_payments/models/find_batch_response.rb +71 -0
  73. data/lib/bb_payments/models/inline_response_200.rb +270 -0
  74. data/lib/bb_payments/models/inline_response_200_1.rb +430 -0
  75. data/lib/bb_payments/models/inline_response_200_1_ocurrences_list.rb +227 -0
  76. data/lib/bb_payments/models/inline_response_200_2.rb +260 -0
  77. data/lib/bb_payments/models/inline_response_200_2_payments_list.rb +399 -0
  78. data/lib/bb_payments/models/inline_response_200_3.rb +487 -0
  79. data/lib/bb_payments/models/inline_response_200_3_lista_boleto.rb +377 -0
  80. data/lib/bb_payments/models/inline_response_200_3_lista_devolucao.rb +227 -0
  81. data/lib/bb_payments/models/inline_response_200_payments_list.rb +289 -0
  82. data/lib/bb_payments/models/inline_response_201.rb +270 -0
  83. data/lib/bb_payments/models/inline_response_201_1.rb +270 -0
  84. data/lib/bb_payments/models/inline_response_201_1_payments_list.rb +299 -0
  85. data/lib/bb_payments/models/inline_response_201_payments_list.rb +399 -0
  86. data/lib/bb_payments/models/inline_response_400.rb +210 -0
  87. data/lib/bb_payments/models/inline_response_401.rb +257 -0
  88. data/lib/bb_payments/models/root_type_for_bank_slip_list.rb +430 -0
  89. data/lib/bb_payments/models/root_type_for_bank_slips_batch_payment.rb +270 -0
  90. data/lib/bb_payments/models/root_type_for_bank_slips_batch_payment_response_object.rb +260 -0
  91. data/lib/bb_payments/models/root_type_for_batch_transfer_get_response_object.rb +230 -0
  92. data/lib/bb_payments/models/root_type_for_batch_transfer_payments_list_get.rb +348 -0
  93. data/lib/bb_payments/models/root_type_for_batch_transfers_cancel_payments_list_object.rb +238 -0
  94. data/lib/bb_payments/models/root_type_for_batch_transfers_cancel_request_object.rb +275 -0
  95. data/lib/bb_payments/models/root_type_for_batch_transfers_cancel_response_object.rb +210 -0
  96. data/lib/bb_payments/models/root_type_for_returned_payments_details.rb +468 -0
  97. data/lib/bb_payments/models/root_type_for_returned_payments_response_object.rb +240 -0
  98. data/lib/bb_payments/models/root_type_for_slips_details_object.rb +408 -0
  99. data/lib/bb_payments/models/transfer_base.rb +128 -0
  100. data/lib/bb_payments/models/transfer_pix.rb +34 -0
  101. data/lib/bb_payments/models/transfer_pix_base.rb +146 -0
  102. data/lib/bb_payments/version.rb +3 -0
  103. data/lib/bb_payments.rb +85 -0
  104. data/spec/api/batch_payments_api_spec.rb +113 -0
  105. data/spec/api_client_spec.rb +225 -0
  106. data/spec/base_object_spec.rb +109 -0
  107. data/spec/configuration_spec.rb +41 -0
  108. data/spec/models/body_spec.rb +76 -0
  109. data/spec/models/error_errors_spec.rb +46 -0
  110. data/spec/models/error_o_auth_unauthorized_attributes_spec.rb +40 -0
  111. data/spec/models/error_o_auth_unauthorized_spec.rb +58 -0
  112. data/spec/models/error_spec.rb +40 -0
  113. data/spec/models/inline_response_200_1_ocurrences_list_spec.rb +52 -0
  114. data/spec/models/inline_response_200_1_spec.rb +172 -0
  115. data/spec/models/inline_response_200_2_payments_list_spec.rb +154 -0
  116. data/spec/models/inline_response_200_2_spec.rb +70 -0
  117. data/spec/models/inline_response_200_3_lista_boleto_spec.rb +142 -0
  118. data/spec/models/inline_response_200_3_lista_devolucao_spec.rb +52 -0
  119. data/spec/models/inline_response_200_3_spec.rb +154 -0
  120. data/spec/models/inline_response_200_payments_list_spec.rb +88 -0
  121. data/spec/models/inline_response_200_spec.rb +76 -0
  122. data/spec/models/inline_response_201_1_payments_list_spec.rb +94 -0
  123. data/spec/models/inline_response_201_1_spec.rb +76 -0
  124. data/spec/models/inline_response_201_payments_list_spec.rb +154 -0
  125. data/spec/models/inline_response_201_spec.rb +76 -0
  126. data/spec/models/inline_response_400_spec.rb +40 -0
  127. data/spec/models/inline_response_401_spec.rb +58 -0
  128. data/spec/models/root_type_for_bank_slip_list_spec.rb +172 -0
  129. data/spec/models/root_type_for_bank_slips_batch_payment_response_object_spec.rb +70 -0
  130. data/spec/models/root_type_for_bank_slips_batch_payment_spec.rb +70 -0
  131. data/spec/models/root_type_for_batch_transfer_get_response_object_spec.rb +52 -0
  132. data/spec/models/root_type_for_batch_transfer_payments_list_get_spec.rb +124 -0
  133. data/spec/models/root_type_for_batch_transfers_cancel_payments_list_object_spec.rb +58 -0
  134. data/spec/models/root_type_for_batch_transfers_cancel_request_object_spec.rb +70 -0
  135. data/spec/models/root_type_for_batch_transfers_cancel_response_object_spec.rb +40 -0
  136. data/spec/models/root_type_for_returned_payments_details_spec.rb +196 -0
  137. data/spec/models/root_type_for_returned_payments_response_object_spec.rb +58 -0
  138. data/spec/models/root_type_for_slips_details_object_spec.rb +136 -0
  139. data/spec/spec_helper.rb +110 -0
  140. metadata +292 -0
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ =begin
4
+ [Pagamentos] Pagamentos que envolvem mais de um tipo de Pagamento
5
+
6
+ [Implemented] - [Endpoint] => Description
7
+ [Y] - [POST /liberar-pagamentos] => Liberar Pagamentos
8
+ [Y] - [POST /cancelar-pagamentos] => Cancelar Lote de Pagamentos
9
+ [Y] - [GET /pagamentos] => Consultar Pagamentos
10
+ [N] - [GET /transferencias/{id}] => Consultar um Pagamento Específico de um Lote de Transferências
11
+ [Y] - [GET /{id}] => Consultar um Lote de Pagamentos
12
+ [N] - [GET /{id}/solicitacao] => Consultar sobre a Solicitação de um Lote de Pagamentos
13
+
14
+ =end
15
+ module BancoBrasilPayments::Payments
16
+
17
+
18
+ # POST /liberar-pagamentos Liberar Pagamentos
19
+ # Permite que a empresa efetue a liberação dos lotes de pagamentos diretamente de seu sistema de gestão - ERP.
20
+ #
21
+ # Após o comando de liberação, o processamento do pagamento de todos os lançamentos do lote liberado dependerá da
22
+ # existência de saldo em conta até o horário limite para efetivação de cada um deles, da validação dos dados e demais
23
+ # regras pactuadas na contratação do serviço.
24
+ #
25
+ # A situação de cada lançamento deverá se consultada posteriormente.
26
+ #
27
+ # O mesmo lote poderá ser liberado mais de uma vez. Por exemplo: Foi enviado lançamentos com data de pagamento do dia
28
+ # anterior e do dia corrente. Após foi comandada a liberação do lote. Nesse caso, apenas os lançamentos com data do
29
+ # dia corrente seriam efetivados. Mas a empresa poderá alterar a data de pagamento dos lançamentos com data
30
+ # incorreta e após solicitar novamente a liberação do lote.
31
+ def liberar_pagamentos_with(id, float, opts = {})
32
+ validations(api_client: api_client, validate_body: false, required_params: { id: id, float: float })
33
+
34
+
35
+ client_opts = build_client_opts(api_client: api_client,
36
+ gw_app_key: gw_app_key,
37
+ opts: opts,
38
+ return_type: 'Hash<String, String>')
39
+ client_opts[:body][:'numeroRequisicao'] = id
40
+ client_opts[:body][:'indicadorFloat'] = float ? 'S' : 'N'
41
+
42
+ call_api_client(api_client: api_client,
43
+ http_method: :POST,
44
+ path: '/liberar-pagamentos',
45
+ data_only: opts.fetch(:data_only, true),
46
+ client_opts: client_opts)
47
+ end
48
+
49
+ # POST /cancelar-pagamentos Cancelar Lote de Pagamentos
50
+ # Efetua o Cancelamento de um Lote de Pagamentos
51
+ def cancel_payments(body, opts = {})
52
+ validations(api_client: api_client, body: body, validate_body: true)
53
+
54
+ client_opts = build_client_opts(api_client: api_client,
55
+ gw_app_key: gw_app_key,
56
+ opts: opts,
57
+ return_type: 'Hash<String, Array<Object>>',
58
+ body: @api_client.object_to_http_body(body))
59
+
60
+ call_api_client(api_client: api_client,
61
+ http_method: :POST,
62
+ path: '/cancelar-pagamentos',
63
+ data_only: opts.fetch(:data_only, true),
64
+ client_opts: client_opts)
65
+ end
66
+
67
+ # GET /pagamentos Consultar Pagamentos
68
+ # Consulta os pagamentos e transferências das requisição feitas para efetuar pagamentos em lote,
69
+ # inclusive pagamentos e transferências relacionados ao PIX. Detre as informações consulatas estão o
70
+ # motivo e valores devolvidos.
71
+ def consult_payments(start_date, end_date, opts = {})
72
+ validations(api_client: api_client, body: body, validate_body: true,
73
+ required_params: { start_date: start_date, end_date: end_date })
74
+
75
+ client_opts = build_client_opts(api_client: api_client,
76
+ gw_app_key: gw_app_key,
77
+ opts: opts)
78
+
79
+ # query parameters
80
+ query_params = client_opts[:query_params]
81
+ query_params[@api_client.config.app_key_name.to_sym] = gw_app_key
82
+ query_params[:'dataInicio'] = start_date.strftime('%d%m%Y').to_i
83
+ query_params[:'dataFim'] = end_date.strftime('%d%m%Y').to_i
84
+ query_params[:'agenciaDebito'] = opts[:'debit_branch_office'] if !opts[:'debit_branch_office'].nil?
85
+ query_params[:'contaCorrenteDebito'] = opts[:'debit_current_account'] if !opts[:'debit_current_account'].nil?
86
+ query_params[:'digitoVerificadorContaCorrente'] = opts[:'check_digits_debit_current_account'] if !opts[:'check_digits_debit_current_account'].nil?
87
+ query_params[:'numeroContratoPagamento'] = opts[:'payment_contract'] if !opts[:'payment_contract'].nil?
88
+ query_params[:'estadoPagamento'] = opts[:'payment_state'] if !opts[:'payment_state'].nil?
89
+ query_params[:'index'] = opts[:'index'] if !opts[:'index'].nil?
90
+
91
+ call_api_client(api_client: api_client,
92
+ http_method: :POST,
93
+ path: '/pagamentos',
94
+ data_only: opts.fetch(:data_only, true),
95
+ client_opts: client_opts)
96
+ end
97
+
98
+ # GET /{id}
99
+ # Consulta um lote de pagamentos.
100
+ def find_batch_payments(id, opts = {})
101
+ validations(api_client: api_client, required_params: { id: id })
102
+
103
+ client_opts = build_client_opts(api_client: api_client,
104
+ gw_app_key: gw_app_key,
105
+ opts: opts,
106
+ return_type: 'FindBatchResponse')
107
+
108
+ call_api_client(api_client: api_client,
109
+ http_method: :GET,
110
+ path: id.to_s,
111
+ data_only: opts.fetch(:data_only, true),
112
+ client_opts: client_opts)
113
+ end
114
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ =begin
4
+ [Transferências] => Pagamentos que envolvem Transferências
5
+
6
+ [Implemented] - [Endpoint] => Description
7
+ [N ]- [GET /lotes-transferencias] Consulta Lote de Pagamentos realizados via Transferências
8
+ [Y ]- [POST /lotes-transferencias] Efetua Lote de Pagamentos realizados via Transferências
9
+ [Y*]- [GET /pagamentos] Consultar Pagamentos (* See BancoBrasilPayments::Payments)
10
+ [N ]- [GET /beneficiarios/{id}/transferencias] Consultar Transferências por Beneficiário
11
+
12
+ =end
13
+ module BancoBrasilPayments::Transfers
14
+ # POST /lotes-transferencias
15
+ # Efetua Lote de Pagamentos realizados via Transferências
16
+ def create_batch_transfers(body, opts = {})
17
+ validations(api_client: api_client, body: body, validate_body: true)
18
+
19
+ client_opts = build_client_opts(api_client: api_client,
20
+ gw_app_key: gw_app_key,
21
+ opts: opts,
22
+ return_type: 'BatchTransfersResponse',
23
+ body: @api_client.object_to_http_body(body))
24
+ client_opts[:header_params]['Content-Type'] = @api_client.select_header_content_type(['application/json'])
25
+ data_only = opts.fetch :data_only, true
26
+
27
+ call_api_client(api_client: api_client,
28
+ http_method: :POST,
29
+ path: '/lotes-transferencias',
30
+ data_only: data_only,
31
+ client_opts: client_opts)
32
+ end
33
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ =begin
4
+ [Transferências-PIX] => Pagamentos que envolvem Transferências do tipo PIX
5
+
6
+ [Implemented] - [Endpoint] => Description
7
+ [Y ]- [POST /lotes-transferencias-pix] => Efetuar Pagamentos em Lote via Transferência PIX
8
+ [Y*]- [GET /pagamentos] => Consultar Pagamentos (* See BancoBrasilPayments::Payments)
9
+ [Y ]- [GET /lotes-transferencias-pix/{id}/solicitacao] => Consultar Solicitação de Transferências PIX
10
+
11
+ =end
12
+ module BancoBrasilPayments::TransfersPix
13
+ include BancoBrasilPayments::BaseApi
14
+
15
+ # POST /lotes-transferencias-pix
16
+ # Efetuar Pagamentos em Lote via Transferência PIX
17
+ def create_batch_transfers_pix(body, opts = {})
18
+ validations(api_client: api_client, body: body, validate_body: true)
19
+
20
+ client_opts = build_client_opts(api_client: api_client,
21
+ gw_app_key: gw_app_key,
22
+ opts: opts,
23
+ return_type: 'BatchPixResponse',
24
+ body: @api_client.object_to_http_body(body))
25
+ client_opts[:header_params]['Content-Type'] = @api_client.select_header_content_type(['application/json'])
26
+ data_only = opts.fetch :data_only, true
27
+
28
+ call_api_client(api_client: api_client,
29
+ http_method: :POST,
30
+ path: '/lotes-transferencias-pix',
31
+ data_only: data_only,
32
+ client_opts: client_opts)
33
+ end
34
+
35
+ # GET /lotes-transferencias-pix/{id}/solicitacao
36
+ # # Consultar Solicitação de Transferências PIX
37
+ def find_batch_transfer_pix(id, opts = {})
38
+ validations(api_client: api_client, body: body, validate_body: true, required_params: { id: id })
39
+
40
+ client_opts = build_client_opts(api_client: api_client,
41
+ gw_app_key: gw_app_key,
42
+ opts: opts,
43
+ body: @api_client.object_to_http_body(body))
44
+ client_opts[:query_params][:'index'] = opts[:'index'] if !opts[:'index'].nil?
45
+
46
+ call_api_client(api_client: api_client,
47
+ http_method: :POST,
48
+ path: "/lotes-transferencias-pix/#{id}/solicitacao",
49
+ data_only: opts.fetch(:data_only, true),
50
+ client_opts: client_opts)
51
+ end
52
+ end
@@ -0,0 +1,414 @@
1
+ =begin
2
+ #Payments-VPN
3
+
4
+ #Esta API fornece os serviços de pagamento do Banco do Brasil.
5
+
6
+ OpenAPI spec version: 3.5
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+ Swagger Codegen version: 3.0.24
10
+ =end
11
+
12
+ require 'date'
13
+ require 'json'
14
+ require 'logger'
15
+ require 'tempfile'
16
+ require 'typhoeus'
17
+ require 'uri'
18
+
19
+ module BancoBrasilPayments
20
+ class ApiClient
21
+ TOKEN_EXPIRE_TIME = 570
22
+
23
+ # The Configuration object holding settings to be used in the API client.
24
+ attr_accessor :config
25
+
26
+ # Defines the headers to be used in HTTP requests of all API calls by default.
27
+ #
28
+ # @return [Hash]
29
+ attr_accessor :default_headers
30
+
31
+ # Defines the last time a token was requested
32
+ attr_accessor :access_token_requested_at
33
+
34
+ # Initializes the ApiClient
35
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
36
+ def initialize(config = Configuration.default)
37
+ @config = config
38
+ @user_agent = "Swagger-Codegen/#{VERSION}/ruby"
39
+ @default_headers = {
40
+ 'Content-Type' => 'application/json',
41
+ 'User-Agent' => @user_agent
42
+ }
43
+ @access_token_requested_at = nil
44
+ end
45
+
46
+ def self.default
47
+ @@default ||= ApiClient.new
48
+ end
49
+
50
+ # Call an API with given options.
51
+ #
52
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
53
+ # the data deserialized from response body (could be nil), response status code and response headers.
54
+ def call_api(http_method, path, opts = {})
55
+ request = build_request(http_method, path, opts)
56
+ response = request.run
57
+
58
+ if @config.debugging
59
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body.force_encoding('utf-8')}\n~END~\n"
60
+ end
61
+
62
+ unless response.success?
63
+ if response.timed_out?
64
+ fail ApiError.new('Connection timed out')
65
+ elsif response.code == 0
66
+ # Errors from libcurl will be made visible here
67
+ fail ApiError.new(:code => 0,
68
+ :message => response.return_message.force_encoding('utf-8'))
69
+ else
70
+ fail ApiError.new(:code => response.code,
71
+ :response_headers => response.headers,
72
+ :response_body => response.body.force_encoding('utf-8')),
73
+ response.status_message
74
+ end
75
+ end
76
+
77
+ if opts[:return_type]
78
+ data = deserialize(response, opts[:return_type])
79
+ else
80
+ data = nil
81
+ end
82
+ return data, response.code, response.headers
83
+ end
84
+
85
+ # Builds the HTTP request
86
+ #
87
+ # @param [String] http_method HTTP method/verb (e.g. POST)
88
+ # @param [String] path URL path (e.g. /account/new)
89
+ # @option opts [Hash] :header_params Header parameters
90
+ # @option opts [Hash] :query_params Query parameters
91
+ # @option opts [Hash] :form_params Query parameters
92
+ # @option opts [Object] :body HTTP body (JSON/XML)
93
+ # @return [Typhoeus::Request] A Typhoeus Request
94
+ def build_request(http_method, path, opts = {})
95
+ base_path = opts[:base_path]
96
+ url = build_request_url(path, base_path)
97
+ http_method = http_method.to_sym.downcase
98
+
99
+ header_params = @default_headers.merge(opts[:header_params] || {})
100
+ query_params = opts[:query_params] || {}
101
+ form_params = opts[:form_params] || {}
102
+
103
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
104
+
105
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
106
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
107
+
108
+ req_opts = {
109
+ :method => http_method,
110
+ :headers => header_params,
111
+ :params => query_params,
112
+ :params_encoding => @config.params_encoding,
113
+ :timeout => @config.timeout,
114
+ :ssl_verifypeer => @config.verify_ssl,
115
+ :ssl_verifyhost => _verify_ssl_host,
116
+ :sslcert => @config.cert_file,
117
+ :sslkey => @config.key_file,
118
+ :sslkeypasswd => @config.ssl_key_passwd,
119
+ :verbose => @config.debugging,
120
+ :accept_encoding => "gzip"
121
+ }
122
+
123
+ # set custom cert, if provided
124
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
125
+
126
+ if [:post, :patch, :put, :delete].include?(http_method)
127
+ req_body = build_request_body(header_params, form_params, opts[:body])
128
+ req_opts.update :body => req_body
129
+ if @config.debugging
130
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body.force_encoding('utf-8')}\n~END~\n"
131
+ end
132
+ end
133
+
134
+ request = Typhoeus::Request.new(url, req_opts)
135
+ download_file(request) if opts[:return_type] == 'File'
136
+ request
137
+ end
138
+
139
+ # Builds the HTTP request body
140
+ #
141
+ # @param [Hash] header_params Header parameters
142
+ # @param [Hash] form_params Query parameters
143
+ # @param [Object] body HTTP body (JSON/XML)
144
+ # @return [String] HTTP body data in the form of string
145
+ def build_request_body(header_params, form_params, body)
146
+ # http form
147
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
148
+ header_params['Content-Type'] == 'multipart/form-data'
149
+ data = {}
150
+ form_params.each do |key, value|
151
+ case value
152
+ when ::File, ::Array, nil
153
+ # let typhoeus handle File, Array and nil parameters
154
+ data[key] = value
155
+ else
156
+ data[key] = value.to_s
157
+ end
158
+ end
159
+ elsif body
160
+ data = body.is_a?(String) ? body : body.to_json
161
+ else
162
+ data = nil
163
+ end
164
+ data
165
+ end
166
+
167
+ # Check if the given MIME is a JSON MIME.
168
+ # JSON MIME examples:
169
+ # application/json
170
+ # application/json; charset=UTF8
171
+ # APPLICATION/JSON
172
+ # */*
173
+ # @param [String] mime MIME
174
+ # @return [Boolean] True if the MIME is application/json
175
+ def json_mime?(mime)
176
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
177
+ end
178
+
179
+ # Deserialize the response to the given return type.
180
+ #
181
+ # @param [Response] response HTTP response
182
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
183
+ def deserialize(response, return_type)
184
+ body = response.body
185
+
186
+ # handle file downloading - return the File instance processed in request callbacks
187
+ # note that response body is empty when the file is written in chunks in request on_body callback
188
+ return @tempfile if return_type == 'File'
189
+
190
+ return nil if body.nil? || body.empty?
191
+
192
+ # return response body directly for String return type
193
+ return body if return_type == 'String'
194
+
195
+ # ensuring a default content type
196
+ content_type = response.headers['Content-Type'] || 'application/json'
197
+
198
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
199
+
200
+ begin
201
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
202
+ rescue JSON::ParserError => e
203
+ if %w(String Date DateTime).include?(return_type)
204
+ data = body
205
+ else
206
+ raise e
207
+ end
208
+ end
209
+
210
+ convert_to_type data, return_type
211
+ end
212
+
213
+ # Convert data to the given return type.
214
+ # @param [Object] data Data to be converted
215
+ # @param [String] return_type Return type
216
+ # @return [Mixed] Data in a particular type
217
+ def convert_to_type(data, return_type)
218
+ return nil if data.nil?
219
+ case return_type
220
+ when 'String'
221
+ data.to_s
222
+ when 'Integer'
223
+ data.to_i
224
+ when 'Float'
225
+ data.to_f
226
+ when 'Boolean'
227
+ data == true
228
+ when 'DateTime'
229
+ # parse date time (expecting ISO 8601 format)
230
+ DateTime.parse data
231
+ when 'Date'
232
+ # parse date time (expecting ISO 8601 format)
233
+ Date.parse data
234
+ when 'Object'
235
+ # generic object (usually a Hash), return directly
236
+ data
237
+ when /\AArray<(.+)>\z/
238
+ # e.g. Array<Pet>
239
+ sub_type = $1
240
+ data.map { |item| convert_to_type(item, sub_type) }
241
+ when /\AHash\<String, (.+)\>\z/
242
+ # e.g. Hash<String, Integer>
243
+ sub_type = $1
244
+ {}.tap do |hash|
245
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
246
+ end
247
+ else
248
+ # models, e.g. Pet
249
+ # TODO make it more generic (in case we use the same base with different apis)
250
+ BancoBrasilPayments.const_get(return_type).build_from_hash(data)
251
+ end
252
+ end
253
+
254
+ # Save response body into a file in (the defined) temporary folder, using the filename
255
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
256
+ # The response body is written to the file in chunks in order to handle files which
257
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
258
+ # process can use.
259
+ #
260
+ # @see Configuration#temp_folder_path
261
+ def download_file(request)
262
+ tempfile = nil
263
+ encoding = nil
264
+ request.on_headers do |response|
265
+ content_disposition = response.headers['Content-Disposition']
266
+ if content_disposition && content_disposition =~ /filename=/i
267
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
268
+ prefix = sanitize_filename(filename)
269
+ else
270
+ prefix = 'download-'
271
+ end
272
+ prefix = prefix + '-' unless prefix.end_with?('-')
273
+ encoding = response.body.encoding
274
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
275
+ @tempfile = tempfile
276
+ end
277
+ request.on_body do |chunk|
278
+ chunk.force_encoding(encoding)
279
+ tempfile.write(chunk)
280
+ end
281
+ request.on_complete do |response|
282
+ if tempfile
283
+ tempfile.close
284
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
285
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
286
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
287
+ "explicitly with `tempfile.delete`"
288
+ end
289
+ end
290
+ end
291
+
292
+ # Sanitize filename by removing path.
293
+ # e.g. ../../sun.gif becomes sun.gif
294
+ #
295
+ # @param [String] filename the filename to be sanitized
296
+ # @return [String] the sanitized filename
297
+ def sanitize_filename(filename)
298
+ filename.gsub(/.*[\/\\]/, '')
299
+ end
300
+
301
+ def build_request_url(path, base_path = nil)
302
+ # Add leading and trailing slashes to path
303
+ path = "/#{path}".gsub(/\/+/, '/')
304
+ @config.base_url(base_path || @config.base_path) + path
305
+ end
306
+
307
+ def valid_token?
308
+ access_token_requested_at &&
309
+ (Time.zone.now - access_token_requested_at) > TOKEN_EXPIRE_TIME
310
+ end
311
+
312
+ def renew_token
313
+ api_instance = BancoBrasilClientCredentials::DefaultApi.new @config.client_credentials_api
314
+ result = api_instance.oauth_token_post('client_credentials',
315
+ @config.access_token_scopes, @config.basic_auth_token,
316
+ 'application/x-www-form-urlencoded')
317
+ self.access_token_requested_at = Time.zone.now
318
+ @config.access_token = result.access_token
319
+ result.access_token
320
+ end
321
+
322
+ # Update hearder and query params based on authentication settings.
323
+ #
324
+ # @param [Hash] header_params Header parameters
325
+ # @param [Hash] query_params Query parameters
326
+ # @param [String] auth_names Authentication scheme name
327
+ def update_params_for_auth!(header_params, query_params, auth_names)
328
+ renew_token unless valid_token?
329
+ Array(auth_names).each do |auth_name|
330
+ auth_setting = @config.auth_settings[auth_name]
331
+ next unless auth_setting
332
+ case auth_setting[:in]
333
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
334
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
335
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
336
+ end
337
+ end
338
+ end
339
+
340
+ # Sets user agent in HTTP header
341
+ #
342
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
343
+ def user_agent=(user_agent)
344
+ @user_agent = user_agent
345
+ @default_headers['User-Agent'] = @user_agent
346
+ end
347
+
348
+ # Return Accept header based on an array of accepts provided.
349
+ # @param [Array] accepts array for Accept
350
+ # @return [String] the Accept header (e.g. application/json)
351
+ def select_header_accept(accepts)
352
+ return nil if accepts.nil? || accepts.empty?
353
+ # use JSON when present, otherwise use all of the provided
354
+ json_accept = accepts.find { |s| json_mime?(s) }
355
+ json_accept || accepts.join(',')
356
+ end
357
+
358
+ # Return Content-Type header based on an array of content types provided.
359
+ # @param [Array] content_types array for Content-Type
360
+ # @return [String] the Content-Type header (e.g. application/json)
361
+ def select_header_content_type(content_types)
362
+ # use application/json by default
363
+ return 'application/json' if content_types.nil? || content_types.empty?
364
+ # use JSON when present, otherwise use the first one
365
+ json_content_type = content_types.find { |s| json_mime?(s) }
366
+ json_content_type || content_types.first
367
+ end
368
+
369
+ # Convert object (array, hash, object, etc) to JSON string.
370
+ # @param [Object] model object to be converted into JSON string
371
+ # @return [String] JSON string representation of the object
372
+ def object_to_http_body(model)
373
+ return model if model.nil? || model.is_a?(String)
374
+ local_body = nil
375
+ if model.is_a?(Array)
376
+ local_body = model.map { |m| object_to_hash(m) }
377
+ else
378
+ local_body = object_to_hash(model)
379
+ end
380
+ local_body.to_json
381
+ end
382
+
383
+ # Convert object(non-array) to hash.
384
+ # @param [Object] obj object to be converted into JSON string
385
+ # @return [String] JSON string representation of the object
386
+ def object_to_hash(obj)
387
+ if obj.respond_to?(:to_hash)
388
+ obj.to_hash
389
+ else
390
+ obj
391
+ end
392
+ end
393
+
394
+ # Build parameter value according to the given collection format.
395
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
396
+ def build_collection_param(param, collection_format)
397
+ case collection_format
398
+ when :csv
399
+ param.join(',')
400
+ when :ssv
401
+ param.join(' ')
402
+ when :tsv
403
+ param.join("\t")
404
+ when :pipes
405
+ param.join('|')
406
+ when :multi
407
+ # return the array directly as typhoeus will handle it as expected
408
+ param
409
+ else
410
+ fail "unknown collection format: #{collection_format.inspect}"
411
+ end
412
+ end
413
+ end
414
+ end
@@ -0,0 +1,57 @@
1
+ =begin
2
+ #Payments-VPN
3
+
4
+ #Esta API fornece os serviços de pagamento do Banco do Brasil.
5
+
6
+ OpenAPI spec version: 3.5
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+ Swagger Codegen version: 3.0.24
10
+ =end
11
+
12
+ module BancoBrasilPayments
13
+ class ApiError < StandardError
14
+ attr_reader :code, :response_headers, :response_body
15
+
16
+ # Usage examples:
17
+ # ApiError.new
18
+ # ApiError.new("message")
19
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
20
+ # ApiError.new(:code => 404, :message => "Not Found")
21
+ def initialize(arg = nil)
22
+ if arg.is_a? Hash
23
+ if arg.key?(:message) || arg.key?('message')
24
+ super(arg[:message] || arg['message'])
25
+ else
26
+ super arg
27
+ end
28
+
29
+ arg.each do |k, v|
30
+ instance_variable_set "@#{k}", v
31
+ end
32
+ else
33
+ super arg
34
+ end
35
+ end
36
+
37
+ # Override to_s to display a friendly error message
38
+ def to_s
39
+ message
40
+ end
41
+
42
+ def message
43
+ if @message.nil?
44
+ msg = "Error message: the server returns an error"
45
+ else
46
+ msg = @message
47
+ end
48
+
49
+ msg += "\nHTTP status code: #{code}" if code
50
+ msg += "\nResponse headers: #{response_headers}" if response_headers
51
+ msg += "\nResponse body: #{response_body}" if response_body
52
+
53
+ msg
54
+ end
55
+
56
+ end
57
+ end