1 // Copyright 2013 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 5 #include "components/autofill/content/browser/wallet/wallet_client.h" 6 7 #include "base/bind.h" 8 #include "base/json/json_reader.h" 9 #include "base/json/json_writer.h" 10 #include "base/logging.h" 11 #include "base/memory/scoped_ptr.h" 12 #include "base/message_loop/message_loop.h" 13 #include "base/strings/string_number_conversions.h" 14 #include "base/strings/string_util.h" 15 #include "base/strings/stringprintf.h" 16 #include "base/strings/utf_string_conversions.h" 17 #include "components/autofill/content/browser/wallet/form_field_error.h" 18 #include "components/autofill/content/browser/wallet/instrument.h" 19 #include "components/autofill/content/browser/wallet/wallet_address.h" 20 #include "components/autofill/content/browser/wallet/wallet_client_delegate.h" 21 #include "components/autofill/content/browser/wallet/wallet_items.h" 22 #include "components/autofill/content/browser/wallet/wallet_service_url.h" 23 #include "components/autofill/core/browser/autofill_metrics.h" 24 #include "crypto/random.h" 25 #include "google_apis/google_api_keys.h" 26 #include "net/base/escape.h" 27 #include "net/http/http_status_code.h" 28 #include "net/url_request/url_fetcher.h" 29 #include "net/url_request/url_request_context_getter.h" 30 31 namespace autofill { 32 namespace wallet { 33 34 namespace { 35 36 const char kFormEncodedMimeType[] = "application/x-www-form-urlencoded"; 37 const char kJsonMimeType[] = "application/json"; 38 const char kEscrowNewInstrumentFormat[] = 39 "request_content_type=application/json&request=%s&cvn=%s&card_number=%s"; 40 const char kEscrowCardVerificationNumberFormat[] = 41 "request_content_type=application/json&request=%s&cvn=%s"; 42 const char kGetFullWalletRequestFormat[] = 43 "request_content_type=application/json&request=%s&otp=%s:%s"; 44 const size_t kOneTimePadLength = 6; 45 46 // The maximum number of bits in the one time pad that the server is willing to 47 // accept. 48 const size_t kMaxBits = 56; 49 50 // The minimum number of bits in the one time pad that the server is willing to 51 // accept. 52 const size_t kMinBits = 40; 53 54 std::string RiskCapabilityToString( 55 WalletClient::RiskCapability risk_capability) { 56 switch (risk_capability) { 57 case WalletClient::RELOGIN: 58 return "RELOGIN"; 59 case WalletClient::VERIFY_CVC: 60 return "VERIFY_CVC"; 61 } 62 NOTREACHED(); 63 return "NOT_POSSIBLE"; 64 } 65 66 WalletClient::ErrorType StringToErrorType(const std::string& error_type) { 67 std::string trimmed; 68 base::TrimWhitespaceASCII(error_type, base::TRIM_ALL, &trimmed); 69 if (LowerCaseEqualsASCII(trimmed, "buyer_account_error")) 70 return WalletClient::BUYER_ACCOUNT_ERROR; 71 if (LowerCaseEqualsASCII(trimmed, "unsupported_merchant")) 72 return WalletClient::UNSUPPORTED_MERCHANT; 73 if (LowerCaseEqualsASCII(trimmed, "internal_error")) 74 return WalletClient::INTERNAL_ERROR; 75 if (LowerCaseEqualsASCII(trimmed, "invalid_params")) 76 return WalletClient::INVALID_PARAMS; 77 if (LowerCaseEqualsASCII(trimmed, "service_unavailable")) 78 return WalletClient::SERVICE_UNAVAILABLE; 79 if (LowerCaseEqualsASCII(trimmed, "unsupported_api_version")) 80 return WalletClient::UNSUPPORTED_API_VERSION; 81 if (LowerCaseEqualsASCII(trimmed, "unsupported_user_agent")) 82 return WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY; 83 84 DVLOG(1) << "Unknown wallet error string: \"" << error_type << '"'; 85 return WalletClient::UNKNOWN_ERROR; 86 } 87 88 // Get the more specific WalletClient::ErrorType when the error is 89 // |BUYER_ACCOUNT_ERROR|. 90 WalletClient::ErrorType BuyerErrorStringToErrorType( 91 const std::string& message_type_for_buyer) { 92 std::string trimmed; 93 base::TrimWhitespaceASCII(message_type_for_buyer, base::TRIM_ALL, &trimmed); 94 if (LowerCaseEqualsASCII(trimmed, "bla_country_not_supported")) 95 return WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED; 96 if (LowerCaseEqualsASCII(trimmed, "buyer_kyc_error")) 97 return WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS; 98 99 return WalletClient::BUYER_ACCOUNT_ERROR; 100 } 101 102 // Gets and parses required actions from a SaveToWallet response. Returns 103 // false if any unknown required actions are seen and true otherwise. 104 void GetRequiredActionsForSaveToWallet( 105 const base::DictionaryValue& dict, 106 std::vector<RequiredAction>* required_actions) { 107 const base::ListValue* required_action_list; 108 if (!dict.GetList("required_action", &required_action_list)) 109 return; 110 111 for (size_t i = 0; i < required_action_list->GetSize(); ++i) { 112 std::string action_string; 113 if (required_action_list->GetString(i, &action_string)) { 114 RequiredAction action = ParseRequiredActionFromString(action_string); 115 if (!ActionAppliesToSaveToWallet(action)) { 116 DLOG(ERROR) << "Response from Google wallet with bad required action:" 117 " \"" << action_string << "\""; 118 required_actions->clear(); 119 return; 120 } 121 required_actions->push_back(action); 122 } 123 } 124 } 125 126 void GetFormFieldErrors(const base::DictionaryValue& dict, 127 std::vector<FormFieldError>* form_errors) { 128 DCHECK(form_errors->empty()); 129 const base::ListValue* form_errors_list; 130 if (!dict.GetList("form_field_error", &form_errors_list)) 131 return; 132 133 for (size_t i = 0; i < form_errors_list->GetSize(); ++i) { 134 const base::DictionaryValue* dictionary; 135 if (form_errors_list->GetDictionary(i, &dictionary)) 136 form_errors->push_back(FormFieldError::CreateFormFieldError(*dictionary)); 137 } 138 } 139 140 // Converts the |error_type| to the corresponding value from the stable UMA 141 // metric enumeration. 142 AutofillMetrics::WalletErrorMetric ErrorTypeToUmaMetric( 143 WalletClient::ErrorType error_type) { 144 switch (error_type) { 145 case WalletClient::BAD_REQUEST: 146 return AutofillMetrics::WALLET_BAD_REQUEST; 147 case WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED: 148 return AutofillMetrics::WALLET_BUYER_LEGAL_ADDRESS_NOT_SUPPORTED; 149 case WalletClient::BUYER_ACCOUNT_ERROR: 150 return AutofillMetrics::WALLET_BUYER_ACCOUNT_ERROR; 151 case WalletClient::INTERNAL_ERROR: 152 return AutofillMetrics::WALLET_INTERNAL_ERROR; 153 case WalletClient::INVALID_PARAMS: 154 return AutofillMetrics::WALLET_INVALID_PARAMS; 155 case WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS: 156 return AutofillMetrics::WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS; 157 case WalletClient::SERVICE_UNAVAILABLE: 158 return AutofillMetrics::WALLET_SERVICE_UNAVAILABLE; 159 case WalletClient::UNSUPPORTED_API_VERSION: 160 return AutofillMetrics::WALLET_UNSUPPORTED_API_VERSION; 161 case WalletClient::UNSUPPORTED_MERCHANT: 162 return AutofillMetrics::WALLET_UNSUPPORTED_MERCHANT; 163 case WalletClient::MALFORMED_RESPONSE: 164 return AutofillMetrics::WALLET_MALFORMED_RESPONSE; 165 case WalletClient::NETWORK_ERROR: 166 return AutofillMetrics::WALLET_NETWORK_ERROR; 167 case WalletClient::UNKNOWN_ERROR: 168 return AutofillMetrics::WALLET_UNKNOWN_ERROR; 169 case WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY: 170 return AutofillMetrics::WALLET_UNSUPPORTED_USER_AGENT_OR_API_KEY; 171 } 172 173 NOTREACHED(); 174 return AutofillMetrics::WALLET_UNKNOWN_ERROR; 175 } 176 177 // Converts the |required_action| to the corresponding value from the stable UMA 178 // metric enumeration. 179 AutofillMetrics::WalletRequiredActionMetric RequiredActionToUmaMetric( 180 RequiredAction required_action) { 181 switch (required_action) { 182 case UNKNOWN_TYPE: 183 return AutofillMetrics::UNKNOWN_REQUIRED_ACTION; 184 case CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS: 185 return AutofillMetrics::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS; 186 case SETUP_WALLET: 187 return AutofillMetrics::SETUP_WALLET; 188 case ACCEPT_TOS: 189 return AutofillMetrics::ACCEPT_TOS; 190 case GAIA_AUTH: 191 return AutofillMetrics::GAIA_AUTH; 192 case UPDATE_EXPIRATION_DATE: 193 return AutofillMetrics::UPDATE_EXPIRATION_DATE; 194 case UPGRADE_MIN_ADDRESS: 195 return AutofillMetrics::UPGRADE_MIN_ADDRESS; 196 case INVALID_FORM_FIELD: 197 return AutofillMetrics::INVALID_FORM_FIELD; 198 case VERIFY_CVV: 199 return AutofillMetrics::VERIFY_CVV; 200 case PASSIVE_GAIA_AUTH: 201 return AutofillMetrics::PASSIVE_GAIA_AUTH; 202 case REQUIRE_PHONE_NUMBER: 203 return AutofillMetrics::REQUIRE_PHONE_NUMBER; 204 } 205 206 NOTREACHED(); 207 return AutofillMetrics::UNKNOWN_REQUIRED_ACTION; 208 } 209 210 // Keys for JSON communication with the Online Wallet server. 211 const char kAcceptedLegalDocumentKey[] = "accepted_legal_document"; 212 const char kApiKeyKey[] = "api_key"; 213 const char kAuthResultKey[] = "auth_result"; 214 const char kErrorTypeKey[] = "wallet_error.error_type"; 215 const char kFeatureKey[] = "feature"; 216 const char kGoogleTransactionIdKey[] = "google_transaction_id"; 217 const char kInstrumentIdKey[] = "instrument_id"; 218 const char kInstrumentKey[] = "instrument"; 219 const char kInstrumentExpMonthKey[] = "instrument.credit_card.exp_month"; 220 const char kInstrumentExpYearKey[] = "instrument.credit_card.exp_year"; 221 const char kInstrumentType[] = "instrument.type"; 222 const char kInstrumentPhoneNumberKey[] = "instrument_phone_number"; 223 const char kMerchantDomainKey[] = "merchant_domain"; 224 const char kMessageTypeForBuyerKey[] = "wallet_error.message_type_for_buyer"; 225 const char kNewWalletUser[] = "new_wallet_user"; 226 const char kPhoneNumberRequired[] = "phone_number_required"; 227 const char kRiskCapabilitiesKey[] = "supported_risk_challenge"; 228 const char kRiskParamsKey[] = "risk_params"; 229 const char kSelectedAddressIdKey[] = "selected_address_id"; 230 const char kSelectedInstrumentIdKey[] = "selected_instrument_id"; 231 const char kShippingAddressIdKey[] = "shipping_address_id"; 232 const char kShippingAddressKey[] = "shipping_address"; 233 const char kShippingAddressRequired[] = "shipping_address_required"; 234 const char kUpgradedBillingAddressKey[] = "upgraded_billing_address"; 235 const char kUpgradedInstrumentIdKey[] = "upgraded_instrument_id"; 236 const char kUseMinimalAddresses[] = "use_minimal_addresses"; 237 238 } // namespace 239 240 WalletClient::FullWalletRequest::FullWalletRequest( 241 const std::string& instrument_id, 242 const std::string& address_id, 243 const std::string& google_transaction_id, 244 const std::vector<RiskCapability> risk_capabilities, 245 bool new_wallet_user) 246 : instrument_id(instrument_id), 247 address_id(address_id), 248 google_transaction_id(google_transaction_id), 249 risk_capabilities(risk_capabilities), 250 new_wallet_user(new_wallet_user) {} 251 252 WalletClient::FullWalletRequest::~FullWalletRequest() {} 253 254 WalletClient::WalletClient(net::URLRequestContextGetter* context_getter, 255 WalletClientDelegate* delegate, 256 const GURL& source_url) 257 : context_getter_(context_getter), 258 delegate_(delegate), 259 user_index_(0U), 260 source_url_(source_url), 261 request_type_(NO_REQUEST), 262 one_time_pad_(kOneTimePadLength), 263 weak_ptr_factory_(this) { 264 DCHECK(context_getter_.get()); 265 DCHECK(delegate_); 266 } 267 268 WalletClient::~WalletClient() {} 269 270 void WalletClient::AcceptLegalDocuments( 271 const std::vector<WalletItems::LegalDocument*>& documents, 272 const std::string& google_transaction_id) { 273 if (documents.empty()) 274 return; 275 276 std::vector<std::string> document_ids; 277 for (size_t i = 0; i < documents.size(); ++i) { 278 document_ids.push_back(documents[i]->id()); 279 } 280 DoAcceptLegalDocuments(document_ids, google_transaction_id); 281 } 282 283 void WalletClient::AuthenticateInstrument( 284 const std::string& instrument_id, 285 const std::string& card_verification_number) { 286 base::DictionaryValue request_dict; 287 request_dict.SetString(kApiKeyKey, google_apis::GetAPIKey()); 288 request_dict.SetString(kRiskParamsKey, delegate_->GetRiskData()); 289 request_dict.SetString(kInstrumentIdKey, instrument_id); 290 291 std::string json_payload; 292 base::JSONWriter::Write(&request_dict, &json_payload); 293 294 std::string escaped_card_verification_number = net::EscapeUrlEncodedData( 295 card_verification_number, true); 296 297 std::string post_body = base::StringPrintf( 298 kEscrowCardVerificationNumberFormat, 299 net::EscapeUrlEncodedData(json_payload, true).c_str(), 300 escaped_card_verification_number.c_str()); 301 302 MakeWalletRequest(GetAuthenticateInstrumentUrl(user_index_), 303 post_body, 304 kFormEncodedMimeType, 305 AUTHENTICATE_INSTRUMENT); 306 } 307 308 void WalletClient::GetFullWallet(const FullWalletRequest& full_wallet_request) { 309 base::DictionaryValue request_dict; 310 request_dict.SetString(kApiKeyKey, google_apis::GetAPIKey()); 311 request_dict.SetString(kRiskParamsKey, delegate_->GetRiskData()); 312 request_dict.SetBoolean(kUseMinimalAddresses, false); 313 request_dict.SetBoolean(kPhoneNumberRequired, true); 314 request_dict.SetBoolean(kNewWalletUser, full_wallet_request.new_wallet_user); 315 316 request_dict.SetString(kSelectedInstrumentIdKey, 317 full_wallet_request.instrument_id); 318 request_dict.SetString(kSelectedAddressIdKey, full_wallet_request.address_id); 319 request_dict.SetString( 320 kMerchantDomainKey, 321 source_url_.GetWithEmptyPath().spec()); 322 request_dict.SetString(kGoogleTransactionIdKey, 323 full_wallet_request.google_transaction_id); 324 request_dict.SetString(kFeatureKey, "REQUEST_AUTOCOMPLETE"); 325 326 scoped_ptr<base::ListValue> risk_capabilities_list(new base::ListValue()); 327 for (std::vector<RiskCapability>::const_iterator it = 328 full_wallet_request.risk_capabilities.begin(); 329 it != full_wallet_request.risk_capabilities.end(); 330 ++it) { 331 risk_capabilities_list->AppendString(RiskCapabilityToString(*it)); 332 } 333 request_dict.Set(kRiskCapabilitiesKey, risk_capabilities_list.release()); 334 335 std::string json_payload; 336 base::JSONWriter::Write(&request_dict, &json_payload); 337 338 crypto::RandBytes(&(one_time_pad_[0]), one_time_pad_.size()); 339 340 size_t num_bits = one_time_pad_.size() * 8; 341 DCHECK_LE(num_bits, kMaxBits); 342 DCHECK_GE(num_bits, kMinBits); 343 344 std::string post_body = base::StringPrintf( 345 kGetFullWalletRequestFormat, 346 net::EscapeUrlEncodedData(json_payload, true).c_str(), 347 base::HexEncode(&num_bits, 1).c_str(), 348 base::HexEncode(&(one_time_pad_[0]), one_time_pad_.size()).c_str()); 349 350 MakeWalletRequest(GetGetFullWalletUrl(user_index_), 351 post_body, 352 kFormEncodedMimeType, 353 GET_FULL_WALLET); 354 } 355 356 void WalletClient::SaveToWallet( 357 scoped_ptr<Instrument> instrument, 358 scoped_ptr<Address> address, 359 const WalletItems::MaskedInstrument* reference_instrument, 360 const Address* reference_address) { 361 DCHECK(instrument || address); 362 363 base::DictionaryValue request_dict; 364 request_dict.SetString(kApiKeyKey, google_apis::GetAPIKey()); 365 request_dict.SetString(kRiskParamsKey, delegate_->GetRiskData()); 366 request_dict.SetString(kMerchantDomainKey, 367 source_url_.GetWithEmptyPath().spec()); 368 request_dict.SetBoolean(kUseMinimalAddresses, false); 369 request_dict.SetBoolean(kPhoneNumberRequired, true); 370 371 std::string primary_account_number; 372 std::string card_verification_number; 373 if (instrument) { 374 primary_account_number = net::EscapeUrlEncodedData( 375 base::UTF16ToUTF8(instrument->primary_account_number()), true); 376 card_verification_number = net::EscapeUrlEncodedData( 377 base::UTF16ToUTF8(instrument->card_verification_number()), true); 378 379 if (!reference_instrument) { 380 request_dict.Set(kInstrumentKey, instrument->ToDictionary().release()); 381 request_dict.SetString(kInstrumentPhoneNumberKey, 382 instrument->address()->phone_number()); 383 } else { 384 DCHECK(!reference_instrument->object_id().empty()); 385 386 int new_month = instrument->expiration_month(); 387 int new_year = instrument->expiration_year(); 388 bool expiration_date_changed = 389 new_month != reference_instrument->expiration_month() || 390 new_year != reference_instrument->expiration_year(); 391 392 DCHECK(instrument->address() || expiration_date_changed); 393 394 request_dict.SetString(kUpgradedInstrumentIdKey, 395 reference_instrument->object_id()); 396 397 if (instrument->address()) { 398 request_dict.SetString(kInstrumentPhoneNumberKey, 399 instrument->address()->phone_number()); 400 request_dict.Set( 401 kUpgradedBillingAddressKey, 402 instrument->address()->ToDictionaryWithoutID().release()); 403 } 404 405 if (expiration_date_changed) { 406 // Updating expiration date requires a CVC. 407 DCHECK(!instrument->card_verification_number().empty()); 408 request_dict.SetInteger(kInstrumentExpMonthKey, 409 instrument->expiration_month()); 410 request_dict.SetInteger(kInstrumentExpYearKey, 411 instrument->expiration_year()); 412 } 413 414 if (request_dict.HasKey(kInstrumentKey)) 415 request_dict.SetString(kInstrumentType, "CREDIT_CARD"); 416 } 417 } 418 if (address) { 419 if (reference_address) { 420 address->set_object_id(reference_address->object_id()); 421 DCHECK(!address->object_id().empty()); 422 } 423 request_dict.Set(kShippingAddressKey, 424 address->ToDictionaryWithID().release()); 425 } 426 427 std::string json_payload; 428 base::JSONWriter::Write(&request_dict, &json_payload); 429 430 if (!card_verification_number.empty()) { 431 std::string post_body; 432 if (!primary_account_number.empty()) { 433 post_body = base::StringPrintf( 434 kEscrowNewInstrumentFormat, 435 net::EscapeUrlEncodedData(json_payload, true).c_str(), 436 card_verification_number.c_str(), 437 primary_account_number.c_str()); 438 } else { 439 post_body = base::StringPrintf( 440 kEscrowCardVerificationNumberFormat, 441 net::EscapeUrlEncodedData(json_payload, true).c_str(), 442 card_verification_number.c_str()); 443 } 444 MakeWalletRequest(GetSaveToWalletUrl(user_index_), 445 post_body, 446 kFormEncodedMimeType, 447 SAVE_TO_WALLET); 448 } else { 449 MakeWalletRequest(GetSaveToWalletNoEscrowUrl(user_index_), 450 json_payload, 451 kJsonMimeType, 452 SAVE_TO_WALLET); 453 } 454 } 455 456 void WalletClient::GetWalletItems() { 457 base::DictionaryValue request_dict; 458 request_dict.SetString(kApiKeyKey, google_apis::GetAPIKey()); 459 request_dict.SetString(kMerchantDomainKey, 460 source_url_.GetWithEmptyPath().spec()); 461 request_dict.SetBoolean(kShippingAddressRequired, 462 delegate_->IsShippingAddressRequired()); 463 request_dict.SetBoolean(kUseMinimalAddresses, false); 464 request_dict.SetBoolean(kPhoneNumberRequired, true); 465 466 std::string post_body; 467 base::JSONWriter::Write(&request_dict, &post_body); 468 469 MakeWalletRequest(GetGetWalletItemsUrl(user_index_), 470 post_body, 471 kJsonMimeType, 472 GET_WALLET_ITEMS); 473 } 474 475 bool WalletClient::HasRequestInProgress() const { 476 return request_; 477 } 478 479 void WalletClient::CancelRequest() { 480 request_.reset(); 481 request_type_ = NO_REQUEST; 482 } 483 484 void WalletClient::SetUserIndex(size_t user_index) { 485 CancelRequest(); 486 user_index_ = user_index; 487 } 488 489 void WalletClient::DoAcceptLegalDocuments( 490 const std::vector<std::string>& document_ids, 491 const std::string& google_transaction_id) { 492 base::DictionaryValue request_dict; 493 request_dict.SetString(kApiKeyKey, google_apis::GetAPIKey()); 494 request_dict.SetString(kGoogleTransactionIdKey, google_transaction_id); 495 request_dict.SetString(kMerchantDomainKey, 496 source_url_.GetWithEmptyPath().spec()); 497 scoped_ptr<base::ListValue> docs_list(new base::ListValue()); 498 for (std::vector<std::string>::const_iterator it = document_ids.begin(); 499 it != document_ids.end(); ++it) { 500 if (!it->empty()) 501 docs_list->AppendString(*it); 502 } 503 request_dict.Set(kAcceptedLegalDocumentKey, docs_list.release()); 504 505 std::string post_body; 506 base::JSONWriter::Write(&request_dict, &post_body); 507 508 MakeWalletRequest(GetAcceptLegalDocumentsUrl(user_index_), 509 post_body, 510 kJsonMimeType, 511 ACCEPT_LEGAL_DOCUMENTS); 512 } 513 514 void WalletClient::MakeWalletRequest(const GURL& url, 515 const std::string& post_body, 516 const std::string& mime_type, 517 RequestType request_type) { 518 DCHECK_EQ(request_type_, NO_REQUEST); 519 request_type_ = request_type; 520 521 request_.reset(net::URLFetcher::Create( 522 0, url, net::URLFetcher::POST, this)); 523 request_->SetRequestContext(context_getter_.get()); 524 DVLOG(1) << "Making request to " << url << " with post_body=" << post_body; 525 request_->SetUploadData(mime_type, post_body); 526 request_->AddExtraRequestHeader("Authorization: GoogleLogin auth=" + 527 delegate_->GetWalletCookieValue()); 528 DVLOG(1) << "Setting authorization header value to " 529 << delegate_->GetWalletCookieValue(); 530 request_started_timestamp_ = base::Time::Now(); 531 request_->Start(); 532 533 delegate_->GetMetricLogger().LogWalletErrorMetric( 534 AutofillMetrics::WALLET_ERROR_BASELINE_ISSUED_REQUEST); 535 delegate_->GetMetricLogger().LogWalletRequiredActionMetric( 536 AutofillMetrics::WALLET_REQUIRED_ACTION_BASELINE_ISSUED_REQUEST); 537 } 538 539 // TODO(ahutter): Add manual retry logic if it's necessary. 540 void WalletClient::OnURLFetchComplete( 541 const net::URLFetcher* source) { 542 delegate_->GetMetricLogger().LogWalletApiCallDuration( 543 RequestTypeToUmaMetric(request_type_), 544 base::Time::Now() - request_started_timestamp_); 545 546 DCHECK_EQ(source, request_.get()); 547 DVLOG(1) << "Got response from " << source->GetOriginalURL(); 548 549 // |request_|, which is aliased to |source|, might continue to be used in this 550 // |method, but should be freed once control leaves the method. 551 scoped_ptr<net::URLFetcher> scoped_request(request_.Pass()); 552 553 std::string data; 554 source->GetResponseAsString(&data); 555 DVLOG(1) << "Response body: " << data; 556 557 scoped_ptr<base::DictionaryValue> response_dict; 558 559 int response_code = source->GetResponseCode(); 560 delegate_->GetMetricLogger().LogWalletResponseCode(response_code); 561 562 switch (response_code) { 563 // HTTP_BAD_REQUEST means the arguments are invalid. No point retrying. 564 case net::HTTP_BAD_REQUEST: { 565 request_type_ = NO_REQUEST; 566 HandleWalletError(BAD_REQUEST); 567 return; 568 } 569 // HTTP_OK holds a valid response and HTTP_INTERNAL_SERVER_ERROR holds an 570 // error code and message for the user. 571 case net::HTTP_OK: 572 case net::HTTP_INTERNAL_SERVER_ERROR: { 573 scoped_ptr<base::Value> message_value(base::JSONReader::Read(data)); 574 if (message_value.get() && 575 message_value->IsType(base::Value::TYPE_DICTIONARY)) { 576 response_dict.reset( 577 static_cast<base::DictionaryValue*>(message_value.release())); 578 } 579 if (response_code == net::HTTP_INTERNAL_SERVER_ERROR) { 580 request_type_ = NO_REQUEST; 581 582 std::string error_type_string; 583 if (!response_dict->GetString(kErrorTypeKey, &error_type_string)) { 584 HandleWalletError(UNKNOWN_ERROR); 585 return; 586 } 587 WalletClient::ErrorType error_type = 588 StringToErrorType(error_type_string); 589 if (error_type == BUYER_ACCOUNT_ERROR) { 590 // If the error_type is |BUYER_ACCOUNT_ERROR|, then 591 // message_type_for_buyer field contains more specific information 592 // about the error. 593 std::string message_type_for_buyer_string; 594 if (response_dict->GetString(kMessageTypeForBuyerKey, 595 &message_type_for_buyer_string)) { 596 error_type = BuyerErrorStringToErrorType( 597 message_type_for_buyer_string); 598 } 599 } 600 601 HandleWalletError(error_type); 602 return; 603 } 604 break; 605 } 606 607 // Anything else is an error. 608 default: 609 request_type_ = NO_REQUEST; 610 HandleWalletError(NETWORK_ERROR); 611 return; 612 } 613 614 RequestType type = request_type_; 615 request_type_ = NO_REQUEST; 616 617 if (type != ACCEPT_LEGAL_DOCUMENTS && !response_dict) { 618 HandleMalformedResponse(type, scoped_request.get()); 619 return; 620 } 621 622 switch (type) { 623 case ACCEPT_LEGAL_DOCUMENTS: 624 delegate_->OnDidAcceptLegalDocuments(); 625 break; 626 627 case AUTHENTICATE_INSTRUMENT: { 628 std::string auth_result; 629 if (response_dict->GetString(kAuthResultKey, &auth_result)) { 630 std::string trimmed; 631 base::TrimWhitespaceASCII(auth_result, base::TRIM_ALL, &trimmed); 632 delegate_->OnDidAuthenticateInstrument( 633 LowerCaseEqualsASCII(trimmed, "success")); 634 } else { 635 HandleMalformedResponse(type, scoped_request.get()); 636 } 637 break; 638 } 639 640 case GET_FULL_WALLET: { 641 scoped_ptr<FullWallet> full_wallet( 642 FullWallet::CreateFullWallet(*response_dict)); 643 if (full_wallet) { 644 full_wallet->set_one_time_pad(one_time_pad_); 645 LogRequiredActions(full_wallet->required_actions()); 646 delegate_->OnDidGetFullWallet(full_wallet.Pass()); 647 } else { 648 HandleMalformedResponse(type, scoped_request.get()); 649 } 650 break; 651 } 652 653 case GET_WALLET_ITEMS: { 654 scoped_ptr<WalletItems> wallet_items( 655 WalletItems::CreateWalletItems(*response_dict)); 656 if (wallet_items) { 657 LogRequiredActions(wallet_items->required_actions()); 658 delegate_->OnDidGetWalletItems(wallet_items.Pass()); 659 } else { 660 HandleMalformedResponse(type, scoped_request.get()); 661 } 662 break; 663 } 664 665 case SAVE_TO_WALLET: { 666 std::string instrument_id; 667 response_dict->GetString(kInstrumentIdKey, &instrument_id); 668 std::string shipping_address_id; 669 response_dict->GetString(kShippingAddressIdKey, 670 &shipping_address_id); 671 std::vector<RequiredAction> required_actions; 672 GetRequiredActionsForSaveToWallet(*response_dict, &required_actions); 673 std::vector<FormFieldError> form_errors; 674 GetFormFieldErrors(*response_dict, &form_errors); 675 if (instrument_id.empty() && shipping_address_id.empty() && 676 required_actions.empty()) { 677 HandleMalformedResponse(type, scoped_request.get()); 678 } else { 679 LogRequiredActions(required_actions); 680 delegate_->OnDidSaveToWallet(instrument_id, 681 shipping_address_id, 682 required_actions, 683 form_errors); 684 } 685 break; 686 } 687 688 case NO_REQUEST: 689 NOTREACHED(); 690 } 691 } 692 693 void WalletClient::HandleMalformedResponse(RequestType request_type, 694 net::URLFetcher* request) { 695 // Called to inform exponential backoff logic of the error. 696 request->ReceivedContentWasMalformed(); 697 // Record failed API call in metrics. 698 delegate_->GetMetricLogger().LogWalletMalformedResponseMetric( 699 RequestTypeToUmaMetric(request_type)); 700 HandleWalletError(MALFORMED_RESPONSE); 701 } 702 703 void WalletClient::HandleWalletError(WalletClient::ErrorType error_type) { 704 std::string error_message; 705 switch (error_type) { 706 case WalletClient::BAD_REQUEST: 707 error_message = "WALLET_BAD_REQUEST"; 708 break; 709 case WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED: 710 error_message = "WALLET_BUYER_LEGAL_ADDRESS_NOT_SUPPORTED"; 711 break; 712 case WalletClient::BUYER_ACCOUNT_ERROR: 713 error_message = "WALLET_BUYER_ACCOUNT_ERROR"; 714 break; 715 case WalletClient::INTERNAL_ERROR: 716 error_message = "WALLET_INTERNAL_ERROR"; 717 break; 718 case WalletClient::INVALID_PARAMS: 719 error_message = "WALLET_INVALID_PARAMS"; 720 break; 721 case WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS: 722 error_message = "WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS"; 723 break; 724 case WalletClient::SERVICE_UNAVAILABLE: 725 error_message = "WALLET_SERVICE_UNAVAILABLE"; 726 break; 727 case WalletClient::UNSUPPORTED_API_VERSION: 728 error_message = "WALLET_UNSUPPORTED_API_VERSION"; 729 break; 730 case WalletClient::UNSUPPORTED_MERCHANT: 731 error_message = "WALLET_UNSUPPORTED_MERCHANT"; 732 break; 733 case WalletClient::MALFORMED_RESPONSE: 734 error_message = "WALLET_MALFORMED_RESPONSE"; 735 break; 736 case WalletClient::NETWORK_ERROR: 737 error_message = "WALLET_NETWORK_ERROR"; 738 break; 739 case WalletClient::UNKNOWN_ERROR: 740 error_message = "WALLET_UNKNOWN_ERROR"; 741 break; 742 case WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY: 743 error_message = "WALLET_UNSUPPORTED_USER_AGENT_OR_API_KEY"; 744 break; 745 } 746 747 DVLOG(1) << "Wallet encountered a " << error_message; 748 749 delegate_->OnWalletError(error_type); 750 delegate_->GetMetricLogger().LogWalletErrorMetric( 751 ErrorTypeToUmaMetric(error_type)); 752 } 753 754 // Logs an UMA metric for each of the |required_actions|. 755 void WalletClient::LogRequiredActions( 756 const std::vector<RequiredAction>& required_actions) const { 757 for (size_t i = 0; i < required_actions.size(); ++i) { 758 delegate_->GetMetricLogger().LogWalletRequiredActionMetric( 759 RequiredActionToUmaMetric(required_actions[i])); 760 } 761 } 762 763 AutofillMetrics::WalletApiCallMetric WalletClient::RequestTypeToUmaMetric( 764 RequestType request_type) const { 765 switch (request_type) { 766 case ACCEPT_LEGAL_DOCUMENTS: 767 return AutofillMetrics::ACCEPT_LEGAL_DOCUMENTS; 768 case AUTHENTICATE_INSTRUMENT: 769 return AutofillMetrics::AUTHENTICATE_INSTRUMENT; 770 case GET_FULL_WALLET: 771 return AutofillMetrics::GET_FULL_WALLET; 772 case GET_WALLET_ITEMS: 773 return AutofillMetrics::GET_WALLET_ITEMS; 774 case SAVE_TO_WALLET: 775 return AutofillMetrics::SAVE_TO_WALLET; 776 case NO_REQUEST: 777 NOTREACHED(); 778 return AutofillMetrics::UNKNOWN_API_CALL; 779 } 780 781 NOTREACHED(); 782 return AutofillMetrics::UNKNOWN_API_CALL; 783 } 784 785 } // namespace wallet 786 } // namespace autofill 787