blob: 27397853dea788f35455313dd81bf316519e41f9 [file] [log] [blame]
mathpf709499d2017-01-09 20:48:361// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
rouslan908248c2017-02-27 21:30:245#include "components/payments/content/payment_request.h"
6
mathpd4be8de82017-03-01 00:51:487#include <algorithm>
rouslan908248c2017-02-27 21:30:248#include <unordered_map>
9#include <utility>
mathpf709499d2017-01-09 20:48:3610
tmartino68c0a272017-01-19 17:44:0811#include "base/memory/ptr_util.h"
mathpd4be8de82017-03-01 00:51:4812#include "components/autofill/core/browser/autofill_data_util.h"
13#include "components/autofill/core/browser/field_types.h"
rouslan908248c2017-02-27 21:30:2414#include "components/autofill/core/browser/personal_data_manager.h"
15#include "components/payments/content/payment_details_validation.h"
16#include "components/payments/content/payment_request_web_contents_manager.h"
mathp4b85b582017-03-08 21:07:1617#include "components/payments/core/autofill_payment_instrument.h"
rouslan908248c2017-02-27 21:30:2418#include "components/payments/core/currency_formatter.h"
mathpf709499d2017-01-09 20:48:3619#include "content/public/browser/browser_thread.h"
20#include "content/public/browser/web_contents.h"
21
22namespace payments {
23
mathp4b85b582017-03-08 21:07:1624namespace {
25// Identifier for the basic card payment method in the PaymentMethodData.
26static const char* const kBasicCardMethodName = "basic-card";
27} // namespace
28
mathpf709499d2017-01-09 20:48:3629PaymentRequest::PaymentRequest(
30 content::WebContents* web_contents,
31 std::unique_ptr<PaymentRequestDelegate> delegate,
32 PaymentRequestWebContentsManager* manager,
33 mojo::InterfaceRequest<payments::mojom::PaymentRequest> request)
34 : web_contents_(web_contents),
35 delegate_(std::move(delegate)),
36 manager_(manager),
tmartino36405622017-01-26 16:23:0337 binding_(this, std::move(request)),
mathpd4be8de82017-03-01 00:51:4838 is_ready_to_pay_(false),
tmartino36405622017-01-26 16:23:0339 selected_shipping_profile_(nullptr),
anthonyvd75bc4662017-02-22 22:04:4340 selected_contact_profile_(nullptr),
41 selected_credit_card_(nullptr) {
mathpf4bc50e2017-01-24 05:17:5042 // OnConnectionTerminated will be called when the Mojo pipe is closed. This
43 // will happen as a result of many renderer-side events (both successful and
44 // erroneous in nature).
45 // TODO(crbug.com/683636): Investigate using
46 // set_connection_error_with_reason_handler with Binding::CloseWithReason.
47 binding_.set_connection_error_handler(base::Bind(
48 &PaymentRequest::OnConnectionTerminated, base::Unretained(this)));
mathpf709499d2017-01-09 20:48:3649}
50
51PaymentRequest::~PaymentRequest() {}
52
53void PaymentRequest::Init(
54 payments::mojom::PaymentRequestClientPtr client,
mathpc2d07f962017-02-17 18:33:5155 std::vector<payments::mojom::PaymentMethodDataPtr> method_data,
mathpf709499d2017-01-09 20:48:3656 payments::mojom::PaymentDetailsPtr details,
57 payments::mojom::PaymentOptionsPtr options) {
58 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
59 std::string error;
60 if (!payments::validatePaymentDetails(details, &error)) {
61 LOG(ERROR) << error;
mathpf4bc50e2017-01-24 05:17:5062 OnConnectionTerminated();
mathpf709499d2017-01-09 20:48:3663 return;
64 }
65 client_ = std::move(client);
66 details_ = std::move(details);
mathpd4be8de82017-03-01 00:51:4867 options_ = std::move(options);
mathpc2d07f962017-02-17 18:33:5168 PopulateValidatedMethodData(method_data);
tmartino36405622017-01-26 16:23:0369 PopulateProfileCache();
70 SetDefaultProfileSelections();
mathpf709499d2017-01-09 20:48:3671}
72
73void PaymentRequest::Show() {
tmartino8ce922852017-01-09 22:23:1074 if (!client_.is_bound() || !binding_.is_bound()) {
mathpf4bc50e2017-01-24 05:17:5075 LOG(ERROR) << "Attempted Show(), but binding(s) missing.";
76 OnConnectionTerminated();
tmartino8ce922852017-01-09 22:23:1077 return;
78 }
mathpf4bc50e2017-01-24 05:17:5079 delegate_->ShowDialog(this);
mathpf709499d2017-01-09 20:48:3680}
81
mathpf4bc50e2017-01-24 05:17:5082void PaymentRequest::Abort() {
83 // The API user has decided to abort. We return a successful abort message to
84 // the renderer, which closes the Mojo message pipe, which triggers
85 // PaymentRequest::OnConnectionTerminated, which destroys this object.
86 if (client_.is_bound())
87 client_->OnAbort(true /* aborted_successfully */);
88}
89
mathp4b85b582017-03-08 21:07:1690void PaymentRequest::Complete(payments::mojom::PaymentComplete result) {
91 if (!client_.is_bound())
92 return;
93
94 // TODO(mathp): Validate |result|.
95
96 // When the renderer closes the connection,
97 // PaymentRequest::OnConnectionTerminated will be called.
98 client_->OnComplete();
99}
100
101void PaymentRequest::CanMakePayment() {
102 // TODO(mathp): Return whether we can make payment.
103 client_->OnCanMakePayment(mojom::CanMakePaymentQueryResult::CAN_MAKE_PAYMENT);
104}
105
106void PaymentRequest::OnInstrumentDetailsReady(
107 const std::string& method_name,
108 const std::string& stringified_details) {
109 payment_response_->method_name = method_name;
110 payment_response_->stringified_details = stringified_details;
111 client_->OnPaymentResponse(std::move(payment_response_));
112}
113
mathpf4bc50e2017-01-24 05:17:50114void PaymentRequest::UserCancelled() {
115 // If |client_| is not bound, then the object is already being destroyed as
116 // a result of a renderer event.
117 if (!client_.is_bound())
118 return;
119
120 // This sends an error to the renderer, which informs the API user.
mathpf709499d2017-01-09 20:48:36121 client_->OnError(payments::mojom::PaymentErrorReason::USER_CANCEL);
mathpf4bc50e2017-01-24 05:17:50122
123 // We close all bindings and ask to be destroyed.
124 client_.reset();
125 binding_.Close();
126 manager_->DestroyRequest(this);
mathpf709499d2017-01-09 20:48:36127}
128
mathpf4bc50e2017-01-24 05:17:50129void PaymentRequest::OnConnectionTerminated() {
130 // We are here because of a browser-side error, or likely as a result of the
131 // connection_error_handler on |binding_|, which can mean that the renderer
132 // has decided to close the pipe for various reasons (see all uses of
133 // PaymentRequest::clearResolversAndCloseMojoConnection() in Blink). We close
134 // the binding and the dialog, and ask to be deleted.
135 client_.reset();
mathpf709499d2017-01-09 20:48:36136 binding_.Close();
mathpf4bc50e2017-01-24 05:17:50137 delegate_->CloseDialog();
mathpf709499d2017-01-09 20:48:36138 manager_->DestroyRequest(this);
139}
140
mathpd4be8de82017-03-01 00:51:48141void PaymentRequest::Pay() {
142 DCHECK(is_ready_to_pay_);
143
mathp4b85b582017-03-08 21:07:16144 // TODO(mathp): Fill other fields in the PaymentResponsePtr object.
145 payment_response_ = mojom::PaymentResponse::New();
146
147 // TODO(mathp): PaymentRequest should know about the currently selected
148 // instrument, and not |selected_credit_card_| which is too specific.
149 // TODO(mathp): The method_name should reflect what the merchant asked, and
150 // not necessarily basic-card.
151 selected_payment_instrument_.reset(new AutofillPaymentInstrument(
152 kBasicCardMethodName, *selected_credit_card_, shipping_profiles_,
153 delegate_->GetApplicationLocale()));
154 // Fetch the instrument details, will call back into
155 // PaymentRequest::OnInstrumentsDetailsReady.
156 selected_payment_instrument_->InvokePaymentApp(this);
mathpd4be8de82017-03-01 00:51:48157}
158
159void PaymentRequest::AddObserver(Observer* observer) {
160 CHECK(observer);
161 observers_.AddObserver(observer);
162}
163
164void PaymentRequest::RemoveObserver(Observer* observer) {
165 observers_.RemoveObserver(observer);
166}
167
mathp6758be032017-01-13 04:49:50168CurrencyFormatter* PaymentRequest::GetOrCreateCurrencyFormatter(
169 const std::string& currency_code,
jinho.bang42764542017-01-24 14:42:56170 const std::string& currency_system,
mathp6758be032017-01-13 04:49:50171 const std::string& locale_name) {
172 if (!currency_formatter_) {
173 currency_formatter_.reset(
174 new CurrencyFormatter(currency_code, currency_system, locale_name));
175 }
mathp6758be032017-01-13 04:49:50176 return currency_formatter_.get();
177}
178
anthonyvdb0233f22017-03-06 20:34:47179base::string16 PaymentRequest::GetFormattedCurrencyAmount(
180 const std::string& amount) {
181 CurrencyFormatter* formatter =
182 GetOrCreateCurrencyFormatter(details()->total->amount->currency,
183 details()->total->amount->currency_system,
184 delegate_->GetApplicationLocale());
185 return formatter->Format(amount);
186}
187
188std::string PaymentRequest::GetFormattedCurrencyCode() {
189 CurrencyFormatter* formatter =
190 GetOrCreateCurrencyFormatter(details()->total->amount->currency,
191 details()->total->amount->currency_system,
192 delegate_->GetApplicationLocale());
193
194 return formatter->formatted_currency_code();
195}
196
mathpd4be8de82017-03-01 00:51:48197void PaymentRequest::SetSelectedShippingProfile(
198 autofill::AutofillProfile* profile) {
199 selected_shipping_profile_ = profile;
200 UpdateIsReadyToPayAndNotifyObservers();
tmartino36405622017-01-26 16:23:03201}
202
mathpd4be8de82017-03-01 00:51:48203void PaymentRequest::SetSelectedContactProfile(
204 autofill::AutofillProfile* profile) {
205 selected_contact_profile_ = profile;
206 UpdateIsReadyToPayAndNotifyObservers();
207}
208
209void PaymentRequest::SetSelectedCreditCard(autofill::CreditCard* card) {
210 selected_credit_card_ = card;
211 UpdateIsReadyToPayAndNotifyObservers();
tmartino68c0a272017-01-19 17:44:08212}
213
tmartino36405622017-01-26 16:23:03214void PaymentRequest::PopulateProfileCache() {
tmartino36405622017-01-26 16:23:03215 std::vector<autofill::AutofillProfile*> profiles =
mathpd4cfd8f2017-02-09 21:16:53216 personal_data_manager()->GetProfilesToSuggest();
tmartino36405622017-01-26 16:23:03217
218 // PaymentRequest may outlive the Profiles returned by the Data Manager.
219 // Thus, we store copies, and return a vector of pointers to these copies
anthonyvd75bc4662017-02-22 22:04:43220 // whenever Profiles are requested. The same is true for credit cards.
tmartino36405622017-01-26 16:23:03221 for (size_t i = 0; i < profiles.size(); i++) {
222 profile_cache_.push_back(
223 base::MakeUnique<autofill::AutofillProfile>(*profiles[i]));
224
225 // TODO(tmartino): Implement deduplication rules specific to shipping and
226 // contact profiles.
227 shipping_profiles_.push_back(profile_cache_[i].get());
228 contact_profiles_.push_back(profile_cache_[i].get());
229 }
anthonyvd75bc4662017-02-22 22:04:43230
231 const std::vector<autofill::CreditCard*>& cards =
232 personal_data_manager()->GetCreditCardsToSuggest();
233 for (autofill::CreditCard* card : cards) {
234 card_cache_.push_back(base::MakeUnique<autofill::CreditCard>(*card));
235 credit_cards_.push_back(card_cache_.back().get());
236 }
tmartino36405622017-01-26 16:23:03237}
238
239void PaymentRequest::SetDefaultProfileSelections() {
240 if (!shipping_profiles().empty())
mathpd4be8de82017-03-01 00:51:48241 selected_shipping_profile_ = shipping_profiles()[0];
tmartino36405622017-01-26 16:23:03242
243 if (!contact_profiles().empty())
mathpd4be8de82017-03-01 00:51:48244 selected_contact_profile_ = contact_profiles()[0];
anthonyvd75bc4662017-02-22 22:04:43245
246 // TODO(anthonyvd): Change this code to prioritize server cards and implement
247 // a way to modify this function's return value.
248 const std::vector<autofill::CreditCard*> cards = credit_cards();
249 auto first_complete_card =
250 std::find_if(cards.begin(), cards.end(),
251 [](autofill::CreditCard* card) { return card->IsValid(); });
252
253 selected_credit_card_ =
254 first_complete_card == cards.end() ? nullptr : *first_complete_card;
mathpd4be8de82017-03-01 00:51:48255
256 UpdateIsReadyToPayAndNotifyObservers();
tmartino36405622017-01-26 16:23:03257}
258
mathpc2d07f962017-02-17 18:33:51259void PaymentRequest::PopulateValidatedMethodData(
260 const std::vector<payments::mojom::PaymentMethodDataPtr>& method_data) {
261 if (method_data.empty()) {
262 LOG(ERROR) << "Invalid payment methods or data";
263 OnConnectionTerminated();
264 return;
265 }
266
267 std::set<std::string> card_networks{"amex", "diners", "discover",
268 "jcb", "mastercard", "mir",
269 "unionpay", "visa"};
270 for (const payments::mojom::PaymentMethodDataPtr& method_data_entry :
271 method_data) {
272 std::vector<std::string> supported_methods =
273 method_data_entry->supported_methods;
274 if (supported_methods.empty()) {
275 LOG(ERROR) << "Invalid payment methods or data";
276 OnConnectionTerminated();
277 return;
278 }
279
280 for (const std::string& method : supported_methods) {
281 if (method.empty())
282 continue;
283
284 // If a card network is specified right in "supportedMethods", add it.
285 auto card_it = card_networks.find(method);
286 if (card_it != card_networks.end()) {
287 supported_card_networks_.push_back(method);
288 // |method| removed from |card_networks| so that it is not doubly added
289 // to |supported_card_networks_| if "basic-card" is specified with no
290 // supported networks.
291 card_networks.erase(card_it);
292 } else if (method == kBasicCardMethodName) {
293 // For the "basic-card" method, check "supportedNetworks".
294 if (method_data_entry->supported_networks.empty()) {
295 // Empty |supported_networks| means all networks are supported.
296 supported_card_networks_.insert(supported_card_networks_.end(),
297 card_networks.begin(),
298 card_networks.end());
299 // Clear the set so that no further networks are added to
300 // |supported_card_networks_|.
301 card_networks.clear();
302 } else {
303 // The merchant has specified a few basic card supported networks. Use
304 // the mapping to transform to known basic-card types.
rouslan908248c2017-02-27 21:30:24305 using ::payments::mojom::BasicCardNetwork;
mathpc2d07f962017-02-17 18:33:51306 std::unordered_map<BasicCardNetwork, std::string> networks = {
307 {BasicCardNetwork::AMEX, "amex"},
308 {BasicCardNetwork::DINERS, "diners"},
309 {BasicCardNetwork::DISCOVER, "discover"},
310 {BasicCardNetwork::JCB, "jcb"},
311 {BasicCardNetwork::MASTERCARD, "mastercard"},
312 {BasicCardNetwork::MIR, "mir"},
313 {BasicCardNetwork::UNIONPAY, "unionpay"},
314 {BasicCardNetwork::VISA, "visa"}};
315 for (const BasicCardNetwork& supported_network :
316 method_data_entry->supported_networks) {
317 // Make sure that the network was not already added to
318 // |supported_card_networks_|.
319 auto card_it = card_networks.find(networks[supported_network]);
320 if (card_it != card_networks.end()) {
321 supported_card_networks_.push_back(networks[supported_network]);
322 card_networks.erase(card_it);
323 }
324 }
325 }
326 }
327 }
328 }
329}
330
mathpd4be8de82017-03-01 00:51:48331void PaymentRequest::UpdateIsReadyToPayAndNotifyObservers() {
332 is_ready_to_pay_ =
333 ArePaymentDetailsSatisfied() && ArePaymentOptionsSatisfied();
334 NotifyOnSelectedInformationChanged();
335}
336
337void PaymentRequest::NotifyOnSelectedInformationChanged() {
338 for (auto& observer : observers_)
339 observer.OnSelectedInformationChanged();
340}
341
342bool PaymentRequest::ArePaymentDetailsSatisfied() {
343 // TODO(mathp): A masked card may not satisfy IsValid().
344 if (selected_credit_card_ == nullptr || !selected_credit_card_->IsValid())
345 return false;
346
347 const std::string basic_card_payment_type =
348 autofill::data_util::GetPaymentRequestData(selected_credit_card_->type())
349 .basic_card_payment_type;
350 return !supported_card_networks_.empty() &&
351 std::find(supported_card_networks_.begin(),
352 supported_card_networks_.end(),
353 basic_card_payment_type) != supported_card_networks_.end();
354}
355
356bool PaymentRequest::ArePaymentOptionsSatisfied() {
357 // TODO(mathp): Have a measure of shipping address completeness.
mathpabf66752017-03-01 22:16:44358 if (request_shipping() && selected_shipping_profile_ == nullptr)
mathpd4be8de82017-03-01 00:51:48359 return false;
360
361 // TODO(mathp): Make an encompassing class to validate contact info.
362 const std::string& app_locale = delegate_->GetApplicationLocale();
mathpabf66752017-03-01 22:16:44363 if (request_payer_name() &&
mathpd4be8de82017-03-01 00:51:48364 (selected_contact_profile_ == nullptr ||
365 selected_contact_profile_
366 ->GetInfo(autofill::AutofillType(autofill::NAME_FULL), app_locale)
367 .empty())) {
368 return false;
369 }
mathpabf66752017-03-01 22:16:44370 if (request_payer_email() &&
mathpd4be8de82017-03-01 00:51:48371 (selected_contact_profile_ == nullptr ||
372 selected_contact_profile_
373 ->GetInfo(autofill::AutofillType(autofill::EMAIL_ADDRESS),
374 app_locale)
375 .empty())) {
376 return false;
377 }
mathpabf66752017-03-01 22:16:44378 if (request_payer_phone() &&
mathpd4be8de82017-03-01 00:51:48379 (selected_contact_profile_ == nullptr ||
380 selected_contact_profile_
381 ->GetInfo(autofill::AutofillType(autofill::PHONE_HOME_WHOLE_NUMBER),
382 app_locale)
383 .empty())) {
384 return false;
385 }
386
387 return true;
388}
389
mathpf709499d2017-01-09 20:48:36390} // namespace payments