onlinepayments-sdk-ruby 11.0.0 → 11.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/AGENTS.md +23 -0
- data/README.md +22 -0
- data/lib/onlinepayments/sdk/communication/metadata_provider.rb +1 -1
- data/lib/onlinepayments/sdk/factory.rb +6 -0
- data/lib/onlinepayments/sdk/merchant/merchant_client.rb +4 -0
- data/onlinepayments-sdk-ruby.gemspec +2 -2
- data/skills/worldline-direct/SKILL.md +85 -0
- data/skills/worldline-direct/examples/after_payment_operations_example.rb +75 -0
- data/skills/worldline-direct/examples/app_types.rb +170 -0
- data/skills/worldline-direct/examples/client_integration_example.rb +76 -0
- data/skills/worldline-direct/examples/client_setup.rb +60 -0
- data/skills/worldline-direct/examples/create_payment_response_handler.rb +32 -0
- data/skills/worldline-direct/examples/customer_device.rb +32 -0
- data/skills/worldline-direct/examples/error_handling_example.rb +99 -0
- data/skills/worldline-direct/examples/hosted_checkout_example.rb +181 -0
- data/skills/worldline-direct/examples/hosted_fields_example.rb +82 -0
- data/skills/worldline-direct/examples/hosted_tokenization_example.rb +79 -0
- data/skills/worldline-direct/examples/payment_attempt.rb +30 -0
- data/skills/worldline-direct/examples/payment_links_example.rb +52 -0
- data/skills/worldline-direct/examples/payment_status_example.rb +62 -0
- data/skills/worldline-direct/examples/recurring_payments_example.rb +127 -0
- data/skills/worldline-direct/examples/server_to_server_example.rb +81 -0
- data/skills/worldline-direct/examples/webhook_event_processor.rb +40 -0
- data/skills/worldline-direct/examples/webhooks_endpoint.rb +73 -0
- data/skills/worldline-direct/examples/webhooks_setup.rb +41 -0
- data/skills/worldline-direct/references/errors.md +113 -0
- data/skills/worldline-direct/references/flows.md +966 -0
- data/skills/worldline-direct/references/ruby.md +208 -0
- data/skills/worldline-direct/references/webhooks.md +167 -0
- metadata +25 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# Ruby SDK reference
|
|
2
|
+
|
|
3
|
+
How to install and set up the Ruby SDK (`onlinepayments-sdk-ruby`), and the SDK calls for the API operations used in
|
|
4
|
+
this skill.
|
|
5
|
+
Source code and README: https://github.com/wl-online-payments-direct/sdk-ruby
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
gem install onlinepayments-sdk-ruby
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or add `gem 'onlinepayments-sdk-ruby'` to your `Gemfile` and run `bundle install`. The SDK uses `httpclient` for HTTP
|
|
14
|
+
and `concurrent-ruby`. `require 'onlinepayments/sdk'` loads the whole SDK. The classes have YARD comments with the
|
|
15
|
+
types of every property, parameter and return value; there are no RBS or Sorbet signatures.
|
|
16
|
+
|
|
17
|
+
## Namespaces
|
|
18
|
+
|
|
19
|
+
Use the full names; the examples do too.
|
|
20
|
+
|
|
21
|
+
| Namespace | Contains |
|
|
22
|
+
|---|---|
|
|
23
|
+
| `OnlinePayments::SDK` | `Factory`, `CommunicatorConfiguration`, `Client`, `CallContext`, the API exceptions (`ApiException`, `DeclinedPaymentException`, ...) |
|
|
24
|
+
| `OnlinePayments::SDK::Merchant` | `MerchantClient` and the sub-clients, e.g. `Payments::PaymentsClient` |
|
|
25
|
+
| `OnlinePayments::SDK::Domain` | Every request and response class, e.g. `CreatePaymentRequest`, `Order`, `AmountOfMoney` |
|
|
26
|
+
| `OnlinePayments::SDK::Authentication` | `AuthorizationType::V1HMAC` |
|
|
27
|
+
| `OnlinePayments::SDK::Communication` | `CommunicationException`, `RequestHeader` |
|
|
28
|
+
| `OnlinePayments::SDK::Webhooks` | `WebhooksHelper`, `WebhooksEvent`, `InMemorySecretKeyStore`, `SecretKeyStore`, `SignatureValidationException`, `SecretKeyNotAvailableException`, `ApiVersionMismatchException` |
|
|
29
|
+
| `OnlinePayments::SDK::JSON` | `DefaultMarshaller` |
|
|
30
|
+
| `OnlinePayments::SDK::Logging` | `RubyCommunicatorLogger`, `StdoutCommunicatorLogger`; `Obfuscation::BodyObfuscator` and the rules `Obfuscation.obfuscate_all`, ... |
|
|
31
|
+
|
|
32
|
+
## Client setup
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
# Create the client once when the application starts, reuse it for every request and close it on shutdown.
|
|
36
|
+
# Every value is validated here, so a wrong configuration stops the application at startup.
|
|
37
|
+
# @return [OnlinePayments::SDK::Client]
|
|
38
|
+
def self.create_client
|
|
39
|
+
configuration = OnlinePayments::SDK::CommunicatorConfiguration.new(
|
|
40
|
+
# Test or live host, e.g. payment.direct.ecom.preprod.worldline-solutions.com (without a path).
|
|
41
|
+
api_endpoint: "https://#{required_env('onlinePayments_api_endpoint_host')}",
|
|
42
|
+
api_key_id: required_env('onlinePayments_api_v1hmac_apiKeyId'),
|
|
43
|
+
secret_api_key: required_env('onlinePayments_api_v1hmac_secretApiKey'),
|
|
44
|
+
# Required: without it, creating the client raises RuntimeError "Unknown authorizationType".
|
|
45
|
+
authorization_type: OnlinePayments::SDK::Authentication::AuthorizationType::V1HMAC,
|
|
46
|
+
# Your company or application name; it identifies your requests in the platform logs.
|
|
47
|
+
# Required: without it, the SDK raises ArgumentError "integrator is required".
|
|
48
|
+
integrator: required_env('onlinePayments_api_integrator'),
|
|
49
|
+
# In seconds.
|
|
50
|
+
connect_timeout: 5,
|
|
51
|
+
socket_timeout: 300,
|
|
52
|
+
max_connections: 10
|
|
53
|
+
)
|
|
54
|
+
OnlinePayments::SDK::Factory.create_client_from_configuration(configuration)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# The merchant ID is your PSPID. All API calls start from the merchant client.
|
|
58
|
+
# @param client [OnlinePayments::SDK::Client]
|
|
59
|
+
# @return [OnlinePayments::SDK::Merchant::MerchantClient]
|
|
60
|
+
def self.create_merchant_client(client)
|
|
61
|
+
client.merchant(required_env('onlinePayments_api_merchantId'))
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# The absolute public base URL of your shop, e.g. https://shop.example. The return URL of a checkout is built from
|
|
65
|
+
# it, never from the Host header of a request, which the sender controls.
|
|
66
|
+
# @return [String] without a trailing slash
|
|
67
|
+
def self.public_base_url
|
|
68
|
+
value = required_env('shop_publicBaseUrl')
|
|
69
|
+
uri = URI.parse(value)
|
|
70
|
+
unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty? && uri.query.nil? && uri.fragment.nil?
|
|
71
|
+
raise "shop_publicBaseUrl must be an absolute http(s) URL without query or fragment, e.g. https://shop.example"
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
value.strip.chomp('/')
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Read credentials from the environment or, better, a secret store of your platform, and never hard-code them.
|
|
78
|
+
# For local development keep them in your own environment or a local secret store, not in a file in the repository.
|
|
79
|
+
# A blank value counts as missing.
|
|
80
|
+
# @param name [String]
|
|
81
|
+
# @return [String]
|
|
82
|
+
def self.required_env(name)
|
|
83
|
+
value = ENV[name]
|
|
84
|
+
raise "Environment variable #{name} is not set" if value.nil? || value.strip.empty?
|
|
85
|
+
|
|
86
|
+
value
|
|
87
|
+
end
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `CommunicatorConfiguration.new` takes keyword arguments only. Set `authorization_type:` to
|
|
91
|
+
`OnlinePayments::SDK::Authentication::AuthorizationType::V1HMAC` (the string `'v1HMAC'`): without it, creating the
|
|
92
|
+
client raises `RuntimeError: Unknown authorizationType`. The `integrator` is mandatory: a `nil` or blank value
|
|
93
|
+
raises `ArgumentError: integrator is required` when the client is created. Timeouts are in seconds. `max_connections` (connection pool size) defaults
|
|
94
|
+
to 10.
|
|
95
|
+
- `api_endpoint` is the scheme and host only (`https://payment.direct.ecom.preprod.worldline-solutions.com`); a path
|
|
96
|
+
raises `RuntimeError: api_endpoint should not contain a path`.
|
|
97
|
+
- `Factory.create_client_from_file(yaml_file, api_key_id, secret_api_key)` reads the other settings from a YAML file
|
|
98
|
+
with the keys `onlinePayments.api.endpoint.host`, `onlinePayments.api.authorizationType`,
|
|
99
|
+
`onlinePayments.api.integrator`, `onlinePayments.api.connectTimeout`, `onlinePayments.api.socketTimeout`, ... The
|
|
100
|
+
merchant ID is not part of the client configuration.
|
|
101
|
+
- The client holds a connection pool and is thread-safe. Create it once per process (an initializer in Rails, a
|
|
102
|
+
constant or `set` in Sinatra) and call `client.close` on shutdown, e.g. in `at_exit`. With a block,
|
|
103
|
+
`Factory.create_client_from_configuration(configuration) { |client| ... }` closes it at the end of the block.
|
|
104
|
+
`client.merchant(merchant_id)` is cheap.
|
|
105
|
+
|
|
106
|
+
## Conventions
|
|
107
|
+
|
|
108
|
+
- Calls are synchronous and return the response object. They raise exceptions (see below).
|
|
109
|
+
- Request and response classes take no constructor arguments. Create the object with `new` and set its attributes:
|
|
110
|
+
`amount = OnlinePayments::SDK::Domain::AmountOfMoney.new` then `amount.amount = 1000`,
|
|
111
|
+
`amount.currency_code = 'EUR'`. Each attribute also has a `with_<name>(value)` method that returns the object. The
|
|
112
|
+
names are the API names in snake_case (`order.amountOfMoney` is `order.amount_of_money`). Exceptions: `RETURNMAC`
|
|
113
|
+
is `returnmac`, `subsequentcardPaymentMethodSpecificInput` is `subsequentcard_payment_method_specific_input`.
|
|
114
|
+
- A misspelled attribute raises `NoMethodError` when the line runs; an unknown keyword argument raises
|
|
115
|
+
`ArgumentError`. Nothing checks this before you run the code, so copy the names from the examples or the SDK source.
|
|
116
|
+
- All attributes can be `nil` in responses: use `&.` and compare flags with `== true`.
|
|
117
|
+
- Date and time attributes (e.g. `expiration_date`) take a `DateTime`, e.g. `(Time.now + 3600).to_datetime`.
|
|
118
|
+
- `to_h` returns a `Hash` with the API property names, e.g. to send a response object to your page as JSON
|
|
119
|
+
(`response.to_h.to_json`); `from_hash(hash)` fills an object from such a hash.
|
|
120
|
+
- Every call has an optional `context` argument. Set the idempotence key with `CallContext.new(key)`, for example
|
|
121
|
+
with `SecureRandom.uuid`. The key is a positional argument: `CallContext.new(idempotence_key: key)` stores a `Hash`
|
|
122
|
+
as the key. After the call, `context.idempotence_request_timestamp` is set if the platform returned the result of an
|
|
123
|
+
earlier request with the same key. A `CallContext` is not thread-safe: create one per request. `create_hosted_checkout` and `create_payment_link`
|
|
124
|
+
ignore an idempotence key, so the examples call them without a context.
|
|
125
|
+
- Attributes marked `@deprecated` in their YARD comment are deprecated in the API. Use the replacement named there.
|
|
126
|
+
|
|
127
|
+
## API operations used in this skill
|
|
128
|
+
|
|
129
|
+
All calls start from the merchant client: `merchant = client.merchant(merchant_id)`.
|
|
130
|
+
|
|
131
|
+
| API operation | SDK call | Used in |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| CreateHostedCheckout | `merchant.hosted_checkout.create_hosted_checkout(CreateHostedCheckoutRequest)` | Hosted Checkout, recurring payments |
|
|
134
|
+
| GetHostedCheckout | `merchant.hosted_checkout.get_hosted_checkout(hosted_checkout_id)` | Hosted Checkout |
|
|
135
|
+
| CreateHostedTokenization | `merchant.hosted_tokenization.create_hosted_tokenization(CreateHostedTokenizationRequest)` | Hosted Tokenization |
|
|
136
|
+
| CreateHostedFieldsSession | `merchant.hosted_fields.create_hosted_fields_session(CreateHostedFieldsSessionRequest)` | Hosted Fields |
|
|
137
|
+
| CreateSession | `merchant.sessions.create_session(SessionRequest)` | Client integration |
|
|
138
|
+
| CreatePayment | `merchant.payments.create_payment(CreatePaymentRequest, context)` | Server-to-server, Hosted Tokenization, Hosted Fields, client integration |
|
|
139
|
+
| GetPaymentDetails | `merchant.payments.get_payment_details(payment_id)` | Payment status, webhooks, error handling |
|
|
140
|
+
| CapturePayment | `merchant.payments.capture_payment(payment_id, CapturePaymentRequest, context)` | After-payment operations |
|
|
141
|
+
| RefundPayment | `merchant.payments.refund_payment(payment_id, RefundRequest, context)` | After-payment operations |
|
|
142
|
+
| CancelPayment | `merchant.payments.cancel_payment(payment_id, CancelPaymentRequest, context)` | After-payment operations |
|
|
143
|
+
| SubsequentPayment | `merchant.subsequent.subsequent_payment(payment_id, SubsequentPaymentRequest, context)` | Recurring payments |
|
|
144
|
+
| CreatePaymentLink | `merchant.payment_links.create_payment_link(CreatePaymentLinkRequest)` | Payment Links |
|
|
145
|
+
| GetPaymentLinkById | `merchant.payment_links.get_payment_link_by_id(payment_link_id)` | Payment Links |
|
|
146
|
+
|
|
147
|
+
For anything else, use the API reference; the SDK's sub-clients and method names are the operation names there in
|
|
148
|
+
snake_case.
|
|
149
|
+
|
|
150
|
+
## Exceptions
|
|
151
|
+
|
|
152
|
+
All are in `OnlinePayments::SDK` unless noted. Rescue the specific ones before `ApiException`.
|
|
153
|
+
|
|
154
|
+
| Exception | When |
|
|
155
|
+
|---|---|
|
|
156
|
+
| `DeclinedPaymentException` | The error response carries a payment result: a declined payment (seen with 402 and 403), also for `subsequent_payment`. The body decides, not the status. `payment_result` holds the created payment (`.payment.id`). |
|
|
157
|
+
| `DeclinedRefundException` | The error response carries a refund result (the body decides, not the status). `refund_result` holds it. |
|
|
158
|
+
| `IdempotenceException` | 409 on a call with an idempotence key, with a single error with error code `30001002`: a request with the same idempotence key is still running. Has `idempotence_key`. |
|
|
159
|
+
| `ValidationException` | 400: invalid request, including an operation that the payment's state does not allow (error `id` `ACTION_NOT_ALLOWED_ON_TRANSACTION`). |
|
|
160
|
+
| `AuthorizationException` | 403: wrong API key ID, secret or merchant ID (error `id` `ACCESS_TO_MERCHANT_NOT_ALLOWED`), or an action that is not allowed. |
|
|
161
|
+
| `ReferenceException` | 404 (object not found), 410, and a 409 that is not the idempotence case above. |
|
|
162
|
+
| `PlatformException` | 500, 502, 503. Retry only if an error has `retriable` true; for calls with an idempotence key, use a new key. |
|
|
163
|
+
| `ApiException` | Base class of all the above; any other error status, including 401 and 402 without a payment result. An error response with an empty body is a plain `ApiException` whatever its status. Other `ApiException` subclasses, `ProblemDetailsException` and `DeclinedPayoutException`, are raised by operations this skill does not use. Has `status_code`, `error_id`, `errors`, `response_body`. |
|
|
164
|
+
| `Communication::CommunicationException` | No valid response: timeout, connection error, or an error response with a non-empty body that is not JSON (a 404 like that raises a `NotFoundException`). Not an `ApiException`; the original error is in `cause`. |
|
|
165
|
+
| `Webhooks::SignatureValidationException` | Webhook signature check failed. `Webhooks::SecretKeyNotAvailableException` (unknown key ID) is a subclass. |
|
|
166
|
+
| `Webhooks::ApiVersionMismatchException` | Valid signature, but the event has another API version. Not a `SignatureValidationException`. |
|
|
167
|
+
| `JSON::MarshallerSyntaxException` | Valid signature, but the body is not valid JSON. An API call raises it too when the response has a JSON content type but invalid JSON. Not a `SignatureValidationException`. |
|
|
168
|
+
|
|
169
|
+
`errors` is an array (empty if the platform sent none) of `Domain::APIError` with `error_code`, `property_name`,
|
|
170
|
+
`message`, `http_status_code` and `retriable`.
|
|
171
|
+
|
|
172
|
+
`ApiException#to_s` appends the status and the whole response body to the message:
|
|
173
|
+
`the payment platform returned an error response; status_code=400; response_body='{...}'`. `e.message`,
|
|
174
|
+
`"#{e}"`, `e.inspect` and the default output of an uncaught exception all use it, so logging `e`, `e.message` or
|
|
175
|
+
`e.to_s` writes the response body. For an error that carries a payment (a declined payment) log
|
|
176
|
+
only `e.error_id`, `e.status_code` and the `error_code` values; never `e`, `e.message`, `e.to_s` or `e.response_body`.
|
|
177
|
+
For Hosted Checkout calls the error body is a plain error response, so logging `e` is acceptable.
|
|
178
|
+
|
|
179
|
+
On the `GetHostedCheckout` response, `created_payment_output` (`Domain::CreatedPaymentOutput`) holds `payment` and
|
|
180
|
+
`payment_status_category` (a String, may be `nil`); decide on `payment.status_output`, not on this value.
|
|
181
|
+
|
|
182
|
+
## Webhooks
|
|
183
|
+
|
|
184
|
+
`WebhooksHelper.new(OnlinePayments::SDK::JSON::DefaultMarshaller.instance, secret_key_store)` and
|
|
185
|
+
`helper.unmarshal(body, request_headers)`, where `body` is the raw body string and `request_headers` is an array of
|
|
186
|
+
`Communication::RequestHeader.new(name, value)`. The SDK needs the `X-GCS-Signature` and `X-GCS-KeyId` headers (names
|
|
187
|
+
are compared case-insensitively); Rack gives them as
|
|
188
|
+
`request.env['HTTP_X_GCS_SIGNATURE']` and `request.env['HTTP_X_GCS_KEYID']`. The helper takes only this array, no
|
|
189
|
+
hash. If one of the two names occurs more than once in the array, it raises `SignatureValidationException`
|
|
190
|
+
(`encountered multiple occurrences of header`), as it does when one is absent: build one `RequestHeader` per received
|
|
191
|
+
value and never merge repeated headers. A header whose value is `nil` raises `TypeError` or `NoMethodError` instead:
|
|
192
|
+
answer 401 before calling `unmarshal` when a value is `nil` or empty. `secret_key_store` is
|
|
193
|
+
`InMemorySecretKeyStore.instance` after `store_secret_key(key_id, secret)`, or your own object that includes
|
|
194
|
+
`SecretKeyStore` and implements `get_secret_key(key_id)`. `unmarshal` raises `SignatureValidationException`
|
|
195
|
+
(`SecretKeyNotAvailableException` for an unknown key ID) when verification fails. After a valid signature it can
|
|
196
|
+
raise `ApiVersionMismatchException` (the SDK reads API version `v1` only) or `JSON::MarshallerSyntaxException`;
|
|
197
|
+
rescue both separately from the signature exception. It returns a `Webhooks::WebhooksEvent` with `id`, `type`,
|
|
198
|
+
`created`, `merchant_id` and one of `payment`, `refund`, `payment_link`, `payout`, `token`. Read the body with
|
|
199
|
+
`request.body.read` in Sinatra or `request.raw_post` in Rails, not as parsed params, and skip the Rails CSRF check
|
|
200
|
+
for the webhook action. See `webhooks.md` for the full handler.
|
|
201
|
+
|
|
202
|
+
## Logging
|
|
203
|
+
|
|
204
|
+
`client.enable_logging(OnlinePayments::SDK::Logging::RubyCommunicatorLogger.new(Logger.new($stdout), Logger::INFO))` or
|
|
205
|
+
`OnlinePayments::SDK::Logging::StdoutCommunicatorLogger.instance` logs requests and responses with card data and
|
|
206
|
+
secrets masked. Mask other fields with
|
|
207
|
+
`client.set_body_obfuscator(OnlinePayments::SDK::Logging::Obfuscation::BodyObfuscator.new({ 'name' => OnlinePayments::SDK::Logging::Obfuscation.obfuscate_all }))`.
|
|
208
|
+
Do not log request or response objects yourself.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# Webhooks
|
|
2
|
+
|
|
3
|
+
The platform sends an HTTP POST to your endpoint when a payment, refund, payment link, payout or token changes.
|
|
4
|
+
Webhooks are how you learn the result when the customer never returns to your site, and how you learn about changes
|
|
5
|
+
made later (captures, refunds, chargebacks).
|
|
6
|
+
|
|
7
|
+
## Set up
|
|
8
|
+
|
|
9
|
+
1. In the Merchant Portal, go to Developer > Webhooks. Generate the webhook key ID and secret, and enter your
|
|
10
|
+
endpoint URL (HTTPS). The secret is displayed for 60 seconds only: store it at once. Generating a new pair
|
|
11
|
+
revokes the existing one immediately.
|
|
12
|
+
2. Store the key ID and secret like the API secret: configuration or a secret store, never in code.
|
|
13
|
+
3. You can also send up to five endpoint URLs with each request in `feedbacks.webhooksUrls`;
|
|
14
|
+
`feedbacks.webhookUrl` is deprecated.
|
|
15
|
+
4. Let the platform reach your endpoint: whitelist its IP range in your firewall (see the Firewall documentation on
|
|
16
|
+
the documentation portal).
|
|
17
|
+
5. Create the SDK's webhooks helper once at startup with a secret key store that holds the key ID and secret.
|
|
18
|
+
6. Check the setup with the `ValidateWebhookCredentials` operation (your key and secret) and the `SendTestWebhook`
|
|
19
|
+
operation (a test event, type `payment.test`; your endpoint must answer 2xx).
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
# Create the helper once. The key ID and secret come from the Merchant Portal (Developer > Webhooks).
|
|
23
|
+
# Keep them like the API secret: in a secret store of your platform or, locally, in your own environment, never in
|
|
24
|
+
# a file in the repository. A blank value stops the application at startup.
|
|
25
|
+
# In production you can pass your own object that includes OnlinePayments::SDK::Webhooks::SecretKeyStore and
|
|
26
|
+
# implements get_secret_key(key_id) on top of your secret storage.
|
|
27
|
+
# @return [OnlinePayments::SDK::Webhooks::WebhooksHelper]
|
|
28
|
+
def self.create_webhooks_helper
|
|
29
|
+
secret_key_store = OnlinePayments::SDK::Webhooks::InMemorySecretKeyStore.instance
|
|
30
|
+
secret_key_store.store_secret_key(ClientSetup.required_env('onlinePayments_webhooks_keyId'),
|
|
31
|
+
ClientSetup.required_env('onlinePayments_webhooks_secret'))
|
|
32
|
+
OnlinePayments::SDK::Webhooks::WebhooksHelper.new(OnlinePayments::SDK::JSON::DefaultMarshaller.instance,
|
|
33
|
+
secret_key_store)
|
|
34
|
+
end
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Receive
|
|
38
|
+
|
|
39
|
+
Mandatory rule 4: verify every webhook with the SDK's webhooks helper before processing the event.
|
|
40
|
+
|
|
41
|
+
1. Read the raw request body as bytes or an unchanged string. The signature is calculated over the exact body; a
|
|
42
|
+
body that was parsed and serialised again fails verification.
|
|
43
|
+
2. Pass the body and all request headers to the helper. It checks the `X-GCS-Signature` and `X-GCS-KeyId` headers
|
|
44
|
+
and returns the parsed event. A repeated `X-GCS-Signature` or `X-GCS-KeyId` must fail verification, so never pass
|
|
45
|
+
only the first value of a header. How to pass a repeated header depends on the helper: see `ruby.md`.
|
|
46
|
+
3. If verification fails, answer with an error status and do not process the event. Do not add a way to skip
|
|
47
|
+
verification, such as a configuration flag or a check for the development environment. For local testing, use a
|
|
48
|
+
test webhook key ID and secret from the Merchant Portal, or send a test event with SendTestWebhook; both go
|
|
49
|
+
through normal verification.
|
|
50
|
+
4. Save the verified event before you answer: a database row or a persistent queue, ignoring duplicates (the
|
|
51
|
+
webhooks guide identifies a duplicate by identical `payment.id` and `type`). Then answer with HTTP 2xx right away,
|
|
52
|
+
as the guide recommends, and do the work in the background. Do nothing else before the answer.
|
|
53
|
+
5. If the event passed verification but the SDK cannot read it (API version mismatch, malformed body), the sender
|
|
54
|
+
is the platform, so do not answer with an error status. Save the raw body, log it with an alert, and answer 2xx.
|
|
55
|
+
A retry would send the same body and fail the same way; the saved body can be replayed after you upgrade the
|
|
56
|
+
SDK. Only a failed verification gets an error status.
|
|
57
|
+
|
|
58
|
+
When the platform gets no 2xx answer in time, it sends the event again: after 10 minutes, 1 hour, 2 hours, 8 hours
|
|
59
|
+
and 24 hours. Each delivery has a `retry-count` header: 0 for the first attempt, higher for a retry. Log it; it
|
|
60
|
+
tells a new event from a retry. A 2xx tells the platform the event arrived, so do not count on another delivery after
|
|
61
|
+
you answered 2xx. An event that is only in memory when the process dies can be lost, and retrying failed background
|
|
62
|
+
work does not make the platform send it again. Keep your own retry for saved events that failed. The guide also
|
|
63
|
+
recommends a back-up mechanism, so run a reconciliation job: for every order that stays pending longer than a
|
|
64
|
+
customer normally needs to pay, read the status with `GetPaymentDetails` (see "Payment status" in `flows.md`) and
|
|
65
|
+
update the order.
|
|
66
|
+
|
|
67
|
+
```ruby
|
|
68
|
+
# Call this from your HTTP endpoint with the raw body and the two signature headers, e.g. in Sinatra:
|
|
69
|
+
# post '/webhooks' do
|
|
70
|
+
# status endpoint.receive(request.body.read, request.env['HTTP_X_GCS_SIGNATURE'], request.env['HTTP_X_GCS_KEYID'])
|
|
71
|
+
# end
|
|
72
|
+
# In Rails use request.raw_post, request.headers['X-GCS-Signature'] and request.headers['X-GCS-KeyId'], and skip
|
|
73
|
+
# the CSRF check for this action. Pass the body unchanged: parsing it as JSON first breaks the signature check.
|
|
74
|
+
# The web layer has already collapsed repeated headers into one value here. If your framework exposes repeated
|
|
75
|
+
# headers, pass each received value as its own RequestHeader and never merge them: the helper rejects a duplicate
|
|
76
|
+
# X-GCS-Signature or X-GCS-KeyId, and a merged value would hide it.
|
|
77
|
+
# Returns the HTTP status to answer with.
|
|
78
|
+
# @param body [String]
|
|
79
|
+
# @param signature [String, nil]
|
|
80
|
+
# @param key_id [String, nil]
|
|
81
|
+
# @return [Integer]
|
|
82
|
+
def receive(body, signature, key_id)
|
|
83
|
+
# A nil header value makes the SDK raise TypeError or NoMethodError instead of SignatureValidationException:
|
|
84
|
+
# reject it first.
|
|
85
|
+
return 401 if signature.nil? || signature.empty? || key_id.nil? || key_id.empty?
|
|
86
|
+
|
|
87
|
+
request_headers = [
|
|
88
|
+
OnlinePayments::SDK::Communication::RequestHeader.new('X-GCS-Signature', signature),
|
|
89
|
+
OnlinePayments::SDK::Communication::RequestHeader.new('X-GCS-KeyId', key_id)
|
|
90
|
+
]
|
|
91
|
+
begin
|
|
92
|
+
# Checks the signature before parsing the event.
|
|
93
|
+
webhooks_event = webhooks_helper.unmarshal(body, request_headers)
|
|
94
|
+
rescue OnlinePayments::SDK::Webhooks::SignatureValidationException
|
|
95
|
+
# Wrong or missing signature, or an unknown key ID (SecretKeyNotAvailableException is a subclass).
|
|
96
|
+
# Not sent by the platform, or the wrong secret is configured. Do nothing with it.
|
|
97
|
+
return 401
|
|
98
|
+
rescue OnlinePayments::SDK::Webhooks::ApiVersionMismatchException,
|
|
99
|
+
OnlinePayments::SDK::JSON::MarshallerSyntaxException => e
|
|
100
|
+
# The signature is valid, so the platform sent it, but this SDK cannot read it. Neither class is a subclass
|
|
101
|
+
# of SignatureValidationException. Do not answer with an error: a retry sends the same body and fails the same
|
|
102
|
+
# way. Keep the raw body to replay it after you upgrade the SDK, and raise an alert.
|
|
103
|
+
inbox.save_unreadable_body(body, e.class.name.to_s)
|
|
104
|
+
logger.error("ALERT: verified webhook that the SDK cannot read (#{e.class}), raw body saved")
|
|
105
|
+
return 200
|
|
106
|
+
end
|
|
107
|
+
# Save the verified event before you answer. Do not count on the platform sending the event again after a 2xx,
|
|
108
|
+
# so an event that only lives in memory when the process dies can be lost. The inbox ignores duplicates.
|
|
109
|
+
inbox.save_event(webhooks_event)
|
|
110
|
+
# A background job processes the saved events. Slow or failed answers are retried by the platform.
|
|
111
|
+
200
|
|
112
|
+
end
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Process
|
|
116
|
+
|
|
117
|
+
- **Duplicates are normal.** The same event can arrive more than once. Processing must be idempotent.
|
|
118
|
+
- **Order is not guaranteed.** A `payment.created` event can arrive after `payment.captured`.
|
|
119
|
+
- **Read the current status.** Treat the event as a signal: call `GetPaymentDetails` and update the order from its
|
|
120
|
+
`statusOutput` (see "Payment status" in `flows.md`). This also makes duplicates and old events harmless. The
|
|
121
|
+
`payment.id` of a payment changes when a maintenance operation (capture, refund, ...) is performed, and a hosted
|
|
122
|
+
checkout session numbers its authorization attempts (`<id>_0`, `<id>_1`, ...). The platform strongly recommends not
|
|
123
|
+
building your business operations around the ID. `GetPaymentDetails` with the ID of an earlier authorization
|
|
124
|
+
attempt returns the payment's current state, with all operations in `operations` and the latest one as `id`, so
|
|
125
|
+
reading the status by ID gives the current state even for an event about an older operation. Status changes made
|
|
126
|
+
by the platform send webhooks too, without changing the `payment.id`.
|
|
127
|
+
- **Do not log the event or the request body.** The event's `payment` contains card details and customer data (see
|
|
128
|
+
the logging rules in `errors.md`). Log the event `id`, `type` and the payment ID.
|
|
129
|
+
- **Find your order** with `payment.paymentOutput.references.merchantReference`, which holds the order reference you
|
|
130
|
+
sent. The payment ID changes when you perform a maintenance operation such as a capture or refund, so do not use it as
|
|
131
|
+
your only key.
|
|
132
|
+
- **Do not use webhooks for decisions during checkout.** While the customer waits, use `GetHostedCheckout` or
|
|
133
|
+
`GetPaymentDetails`.
|
|
134
|
+
|
|
135
|
+
```ruby
|
|
136
|
+
# Runs in the background. Events can arrive twice and out of order, so read the current
|
|
137
|
+
# status instead of trusting the event; repeating this is harmless.
|
|
138
|
+
# @param webhooks_event [OnlinePayments::SDK::Webhooks::WebhooksEvent]
|
|
139
|
+
# @return [void]
|
|
140
|
+
def process(webhooks_event)
|
|
141
|
+
payment = webhooks_event.payment
|
|
142
|
+
payment_id = payment&.id
|
|
143
|
+
# Refund, payment link, payout and token events carry other objects, e.g. webhooks_event.refund.
|
|
144
|
+
return if payment.nil? || payment_id.nil?
|
|
145
|
+
|
|
146
|
+
order_id = payment.payment_output&.references&.merchant_reference
|
|
147
|
+
return if order_id.nil? || order_id.empty?
|
|
148
|
+
|
|
149
|
+
details = merchant.payments.get_payment_details(payment_id)
|
|
150
|
+
orders.save_payment_id(order_id, details.id || payment_id)
|
|
151
|
+
orders.save_state(order_id, PaymentStatusExample.to_order_state(details.status, details.status_output))
|
|
152
|
+
end
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Event types
|
|
156
|
+
|
|
157
|
+
| Object | Types |
|
|
158
|
+
|---|---|
|
|
159
|
+
| Payment | `payment.created`, `payment.redirected`, `payment.authorization_requested`, `payment.pending_approval`, `payment.pending_completion`, `payment.pending_capture`, `payment.capture_requested`, `payment.captured`, `payment.rejected`, `payment.rejected_capture`, `payment.cancelled`, `payment.refunded` |
|
|
160
|
+
| Refund | `refund.refund_requested` |
|
|
161
|
+
| Payment link | `paymentlink.created`, `paymentlink.clicked`, `paymentlink.paid`, `paymentlink.cancelled`, `paymentlink.expired`, `paymentlink.payment.rejected`, `paymentlink.payment.cancelled` |
|
|
162
|
+
| Test | `payment.test` (sent by the SendTestWebhook operation) |
|
|
163
|
+
|
|
164
|
+
The event's `type` field holds the type. The object that changed is in the matching field of the event (`payment`,
|
|
165
|
+
`refund`, `paymentLink`, `payout`, `token`).
|
|
166
|
+
|
|
167
|
+
Webhooks guide: https://docs.direct.worldline-solutions.com/en/integration/api-developer-guide/webhooks
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: onlinepayments-sdk-ruby
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 11.
|
|
4
|
+
version: 11.1.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Worldline Direct support team
|
|
@@ -143,6 +143,7 @@ executables: []
|
|
|
143
143
|
extensions: []
|
|
144
144
|
extra_rdoc_files: []
|
|
145
145
|
files:
|
|
146
|
+
- AGENTS.md
|
|
146
147
|
- Gemfile
|
|
147
148
|
- LICENSE.txt
|
|
148
149
|
- README.md
|
|
@@ -650,6 +651,29 @@ files:
|
|
|
650
651
|
- lib/onlinepayments/sdk/webhooks/webhooks_event.rb
|
|
651
652
|
- lib/onlinepayments/sdk/webhooks/webhooks_helper.rb
|
|
652
653
|
- onlinepayments-sdk-ruby.gemspec
|
|
654
|
+
- skills/worldline-direct/SKILL.md
|
|
655
|
+
- skills/worldline-direct/examples/after_payment_operations_example.rb
|
|
656
|
+
- skills/worldline-direct/examples/app_types.rb
|
|
657
|
+
- skills/worldline-direct/examples/client_integration_example.rb
|
|
658
|
+
- skills/worldline-direct/examples/client_setup.rb
|
|
659
|
+
- skills/worldline-direct/examples/create_payment_response_handler.rb
|
|
660
|
+
- skills/worldline-direct/examples/customer_device.rb
|
|
661
|
+
- skills/worldline-direct/examples/error_handling_example.rb
|
|
662
|
+
- skills/worldline-direct/examples/hosted_checkout_example.rb
|
|
663
|
+
- skills/worldline-direct/examples/hosted_fields_example.rb
|
|
664
|
+
- skills/worldline-direct/examples/hosted_tokenization_example.rb
|
|
665
|
+
- skills/worldline-direct/examples/payment_attempt.rb
|
|
666
|
+
- skills/worldline-direct/examples/payment_links_example.rb
|
|
667
|
+
- skills/worldline-direct/examples/payment_status_example.rb
|
|
668
|
+
- skills/worldline-direct/examples/recurring_payments_example.rb
|
|
669
|
+
- skills/worldline-direct/examples/server_to_server_example.rb
|
|
670
|
+
- skills/worldline-direct/examples/webhook_event_processor.rb
|
|
671
|
+
- skills/worldline-direct/examples/webhooks_endpoint.rb
|
|
672
|
+
- skills/worldline-direct/examples/webhooks_setup.rb
|
|
673
|
+
- skills/worldline-direct/references/errors.md
|
|
674
|
+
- skills/worldline-direct/references/flows.md
|
|
675
|
+
- skills/worldline-direct/references/ruby.md
|
|
676
|
+
- skills/worldline-direct/references/webhooks.md
|
|
653
677
|
homepage: https://github.com/wl-online-payments-direct/sdk-ruby
|
|
654
678
|
licenses:
|
|
655
679
|
- MIT
|