blob: e55e68b272a5ec75112dfe572c94fadd4b8f4389 [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"
17#include "components/payments/core/currency_formatter.h"
mathpf709499d2017-01-09 20:48:3618#include "content/public/browser/browser_thread.h"
19#include "content/public/browser/web_contents.h"
20
21namespace payments {
22
23PaymentRequest::PaymentRequest(
24 content::WebContents* web_contents,
25 std::unique_ptr<PaymentRequestDelegate> delegate,
26 PaymentRequestWebContentsManager* manager,
27 mojo::InterfaceRequest<payments::mojom::PaymentRequest> request)
28 : web_contents_(web_contents),
29 delegate_(std::move(delegate)),
30 manager_(manager),
tmartino36405622017-01-26 16:23:0331 binding_(this, std::move(request)),
mathpd4be8de82017-03-01 00:51:4832 is_ready_to_pay_(false),
tmartino36405622017-01-26 16:23:0333 selected_shipping_profile_(nullptr),
anthonyvd75bc4662017-02-22 22:04:4334 selected_contact_profile_(nullptr),
35 selected_credit_card_(nullptr) {
mathpf4bc50e2017-01-24 05:17:5036 // OnConnectionTerminated will be called when the Mojo pipe is closed. This
37 // will happen as a result of many renderer-side events (both successful and
38 // erroneous in nature).
39 // TODO(crbug.com/683636): Investigate using
40 // set_connection_error_with_reason_handler with Binding::CloseWithReason.
41 binding_.set_connection_error_handler(base::Bind(
42 &PaymentRequest::OnConnectionTerminated, base::Unretained(this)));
mathpf709499d2017-01-09 20:48:3643}
44
45PaymentRequest::~PaymentRequest() {}
46
47void PaymentRequest::Init(
48 payments::mojom::PaymentRequestClientPtr client,
mathpc2d07f962017-02-17 18:33:5149 std::vector<payments::mojom::PaymentMethodDataPtr> method_data,
mathpf709499d2017-01-09 20:48:3650 payments::mojom::PaymentDetailsPtr details,
51 payments::mojom::PaymentOptionsPtr options) {
52 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
53 std::string error;
54 if (!payments::validatePaymentDetails(details, &error)) {
55 LOG(ERROR) << error;
mathpf4bc50e2017-01-24 05:17:5056 OnConnectionTerminated();
mathpf709499d2017-01-09 20:48:3657 return;
58 }
59 client_ = std::move(client);
60 details_ = std::move(details);
mathpd4be8de82017-03-01 00:51:4861 options_ = std::move(options);
mathpc2d07f962017-02-17 18:33:5162 PopulateValidatedMethodData(method_data);
tmartino36405622017-01-26 16:23:0363 PopulateProfileCache();
64 SetDefaultProfileSelections();
mathpf709499d2017-01-09 20:48:3665}
66
67void PaymentRequest::Show() {
tmartino8ce922852017-01-09 22:23:1068 if (!client_.is_bound() || !binding_.is_bound()) {
mathpf4bc50e2017-01-24 05:17:5069 LOG(ERROR) << "Attempted Show(), but binding(s) missing.";
70 OnConnectionTerminated();
tmartino8ce922852017-01-09 22:23:1071 return;
72 }
mathpf4bc50e2017-01-24 05:17:5073 delegate_->ShowDialog(this);
mathpf709499d2017-01-09 20:48:3674}
75
mathpf4bc50e2017-01-24 05:17:5076void PaymentRequest::Abort() {
77 // The API user has decided to abort. We return a successful abort message to
78 // the renderer, which closes the Mojo message pipe, which triggers
79 // PaymentRequest::OnConnectionTerminated, which destroys this object.
80 if (client_.is_bound())
81 client_->OnAbort(true /* aborted_successfully */);
82}
83
84void PaymentRequest::UserCancelled() {
85 // If |client_| is not bound, then the object is already being destroyed as
86 // a result of a renderer event.
87 if (!client_.is_bound())
88 return;
89
90 // This sends an error to the renderer, which informs the API user.
mathpf709499d2017-01-09 20:48:3691 client_->OnError(payments::mojom::PaymentErrorReason::USER_CANCEL);
mathpf4bc50e2017-01-24 05:17:5092
93 // We close all bindings and ask to be destroyed.
94 client_.reset();
95 binding_.Close();
96 manager_->DestroyRequest(this);
mathpf709499d2017-01-09 20:48:3697}
98
mathpf4bc50e2017-01-24 05:17:5099void PaymentRequest::OnConnectionTerminated() {
100 // We are here because of a browser-side error, or likely as a result of the
101 // connection_error_handler on |binding_|, which can mean that the renderer
102 // has decided to close the pipe for various reasons (see all uses of
103 // PaymentRequest::clearResolversAndCloseMojoConnection() in Blink). We close
104 // the binding and the dialog, and ask to be deleted.
105 client_.reset();
mathpf709499d2017-01-09 20:48:36106 binding_.Close();
mathpf4bc50e2017-01-24 05:17:50107 delegate_->CloseDialog();
mathpf709499d2017-01-09 20:48:36108 manager_->DestroyRequest(this);
109}
110
mathpd4be8de82017-03-01 00:51:48111void PaymentRequest::Pay() {
112 DCHECK(is_ready_to_pay_);
113
114 // TODO(mathp): Return the PaymentResponse to the |client_|.
mathp64703412017-03-01 20:11:15115 OnConnectionTerminated();
mathpd4be8de82017-03-01 00:51:48116}
117
118void PaymentRequest::AddObserver(Observer* observer) {
119 CHECK(observer);
120 observers_.AddObserver(observer);
121}
122
123void PaymentRequest::RemoveObserver(Observer* observer) {
124 observers_.RemoveObserver(observer);
125}
126
mathp6758be032017-01-13 04:49:50127CurrencyFormatter* PaymentRequest::GetOrCreateCurrencyFormatter(
128 const std::string& currency_code,
jinho.bang42764542017-01-24 14:42:56129 const std::string& currency_system,
mathp6758be032017-01-13 04:49:50130 const std::string& locale_name) {
131 if (!currency_formatter_) {
132 currency_formatter_.reset(
133 new CurrencyFormatter(currency_code, currency_system, locale_name));
134 }
mathp6758be032017-01-13 04:49:50135 return currency_formatter_.get();
136}
137
mathpd4be8de82017-03-01 00:51:48138void PaymentRequest::SetSelectedShippingProfile(
139 autofill::AutofillProfile* profile) {
140 selected_shipping_profile_ = profile;
141 UpdateIsReadyToPayAndNotifyObservers();
tmartino36405622017-01-26 16:23:03142}
143
mathpd4be8de82017-03-01 00:51:48144void PaymentRequest::SetSelectedContactProfile(
145 autofill::AutofillProfile* profile) {
146 selected_contact_profile_ = profile;
147 UpdateIsReadyToPayAndNotifyObservers();
148}
149
150void PaymentRequest::SetSelectedCreditCard(autofill::CreditCard* card) {
151 selected_credit_card_ = card;
152 UpdateIsReadyToPayAndNotifyObservers();
tmartino68c0a272017-01-19 17:44:08153}
154
tmartino36405622017-01-26 16:23:03155void PaymentRequest::PopulateProfileCache() {
tmartino36405622017-01-26 16:23:03156 std::vector<autofill::AutofillProfile*> profiles =
mathpd4cfd8f2017-02-09 21:16:53157 personal_data_manager()->GetProfilesToSuggest();
tmartino36405622017-01-26 16:23:03158
159 // PaymentRequest may outlive the Profiles returned by the Data Manager.
160 // Thus, we store copies, and return a vector of pointers to these copies
anthonyvd75bc4662017-02-22 22:04:43161 // whenever Profiles are requested. The same is true for credit cards.
tmartino36405622017-01-26 16:23:03162 for (size_t i = 0; i < profiles.size(); i++) {
163 profile_cache_.push_back(
164 base::MakeUnique<autofill::AutofillProfile>(*profiles[i]));
165
166 // TODO(tmartino): Implement deduplication rules specific to shipping and
167 // contact profiles.
168 shipping_profiles_.push_back(profile_cache_[i].get());
169 contact_profiles_.push_back(profile_cache_[i].get());
170 }
anthonyvd75bc4662017-02-22 22:04:43171
172 const std::vector<autofill::CreditCard*>& cards =
173 personal_data_manager()->GetCreditCardsToSuggest();
174 for (autofill::CreditCard* card : cards) {
175 card_cache_.push_back(base::MakeUnique<autofill::CreditCard>(*card));
176 credit_cards_.push_back(card_cache_.back().get());
177 }
tmartino36405622017-01-26 16:23:03178}
179
180void PaymentRequest::SetDefaultProfileSelections() {
181 if (!shipping_profiles().empty())
mathpd4be8de82017-03-01 00:51:48182 selected_shipping_profile_ = shipping_profiles()[0];
tmartino36405622017-01-26 16:23:03183
184 if (!contact_profiles().empty())
mathpd4be8de82017-03-01 00:51:48185 selected_contact_profile_ = contact_profiles()[0];
anthonyvd75bc4662017-02-22 22:04:43186
187 // TODO(anthonyvd): Change this code to prioritize server cards and implement
188 // a way to modify this function's return value.
189 const std::vector<autofill::CreditCard*> cards = credit_cards();
190 auto first_complete_card =
191 std::find_if(cards.begin(), cards.end(),
192 [](autofill::CreditCard* card) { return card->IsValid(); });
193
194 selected_credit_card_ =
195 first_complete_card == cards.end() ? nullptr : *first_complete_card;
mathpd4be8de82017-03-01 00:51:48196
197 UpdateIsReadyToPayAndNotifyObservers();
tmartino36405622017-01-26 16:23:03198}
199
mathpc2d07f962017-02-17 18:33:51200void PaymentRequest::PopulateValidatedMethodData(
201 const std::vector<payments::mojom::PaymentMethodDataPtr>& method_data) {
202 if (method_data.empty()) {
203 LOG(ERROR) << "Invalid payment methods or data";
204 OnConnectionTerminated();
205 return;
206 }
207
rouslan908248c2017-02-27 21:30:24208 // Identifier for the basic card payment method in the PaymentMethodData.
209 const char* const kBasicCardMethodName = "basic-card";
mathpc2d07f962017-02-17 18:33:51210 std::set<std::string> card_networks{"amex", "diners", "discover",
211 "jcb", "mastercard", "mir",
212 "unionpay", "visa"};
213 for (const payments::mojom::PaymentMethodDataPtr& method_data_entry :
214 method_data) {
215 std::vector<std::string> supported_methods =
216 method_data_entry->supported_methods;
217 if (supported_methods.empty()) {
218 LOG(ERROR) << "Invalid payment methods or data";
219 OnConnectionTerminated();
220 return;
221 }
222
223 for (const std::string& method : supported_methods) {
224 if (method.empty())
225 continue;
226
227 // If a card network is specified right in "supportedMethods", add it.
228 auto card_it = card_networks.find(method);
229 if (card_it != card_networks.end()) {
230 supported_card_networks_.push_back(method);
231 // |method| removed from |card_networks| so that it is not doubly added
232 // to |supported_card_networks_| if "basic-card" is specified with no
233 // supported networks.
234 card_networks.erase(card_it);
235 } else if (method == kBasicCardMethodName) {
236 // For the "basic-card" method, check "supportedNetworks".
237 if (method_data_entry->supported_networks.empty()) {
238 // Empty |supported_networks| means all networks are supported.
239 supported_card_networks_.insert(supported_card_networks_.end(),
240 card_networks.begin(),
241 card_networks.end());
242 // Clear the set so that no further networks are added to
243 // |supported_card_networks_|.
244 card_networks.clear();
245 } else {
246 // The merchant has specified a few basic card supported networks. Use
247 // the mapping to transform to known basic-card types.
rouslan908248c2017-02-27 21:30:24248 using ::payments::mojom::BasicCardNetwork;
mathpc2d07f962017-02-17 18:33:51249 std::unordered_map<BasicCardNetwork, std::string> networks = {
250 {BasicCardNetwork::AMEX, "amex"},
251 {BasicCardNetwork::DINERS, "diners"},
252 {BasicCardNetwork::DISCOVER, "discover"},
253 {BasicCardNetwork::JCB, "jcb"},
254 {BasicCardNetwork::MASTERCARD, "mastercard"},
255 {BasicCardNetwork::MIR, "mir"},
256 {BasicCardNetwork::UNIONPAY, "unionpay"},
257 {BasicCardNetwork::VISA, "visa"}};
258 for (const BasicCardNetwork& supported_network :
259 method_data_entry->supported_networks) {
260 // Make sure that the network was not already added to
261 // |supported_card_networks_|.
262 auto card_it = card_networks.find(networks[supported_network]);
263 if (card_it != card_networks.end()) {
264 supported_card_networks_.push_back(networks[supported_network]);
265 card_networks.erase(card_it);
266 }
267 }
268 }
269 }
270 }
271 }
272}
273
mathpd4be8de82017-03-01 00:51:48274void PaymentRequest::UpdateIsReadyToPayAndNotifyObservers() {
275 is_ready_to_pay_ =
276 ArePaymentDetailsSatisfied() && ArePaymentOptionsSatisfied();
277 NotifyOnSelectedInformationChanged();
278}
279
280void PaymentRequest::NotifyOnSelectedInformationChanged() {
281 for (auto& observer : observers_)
282 observer.OnSelectedInformationChanged();
283}
284
285bool PaymentRequest::ArePaymentDetailsSatisfied() {
286 // TODO(mathp): A masked card may not satisfy IsValid().
287 if (selected_credit_card_ == nullptr || !selected_credit_card_->IsValid())
288 return false;
289
290 const std::string basic_card_payment_type =
291 autofill::data_util::GetPaymentRequestData(selected_credit_card_->type())
292 .basic_card_payment_type;
293 return !supported_card_networks_.empty() &&
294 std::find(supported_card_networks_.begin(),
295 supported_card_networks_.end(),
296 basic_card_payment_type) != supported_card_networks_.end();
297}
298
299bool PaymentRequest::ArePaymentOptionsSatisfied() {
300 // TODO(mathp): Have a measure of shipping address completeness.
mathpabf66752017-03-01 22:16:44301 if (request_shipping() && selected_shipping_profile_ == nullptr)
mathpd4be8de82017-03-01 00:51:48302 return false;
303
304 // TODO(mathp): Make an encompassing class to validate contact info.
305 const std::string& app_locale = delegate_->GetApplicationLocale();
mathpabf66752017-03-01 22:16:44306 if (request_payer_name() &&
mathpd4be8de82017-03-01 00:51:48307 (selected_contact_profile_ == nullptr ||
308 selected_contact_profile_
309 ->GetInfo(autofill::AutofillType(autofill::NAME_FULL), app_locale)
310 .empty())) {
311 return false;
312 }
mathpabf66752017-03-01 22:16:44313 if (request_payer_email() &&
mathpd4be8de82017-03-01 00:51:48314 (selected_contact_profile_ == nullptr ||
315 selected_contact_profile_
316 ->GetInfo(autofill::AutofillType(autofill::EMAIL_ADDRESS),
317 app_locale)
318 .empty())) {
319 return false;
320 }
mathpabf66752017-03-01 22:16:44321 if (request_payer_phone() &&
mathpd4be8de82017-03-01 00:51:48322 (selected_contact_profile_ == nullptr ||
323 selected_contact_profile_
324 ->GetInfo(autofill::AutofillType(autofill::PHONE_HOME_WHOLE_NUMBER),
325 app_locale)
326 .empty())) {
327 return false;
328 }
329
330 return true;
331}
332
mathpf709499d2017-01-09 20:48:36333} // namespace payments