WooCommerce PayPal Powered by Braintree Payment Gateway - Version 2.0.0

Version Description

  • Feature - Now supports non-USA Braintree merchant accounts! Bonjour, hola, hallo, and g'day :)
  • Feature - Supports WooCommerce Pre-Orders plugin
  • Feature - Credit cards and PayPal gateways can be enabled individually
  • Feature - Customers can opt to save cards or link a PayPal account at checkout for future use, or use saved methods during checkout
  • Feature - Customers can manage or add new payment methods from the account area
  • Feature - Uses an enhanced payment form with retina icons
  • Feature - Add multiple merchant IDs to support multi-currency shops (requires a currency switcher)
  • Feature - Supports Advanced Fraud tools and Kount Direct
  • Feature - Supports 3D Secure for Visa / MasterCard transactions
  • Feature - Add dynamic descriptors to be displayed for the transaction on customer's credit card statements
  • Feature - Can show detailed decline messages at checkout to better inform customers of transaction decline reasons
  • Feature - Allows bulk action to capture charges
  • Feature - Orders with only virtual items can now force a charge instead of authorization
  • Tweak - Capturing a charge now moves order status to "processing" automatically
  • Tweak - Voided orders are now marked as "cancelled" instead of "refunded"
  • Tweak - Admins can now manually update Subscription payment methods and view payment tokens
  • Fix - Subscription orders will no longer force a charge and allow an authorization depending on settings
  • Fix - Handle Subscriptions renewal failures by failing the order
  • Fix - Customers can switch Subscriptions payment methods on their own from the account
  • Fix - Stores sandbox and live customer tokens separately to avoid Customer ID is invalid. messages
  • Fix - Ensures that payment can be made from the "My Account" page for pending orders
  • Misc - Adds support for WooCommerce 3.0+
  • Misc - Removes support for WooCommerce 2.4 and lower
  • Misc - Added upgrade routine from SkyVerge Braintree plugin to allow for migrating existing tokens and subscriptions
  • Misc - Refactor for improved performance and stability
  • Misc - Other small fixes and improvements
Download this release

Release Info

Developer royho
Plugin Icon 128x128 WooCommerce PayPal Powered by Braintree Payment Gateway
Version 2.0.0
Comparing to
See all releases

Code changes from version 1.2.7 to 2.0.0

Files changed (145) hide show
  1. DEVELOPER.md +0 -62
  2. assets/css/admin.css +0 -13
  3. assets/css/cart.css +0 -14
  4. assets/css/checkout.css +0 -42
  5. assets/css/frontend/wc-braintree.min.css +151 -0
  6. assets/images/branding/paypal-braintree-horizontal.png +0 -0
  7. assets/images/branding/paypal-braintree-horizontal@2x.png +0 -0
  8. assets/images/branding/paypal-braintree-horizontal@3x.png +0 -0
  9. assets/images/branding/paypal-braintree-vertical.png +0 -0
  10. assets/images/branding/paypal-braintree-vertical@2x.png +0 -0
  11. assets/images/branding/paypal-braintree-vertical@3x.png +0 -0
  12. assets/images/icon.png +0 -0
  13. assets/images/payments/PP_logo_h_100x26.png +0 -0
  14. assets/images/payments/american-express.png +0 -0
  15. assets/images/payments/american-express@2x.png +0 -0
  16. assets/images/payments/american-express@3x.png +0 -0
  17. assets/images/payments/discover.png +0 -0
  18. assets/images/payments/discover@2x.png +0 -0
  19. assets/images/payments/discover@3x.png +0 -0
  20. assets/images/payments/master-card.png +0 -0
  21. assets/images/payments/master-card@2x.png +0 -0
  22. assets/images/payments/master-card@3x.png +0 -0
  23. assets/images/payments/payment-method-cards.png +0 -0
  24. assets/images/payments/paypal.png +0 -0
  25. assets/images/payments/paypal@2x.png +0 -0
  26. assets/images/payments/paypal@3x.png +0 -0
  27. assets/images/payments/visa.png +0 -0
  28. assets/images/payments/visa@2x.png +0 -0
  29. assets/images/payments/visa@3x.png +0 -0
  30. assets/js/cart.js +0 -105
  31. assets/js/checkout.js +0 -243
  32. assets/js/frontend/wc-braintree.min.js +1 -0
  33. braintree_sdk/.gitignore +0 -6
  34. braintree_sdk/CHANGELOG.md +0 -400
  35. braintree_sdk/LICENSE +0 -22
  36. braintree_sdk/README.md +0 -74
  37. braintree_sdk/Rakefile +0 -81
  38. braintree_sdk/ci.sh +0 -11
  39. braintree_sdk/composer.json +0 -36
  40. braintree_sdk/phpunit.xml.dist +0 -24
  41. braintree_sdk/tests/Braintree/CreditCardDefaults.php +0 -8
  42. braintree_sdk/tests/Braintree/CreditCardNumbers/CardTypeIndicators.php +0 -15
  43. braintree_sdk/tests/Braintree/OAuthTestHelper.php +0 -35
  44. braintree_sdk/tests/Helper.php +0 -136
  45. braintree_sdk/tests/SanityTest.php +0 -20
  46. braintree_sdk/tests/Setup.php +0 -32
  47. braintree_sdk/tests/integration/AddOnsTest.php +0 -88
  48. braintree_sdk/tests/integration/AddressTest.php +0 -303
  49. braintree_sdk/tests/integration/ClientTokenTest.php +0 -188
  50. braintree_sdk/tests/integration/CreditCardTest.php +0 -1319
  51. braintree_sdk/tests/integration/CreditCardVerificationAdvancedSearchTest.php +0 -259
  52. braintree_sdk/tests/integration/CreditCardVerificationTest.php +0 -56
  53. braintree_sdk/tests/integration/CustomerAdvancedSearchTest.php +0 -199
  54. braintree_sdk/tests/integration/CustomerTest.php +0 -1259
  55. braintree_sdk/tests/integration/DisbursementTest.php +0 -39
  56. braintree_sdk/tests/integration/DiscountTest.php +0 -88
  57. braintree_sdk/tests/integration/Error/ErrorCollectionTest.php +0 -80
  58. braintree_sdk/tests/integration/Error/ValidationErrorCollectionTest.php +0 -75
  59. braintree_sdk/tests/integration/EuropeBankAccountTest.php +0 -54
  60. braintree_sdk/tests/integration/HttpClientApi.php +0 -116
  61. braintree_sdk/tests/integration/HttpTest.php +0 -67
  62. braintree_sdk/tests/integration/MerchantAccountTest.php +0 -431
  63. braintree_sdk/tests/integration/MerchantTest.php +0 -62
  64. braintree_sdk/tests/integration/MultipleValueNodeTest.php +0 -94
  65. braintree_sdk/tests/integration/OAuthTest.php +0 -298
  66. braintree_sdk/tests/integration/PayPalAccountTest.php +0 -309
  67. braintree_sdk/tests/integration/PaymentMethodNonceTest.php +0 -70
  68. braintree_sdk/tests/integration/PaymentMethodTest.php +0 -1496
  69. braintree_sdk/tests/integration/PlanTest.php +0 -132
  70. braintree_sdk/tests/integration/Result/ErrorTest.php +0 -33
  71. braintree_sdk/tests/integration/SettlementBatchSummaryTest.php +0 -95
  72. braintree_sdk/tests/integration/SubscriptionHelper.php +0 -86
  73. braintree_sdk/tests/integration/SubscriptionSearchTest.php +0 -343
  74. braintree_sdk/tests/integration/SubscriptionTest.php +0 -1202
  75. braintree_sdk/tests/integration/TestTransactionTest.php +0 -101
  76. braintree_sdk/tests/integration/TextNodeTest.php +0 -147
  77. braintree_sdk/tests/integration/TransactionAdvancedSearchTest.php +0 -1573
  78. braintree_sdk/tests/integration/TransactionTest.php +0 -3629
  79. braintree_sdk/tests/integration/TransparentRedirectTest.php +0 -354
  80. braintree_sdk/tests/unit/AddOnTest.php +0 -34
  81. braintree_sdk/tests/unit/AddressTest.php +0 -79
  82. braintree_sdk/tests/unit/BraintreeTest.php +0 -25
  83. braintree_sdk/tests/unit/ClientApi/ClientTokenTest.php +0 -22
  84. braintree_sdk/tests/unit/ConfigurationTest.php +0 -417
  85. braintree_sdk/tests/unit/CreditCardTest.php +0 -141
  86. braintree_sdk/tests/unit/CreditCardVerificationTest.php +0 -22
  87. braintree_sdk/tests/unit/CustomerTest.php +0 -59
  88. braintree_sdk/tests/unit/DigestTest.php +0 -97
  89. braintree_sdk/tests/unit/DisbursementDetailsTest.php +0 -29
  90. braintree_sdk/tests/unit/DisbursementTest.php +0 -35
  91. braintree_sdk/tests/unit/DiscountTest.php +0 -34
  92. braintree_sdk/tests/unit/GatewayTest.php +0 -51
  93. braintree_sdk/tests/unit/InstanceTest.php +0 -37
  94. braintree_sdk/tests/unit/MerchantAccountTest.php +0 -68
  95. braintree_sdk/tests/unit/MultipleValueNodeTest.php +0 -24
  96. braintree_sdk/tests/unit/MultipleValueOrTextNodeTest.php +0 -52
  97. braintree_sdk/tests/unit/OAuthTest.php +0 -71
  98. braintree_sdk/tests/unit/PayPalAccountTest.php +0 -44
  99. braintree_sdk/tests/unit/PaymentMethodTest.php +0 -60
  100. braintree_sdk/tests/unit/RangeNodeTest.php +0 -38
  101. braintree_sdk/tests/unit/ResourceCollectionTest.php +0 -88
  102. braintree_sdk/tests/unit/Result/ErrorTest.php +0 -16
  103. braintree_sdk/tests/unit/Result/SuccessfulTest.php +0 -21
  104. braintree_sdk/tests/unit/SanityTest.php +0 -19
  105. braintree_sdk/tests/unit/SubscriptionSearchTest.php +0 -64
  106. braintree_sdk/tests/unit/SubscriptionTest.php +0 -22
  107. braintree_sdk/tests/unit/TextNodeTest.php +0 -45
  108. braintree_sdk/tests/unit/TransactionTest.php +0 -50
  109. braintree_sdk/tests/unit/TransparentRedirectTest.php +0 -31
  110. braintree_sdk/tests/unit/UnknownPaymentMethodTest.php +0 -25
  111. braintree_sdk/tests/unit/UtilTest.php +0 -261
  112. braintree_sdk/tests/unit/WebhookNotificationTest.php +0 -457
  113. braintree_sdk/tests/unit/Xml_GeneratorTest.php +0 -110
  114. braintree_sdk/tests/unit/Xml_ParserTest.php +0 -542
  115. class-wc-braintree.php +789 -0
  116. classes/class-wc-gateway-paypal-braintree-pay-with-card-subscription.php +0 -23
  117. classes/class-wc-gateway-paypal-braintree-pay-with-card.php +0 -30
  118. classes/class-wc-gateway-paypal-braintree-pay-with-paypal-subscription.php +0 -23
  119. classes/class-wc-gateway-paypal-braintree-pay-with-paypal.php +0 -23
  120. classes/class-wc-gateway-paypal-braintree-subscription.php +0 -366
  121. classes/class-wc-gateway-paypal-braintree.php +0 -1144
  122. i18n/languages/woocommerce-gateway-paypal-powered-by-braintree.pot +531 -0
  123. includes/api/class-wc-braintree-api-response-message-helper.php +171 -0
  124. includes/api/class-wc-braintree-api.php +719 -0
  125. includes/api/requests/abstract-wc-braintree-api-request.php +268 -0
  126. includes/api/requests/abstract-wc-braintree-api-vault-request.php +99 -0
  127. includes/api/requests/class-wc-braintree-api-client-token-request.php +54 -0
  128. includes/api/requests/class-wc-braintree-api-customer-request.php +94 -0
  129. includes/api/requests/class-wc-braintree-api-payment-method-nonce-request.php +74 -0
  130. includes/api/requests/class-wc-braintree-api-payment-method-request.php +111 -0
  131. includes/api/requests/class-wc-braintree-api-transaction-request.php +369 -0
  132. includes/api/responses/abstract-wc-braintree-api-response.php +331 -0
  133. includes/api/responses/abstract-wc-braintree-api-transaction-response.php +159 -0
  134. includes/api/responses/abstract-wc-braintree-api-vault-response.php +74 -0
  135. includes/api/responses/class-wc-braintree-api-client-token-response.php +51 -0
  136. includes/api/responses/class-wc-braintree-api-credit-card-transaction-response.php +251 -0
  137. includes/api/responses/class-wc-braintree-api-customer-response.php +192 -0
  138. includes/api/responses/class-wc-braintree-api-payment-method-nonce-response.php +119 -0
  139. includes/api/responses/class-wc-braintree-api-payment-method-response.php +129 -0
  140. includes/api/responses/class-wc-braintree-api-paypal-transaction-response.php +150 -0
  141. includes/class-wc-braintree-frontend.php +163 -0
  142. includes/class-wc-braintree-payment-method-handler.php +80 -0
  143. includes/class-wc-braintree-payment-method.php +127 -0
  144. includes/class-wc-braintree-paypal-cart.php +476 -0
  145. includes/class-wc-gateway-braintree-credit-card.php +569 -0
DEVELOPER.md DELETED
@@ -1,62 +0,0 @@
1
- # DEVELOPER.md
2
-
3
- ## Test cases
4
-
5
- * Complete a purchase for a simple product using the Credit Card subflow
6
- * Complete a purchase for a simple product using the PayPal subflow
7
-
8
- * Complete a purchase for a simple subscription using the Credit Card subflow
9
- * Using WCS_DEBUG and Tools > Scheduled Actions, run woocommerce_scheduled_subscription_payment for that subscription
10
-
11
- * Complete a purchase for a simple subscription using the PayPal subflow
12
- * Using WCS_DEBUG and Tools > Scheduled Actions, run woocommerce_scheduled_subscription_payment for that subscription
13
-
14
- ## Checkout Form Logic
15
-
16
- * Since the payment methods can be refreshed as the user enters their billing and
17
- shipping information, the extension's `script.js` periodically checks the state of the
18
- form ( using `wcCheckPaypalBraintree` ) and loads ( `wcLoadPaypalBraintree` ) and
19
- unloads ( `wcUnloadPaypalBraintree` ) PayPal Braintree as necessary.
20
-
21
- ### Hosted Fields Flow
22
-
23
- * The credit card number, CVV and expiration date fields on the checkout form are emitted as
24
- simple DIVs by WC_Gateway_Paypal_Braintree::payment_fields, and then the extension's `script.js`
25
- wcLoadPaypalBraintree function calls `braintree.js` braintree.setup to take them over.
26
-
27
- * braintree.setup replaces each of those three fields with a "hosted" iframe served by
28
- braintreegateway.com - this means that the credit card number, CVV and expiration date entries
29
- cannot be seen by the merchant's site's javascript and thus supports PCI compliance.
30
-
31
- * When the user clicks the **Place Order** button on the checkout form, `braintree.js` intercepts
32
- the click and requests a nonce (basically a payment token) for the credit card data the
33
- user has entered. We detect that click as well and interrupt the form submittal that
34
- would happen. Then, when the nonce request returns from Braintree, the nonce is saved
35
- in a form hidden field ( `#paypalbraintree_nonce` ) and we submit the form.
36
-
37
- ### PayPal Button on Checkout Form (Checkout with PayPal) Flow
38
-
39
- * If the customer would rather not enter their credit card, exp and CVV values, a PayPal
40
- button is also injected into the form by `braintree.js`
41
- * When the user clicks on the **PayPal** button on the checkout form, `braintree.js` intercepts
42
- the click and displays a modal for the customer to sign in to PayPal to complete their payment. When
43
- the customer completes sign in, a nonce is saved in a form hidden field ( `#paypalbraintree_nonce` )
44
- and we submit the form.
45
- * **NOTE: The currencies supported for Checkout with PayPal are limited compared to the Hosted Fields
46
- flow. See https://developers.braintreepayments.com/guides/paypal/checkout-with-paypal/javascript/v2#currency-support **
47
-
48
- ## Debugging
49
-
50
- ### Checkout with PayPal Button Style Problems
51
-
52
- * Unlike the hosted fields, the PayPal Button can pick up styles from the theme. The extension's
53
- `styles.css` resets a few that Storefront was setting, in the context of the PayPal button, but
54
- other themes may need additional styles to be reset.
55
-
56
- ### Errors during the PayPal Button on Checkout Form Flow
57
-
58
- * If you get a 'Sorry we cannot connect to PayPal. Please try again in a few minutes. Try Again?' message
59
- after clicking on the PayPal Button and signing in, open the Network tab in the browser's Developer Tools
60
- and then click 'Try Again?' You will see a more detailed error message in the response to the GET request
61
- there.
62
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/css/admin.css DELETED
@@ -1,13 +0,0 @@
1
- .paypal-braintree-admin-header {
2
- margin-top: 30px;
3
- display: flex;
4
- flex-direction: row;
5
- }
6
-
7
- .paypal-braintree-admin-brand {
8
- flex-grow: 1;
9
- }
10
-
11
- .paypal-braintree-admin-connect-prompt {
12
- font-weight: bold;
13
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/css/cart.css DELETED
@@ -1,14 +0,0 @@
1
- /* Unfortunately, the Checkout with PayPal button can pick up styles from the theme. So we need to reset at least these and possibly more depending on the theme.*/
2
-
3
- #paypal-braintree-button-container {
4
- text-align: right;
5
- }
6
-
7
- #paypal-braintree-button-container button {
8
- box-shadow: none;
9
- background-color: transparent;
10
- }
11
-
12
- #paypal-braintree-button-container button:hover {
13
- background-color: transparent;
14
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/css/checkout.css DELETED
@@ -1,42 +0,0 @@
1
- #wc-paypal-braintree-card-number, #wc-paypal-braintree-cvv, #wc-paypal-braintree-expiration-date {
2
- height: 30px;
3
- border: 1px solid #ddd;
4
- padding-left: 10px;
5
- -webkit-transition: border-color 160ms;
6
- transition: border-color 160ms;
7
- }
8
-
9
- #wc-paypal-braintree-card-number.braintree-hosted-fields-focused,
10
- #wc-paypal-braintree-cvv.braintree-hosted-fields-focused,
11
- #wc-paypal-braintree-expiration-date.braintree-hosted-fields-focused {
12
- border-color: #aaa;
13
- }
14
-
15
- #wc-paypal-braintree-card-number.braintree-hosted-fields-invalid,
16
- #wc-paypal-braintree-cvv.braintree-hosted-fields-invalid,
17
- #wc-paypal-braintree-expiration-date.braintree-hosted-fields-invalid {
18
- border-color: tomato;
19
- }
20
-
21
- #wc-paypal-braintree-card-number.braintree-hosted-fields-valid,
22
- #wc-paypal-braintree-cvv.braintree-hosted-fields-valid,
23
- #wc-paypal-braintree-expiration-date.braintree-hosted-fields-valid {
24
- border-color: limegreen;
25
- }
26
-
27
- /* Override unwanted styles */
28
-
29
- #payment .payment_methods li.payment_method_paypalbraintree_paypal img,
30
- #payment .payment_methods li.payment_method_paypalbraintree_cards img {
31
- float: none;
32
- display: inline-block;
33
- vertical-align: bottom;
34
- }
35
-
36
- /* Cancel button styles for checkout view */
37
-
38
- .wc-gateway-paypal-braintree-cancel {
39
- display: block;
40
- text-align: center;
41
- padding: 10px;
42
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/css/frontend/wc-braintree.min.css ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ WooCommerce Braintree SCSS
3
+ Version 2.0.0
4
+
5
+ Copyright (c) 2016-2017, Automattic, Inc.
6
+ Licensed under the GNU General Public License v3.0
7
+ http://www.gnu.org/licenses/gpl-3.0.html
8
+ */
9
+ .woocommerce #wc_braintree_paypal_container button,
10
+ .woocommerce #wc_braintree_paypal_container #braintree-paypal-button {
11
+ box-shadow: none;
12
+ margin-bottom: 10px;
13
+ background: none;
14
+ border: none; }
15
+
16
+ .woocommerce #wc_braintree_paypal_container img {
17
+ float: none !important;
18
+ max-height: 100% !important; }
19
+
20
+ .woocommerce #payment div.payment_method_braintree_credit_card label.sv-wc-payment-gateway-payment-form-saved-payment-method,
21
+ .woocommerce #payment div.payment_method_braintree_credit_card label[for="wc-braintree-credit-card-use-new-payment-method"],
22
+ .woocommerce #payment div.payment_method_braintree_credit_card label[for="wc-braintree-paypal-use-new-payment-method"],
23
+ .woocommerce #payment div.payment_method_braintree_paypal label.sv-wc-payment-gateway-payment-form-saved-payment-method,
24
+ .woocommerce #payment div.payment_method_braintree_paypal label[for="wc-braintree-credit-card-use-new-payment-method"],
25
+ .woocommerce #payment div.payment_method_braintree_paypal label[for="wc-braintree-paypal-use-new-payment-method"] {
26
+ margin-left: 3px; }
27
+
28
+ .woocommerce #payment div.payment_method_braintree_credit_card iframe {
29
+ margin: 0 0 0 6px; }
30
+
31
+ .woocommerce #payment div.payment_method_braintree_credit_card div.form-row {
32
+ padding: 3px; }
33
+
34
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field {
35
+ height: 3em;
36
+ padding: 3px;
37
+ border: 1px solid #ccc;
38
+ border-radius: 3px;
39
+ transition: border-color 160ms;
40
+ -webkit-transition: border-color 160ms;
41
+ background-color: white; }
42
+
43
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number {
44
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-cc-plain.svg");
45
+ background-repeat: no-repeat;
46
+ background-position: 99%;
47
+ background-size: 50px 31px; }
48
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-visa {
49
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-visa.svg"); }
50
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-master-card {
51
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-mastercard.svg"); }
52
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-american-express {
53
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-amex.svg"); }
54
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-diners-club {
55
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-diners.svg"); }
56
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-maestro {
57
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-maestro.svg"); }
58
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-jcb {
59
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-jcb.svg"); }
60
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number.card-type-discover {
61
+ background-image: url("../../../lib/skyverge/woocommerce/payment-gateway/assets/images/card-discover.svg"); }
62
+ @media only screen and (max-width: 320px) {
63
+ .woocommerce #payment div.payment_method_braintree_credit_card .wc-braintree-hosted-field-card-number {
64
+ background-image: none; } }
65
+
66
+ .woocommerce #payment div.payment_method_braintree_credit_card .braintree-hosted-fields-focused {
67
+ box-shadow: 0 0 .1875em #3498db; }
68
+ .woocommerce #payment div.payment_method_braintree_credit_card .braintree-hosted-fields-focused.braintree-hosted-fields-valid {
69
+ box-shadow: 0 0 .1875em #69bf29; }
70
+ .woocommerce #payment div.payment_method_braintree_credit_card .braintree-hosted-fields-focused.braintree-hosted-fields-invalid {
71
+ box-shadow: 0 0 .1875em #69bf29; }
72
+
73
+ .woocommerce #payment div.payment_method_braintree_credit_card .braintree-hosted-fields-valid {
74
+ border-color: #69bf29; }
75
+
76
+ .woocommerce #payment div.payment_method_braintree_credit_card .braintree-hosted-fields-invalid {
77
+ border-color: #a00; }
78
+
79
+ #add_payment_method ul.payment_methods li {
80
+ list-style-type: none; }
81
+ #add_payment_method ul.payment_methods li label[for="payment_method_braintree_credit_card"],
82
+ #add_payment_method ul.payment_methods li label[for="payment_method_braintree_paypal"] {
83
+ line-height: 2.3em; }
84
+ #add_payment_method ul.payment_methods li input[type="radio"]#payment_method_braintree_credit_card,
85
+ #add_payment_method ul.payment_methods li input[type="radio"]#payment_method_braintree_paypal {
86
+ margin-left: 5px; }
87
+ #add_payment_method ul.payment_methods li img {
88
+ vertical-align: middle;
89
+ margin: 3px 0 0 .5em;
90
+ padding: 0;
91
+ position: relative;
92
+ box-shadow: none; }
93
+ #add_payment_method ul.payment_methods li img + img {
94
+ margin-left: 2px; }
95
+ #add_payment_method ul.payment_methods li #braintree-paypal-loggedout img {
96
+ max-height: none;
97
+ margin: 0; }
98
+
99
+ .sv-wc-payment-gateway-my-payment-methods-table-title {
100
+ clear: both;
101
+ margin: 1.5em 0; }
102
+ .sv-wc-payment-gateway-my-payment-methods-table-title h2 {
103
+ display: inline; }
104
+ .sv-wc-payment-gateway-my-payment-methods-table-title a.button {
105
+ float: right;
106
+ line-height: 1.5;
107
+ padding-left: .8em;
108
+ padding-right: .8em; }
109
+ .sv-wc-payment-gateway-my-payment-methods-table-title a.button:before {
110
+ margin-right: 5px; }
111
+
112
+ table.sv-wc-payment-gateway-my-payment-methods-table {
113
+ font-size: 0.85em; }
114
+ table.sv-wc-payment-gateway-my-payment-methods-table th, table.sv-wc-payment-gateway-my-payment-methods-table td {
115
+ vertical-align: middle; }
116
+ table.sv-wc-payment-gateway-my-payment-methods-table .button {
117
+ white-space: nowrap; }
118
+ table.sv-wc-payment-gateway-my-payment-methods-table .sv-wc-payment-gateway-payment-method-title img {
119
+ width: 40px;
120
+ height: 25px;
121
+ vertical-align: middle;
122
+ margin: 0;
123
+ display: inline !important; }
124
+ table.sv-wc-payment-gateway-my-payment-methods-table td.sv-wc-payment-gateway-payment-method-actions {
125
+ text-align: right; }
126
+ table.sv-wc-payment-gateway-my-payment-methods-table td.sv-wc-payment-gateway-payment-method-actions .button {
127
+ margin: .125em 0 .125em .25em; }
128
+ table.sv-wc-payment-gateway-my-payment-methods-table tr.sv-wc-payment-gateway-my-payment-methods-type-divider td {
129
+ font-weight: 700; }
130
+
131
+ @media screen and (min-width: 768px) {
132
+ table.sv-wc-payment-gateway-my-payment-methods-table .wc-braintree-payment-method-icon {
133
+ width: 60px;
134
+ padding: 0 0 0 0.7415em; }
135
+ table.sv-wc-payment-gateway-my-payment-methods-table th.wc-braintree-payment-method-icon span {
136
+ display: none; }
137
+ table.sv-wc-payment-gateway-my-payment-methods-table .wc-braintree-payment-method-title {
138
+ padding-left: 0; } }
139
+
140
+ @media screen and (max-width: 768px) {
141
+ table.sv-wc-payment-gateway-my-payment-methods-table td.wc-braintree-payment-method-icon img {
142
+ float: right; }
143
+ table.sv-wc-payment-gateway-my-payment-methods-table td.sv-wc-payment-gateway-payment-method-actions {
144
+ text-align: left; }
145
+ table.sv-wc-payment-gateway-my-payment-methods-table td.sv-wc-payment-gateway-payment-method-actions:before {
146
+ display: none; }
147
+ table.sv-wc-payment-gateway-my-payment-methods-table td.sv-wc-payment-gateway-payment-method-actions .button {
148
+ float: none;
149
+ margin: .125em .25em .125em 0; }
150
+ table.sv-wc-payment-gateway-my-payment-methods-table tr.sv-wc-payment-gateway-my-payment-methods-type-divider td:before {
151
+ display: none; } }
assets/images/branding/paypal-braintree-horizontal.png DELETED
Binary file
assets/images/branding/paypal-braintree-horizontal@2x.png DELETED
Binary file
assets/images/branding/paypal-braintree-horizontal@3x.png DELETED
Binary file
assets/images/branding/paypal-braintree-vertical.png DELETED
Binary file
assets/images/branding/paypal-braintree-vertical@2x.png DELETED
Binary file
assets/images/branding/paypal-braintree-vertical@3x.png DELETED
Binary file
assets/images/icon.png DELETED
Binary file
assets/images/payments/PP_logo_h_100x26.png DELETED
Binary file
assets/images/payments/american-express.png DELETED
Binary file
assets/images/payments/american-express@2x.png DELETED
Binary file
assets/images/payments/american-express@3x.png DELETED
Binary file
assets/images/payments/discover.png DELETED
Binary file
assets/images/payments/discover@2x.png DELETED
Binary file
assets/images/payments/discover@3x.png DELETED
Binary file
assets/images/payments/master-card.png DELETED
Binary file
assets/images/payments/master-card@2x.png DELETED
Binary file
assets/images/payments/master-card@3x.png DELETED
Binary file
assets/images/payments/payment-method-cards.png DELETED
Binary file
assets/images/payments/paypal.png DELETED
Binary file
assets/images/payments/paypal@2x.png DELETED
Binary file
assets/images/payments/paypal@3x.png DELETED
Binary file
assets/images/payments/visa.png DELETED
Binary file
assets/images/payments/visa@2x.png DELETED
Binary file
assets/images/payments/visa@3x.png DELETED
Binary file
assets/js/cart.js DELETED
@@ -1,105 +0,0 @@
1
- // globals jQuery, paypalBraintreeData, braintree
2
- jQuery( document ).ready( function( $ ) {
3
-
4
- var integrationRef = null,
5
- rendering = false, // state during braintree setup
6
- container = paypalBraintreeData.checkoutWithPayPalContainer; // shortcut
7
-
8
- function onPaymentMethodReceived( paymentData ) {
9
- $( 'body' ).block( {
10
- message: null,
11
- overlayCSS: {
12
- background: '#fff',
13
- opacity: 0.6
14
- }
15
- } );
16
-
17
- $.ajax( {
18
- type: 'POST',
19
- url: paypalBraintreeData.checkoutWithPayPal.detailsPostbackURL,
20
- data: paymentData,
21
- dataType: "json"
22
- } ).done( function( responseData ) {
23
- if ( 'undefined' !== typeof responseData.success && responseData.success ) {
24
- if ( 'undefined' !== typeof responseData.redirectTo ) {
25
- window.location = responseData.redirectTo;
26
- }
27
- }
28
- } );
29
- }
30
-
31
- function onReady( integration ) {
32
- integrationRef = integration;
33
- rendering = false;
34
- };
35
-
36
- function init() {
37
- if ( 'undefined' === typeof braintree ) {
38
- return;
39
- }
40
-
41
- if ( 'undefined' === typeof paypalBraintreeData || 'undefined' === typeof paypalBraintreeData.token || 'undefined' === typeof paypalBraintreeData.checkoutWithPayPal ) {
42
- return;
43
- }
44
-
45
- if ( ! paypalBraintreeData.checkoutWithPayPal ) {
46
- return;
47
- }
48
-
49
- if ( 0 === $( '#' + container ).length ) {
50
- return;
51
- }
52
-
53
- renderButton();
54
-
55
- // Currently there's no one global event that triggered when cart is
56
- // udpated, so need to register callback to two events and avoid possible
57
- // conflict with flag `rendering`.
58
- $( document.body ).on( 'updated_wc_div', onCartUpdated );
59
- $( document.body ).on( 'updated_cart_totals', onCartUpdated );
60
- }
61
-
62
- function renderButton() {
63
- var setupArgs = {
64
- paypal : {
65
- container: container,
66
- singleUse: true, // cart checkout must always be single use
67
- amount: paypalBraintreeData.checkoutWithPayPal.amount,
68
- currency: paypalBraintreeData.checkoutWithPayPal.currency
69
- },
70
- onReady: onReady,
71
- onPaymentMethodReceived: onPaymentMethodReceived
72
- };
73
-
74
- rendering = true;
75
- braintree.setup( paypalBraintreeData.token, "custom", setupArgs );
76
- }
77
-
78
- function onCartUpdated() {
79
- // A call to setup already made.
80
- if ( rendering ) {
81
- return;
82
- }
83
-
84
- if ( ! integrationRef ) {
85
- return;
86
- }
87
-
88
- // Teardown old reference.
89
- if ( integrationRef && 'function' === typeof integrationRef.teardown ) {
90
- integrationRef.teardown( function() {
91
- integrationRef = null;
92
- } );
93
- }
94
-
95
- // Update amount and currency from updated data after cart is udpated.
96
- paypalBraintreeData.checkoutWithPayPal.amount = $( '#' + container ).data( 'amount' );
97
- paypalBraintreeData.checkoutWithPayPal.currency = $( '#' + container ).data( 'currency' );
98
-
99
- // Rerender the button.
100
- renderButton();
101
- }
102
-
103
- init();
104
-
105
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/js/checkout.js DELETED
@@ -1,243 +0,0 @@
1
- jQuery( document ).ready( function( $ ) {
2
-
3
- var states = {
4
- NOTLOADED: 'NOTLOADED',
5
- LOADING: 'LOADING',
6
- LOADED: 'LOADED',
7
- UNLOADING: 'UNLOADING'
8
- };
9
-
10
- var methods = {
11
- PAYPAL: 'payment_method_paypalbraintree_paypal',
12
- CARDS: 'payment_method_paypalbraintree_cards'
13
- };
14
-
15
- var state = states.NOTLOADED;
16
- var selectedMethod = false;
17
- var loadingMethod = false;
18
- var loadedMethod = false;
19
-
20
- var integrationRef = false;
21
- var checkoutForm = false;
22
- var paymentDiv = false;
23
-
24
- function onReady( integration ) {
25
- integrationRef = integration;
26
- loadedMethod = loadingMethod;
27
- loadingMethod = false;
28
-
29
- paymentDiv.addClass( 'wc_paypalbraintree_loaded' );
30
- state = states.LOADED;
31
-
32
- checkoutForm.on( 'checkout_place_order.braintree', onCheckoutPlaceOrder );
33
- };
34
-
35
- function onPaymentMethodReceived( response ) {
36
- if ( response.nonce ) {
37
- $( '#paypalbraintree_nonce' ).val( response.nonce );
38
- checkoutForm.trigger( 'submit' );
39
- }
40
- };
41
-
42
- function onError( response ) {
43
- var message = response;
44
- if ( response && response.message ) {
45
- message = response.message;
46
- }
47
-
48
- console.log( 'WooCommerce: PayPal Powered by Braintree: an error occurred:', message );
49
- };
50
-
51
- function onCheckoutPlaceOrder() {
52
- // If neither PayPal nor Cards are selected, go ahead and let it submit (return true)
53
- if ( ! selectedMethod ) {
54
- return true;
55
- }
56
-
57
- // If we have a nonce, go ahead and let it submit (return true)
58
- var nonceEl = jQuery( "#paypalbraintree_nonce" );
59
- if ( 0 !== nonceEl.length ) {
60
- var nonceValue = nonceEl.val();
61
- if ( 0 !== nonceValue.length ) {
62
- return true;
63
- }
64
- }
65
-
66
- // No nonce yet? If we are in PayPal mode, do initAuthFlow
67
- if ( 'PAYPAL' === selectedMethod ) {
68
- if ( integrationRef && integrationRef.paypal ) {
69
- integrationRef.paypal.initAuthFlow();
70
- }
71
- }
72
-
73
- return false;
74
- }
75
-
76
- // Load the headless PayPal integration
77
-
78
- function loadPayPalMethod() {
79
- state = states.LOADING;
80
- loadingMethod = 'PAYPAL';
81
-
82
- braintree.setup( paypalBraintreeData.token, "custom", {
83
- paypal: {
84
- headless: true,
85
- paymentMethodNonceInputField: "paypalbraintree_nonce",
86
- singleUse: paypalBraintreeData.checkoutWithPayPal.singleUse,
87
- amount: paypalBraintreeData.checkoutWithPayPal.amount,
88
- currency: paypalBraintreeData.checkoutWithPayPal.currency
89
- },
90
- onReady: onReady,
91
- onError: onError,
92
- onPaymentMethodReceived: onPaymentMethodReceived
93
- } );
94
- };
95
-
96
- // Load the hosted fields integration
97
-
98
- function loadCardsMethod() {
99
- state = states.LOADING;
100
- loadingMethod = 'CARDS';
101
-
102
- var checkoutFormID = checkoutForm.attr( 'id' );
103
- if ( ! checkoutFormID ) {
104
- checkoutFormID = 'woocommerce-checkout-form';
105
- checkoutForm.attr( 'id', checkoutFormID );
106
- }
107
-
108
- braintree.setup( paypalBraintreeData.token, "custom", {
109
- id: checkoutFormID,
110
- hostedFields: paypalBraintreeData.hostedFields,
111
- onReady: onReady,
112
- onError: onError,
113
- onPaymentMethodReceived: onPaymentMethodReceived
114
- } );
115
- };
116
-
117
- // Tear down a previously loaded method
118
-
119
- function unloadMethod() {
120
- state = states.UNLOADING;
121
-
122
- // Remove submit interceptor
123
- jQuery( 'form.checkout' ).off( 'checkout_place_order.braintree' );
124
-
125
- if ( integrationRef ) {
126
- integrationRef.teardown( function() {
127
- integrationRef = null;
128
- state = states.NOTLOADED;
129
- loadedMethod = false;
130
- } );
131
- } else {
132
- state = states.NOTLOADED;
133
- loadedMethod = false;
134
- }
135
- };
136
-
137
-
138
- // Since the user may select different payment options at any time, and
139
- // since the form can completely re-render at any time, we need to periodically
140
- // check and make sure the selected method is properly loaded, as well
141
- // as manage teardown of methods when they are no longer selected or
142
- // when the form has re-rendered on us.
143
-
144
- function checkSetup() {
145
-
146
- // In the middle of loading or unloading something? Just return.
147
- if ( state === states.LOADING || state === states.UNLOADING ) {
148
-
149
- // If we're waiting for onReady to fire, return. Otherwise, reset state in
150
- // order to attempt Braintree.setup again.
151
- if ( 0 != jQuery( '#wc-paypal-braintree-cvv' ).children().length ) {
152
- return;
153
- } else {
154
- state = states.NOTLOADED;
155
- }
156
- }
157
-
158
- // Are key things missing? Just return.
159
- if ( 'undefined' === typeof braintree || 'undefined' === typeof paypalBraintreeData || 'undefined' === typeof paypalBraintreeData.token ) {
160
- return;
161
- }
162
-
163
- // No checkout form? Just return.
164
- checkoutForm = jQuery( 'form.checkout, form#order_review, form#add_payment_method' );
165
- if ( ! checkoutForm.length ) {
166
- return;
167
- }
168
-
169
- // No payment div? Just return.
170
- paymentDiv = jQuery( '#payment' );
171
- if ( ! paymentDiv.length ) {
172
- return;
173
- }
174
-
175
- // Make sure the checkout form has a nonce field,
176
- // add it if necessary
177
- if ( 0 === jQuery( "#paypalbraintree_nonce" ).length ) {
178
- checkoutForm.append( "<input type='hidden' name='paypalbraintree_nonce' id='paypalbraintree_nonce' />" );
179
- }
180
-
181
- // What payment method radiobutton is presently checked
182
- selectedMethod = false;
183
- for ( var method in methods ) {
184
- if ( 0 != $( '#' + methods[method] + ':checked' ).length ) {
185
- selectedMethod = method;
186
- }
187
- }
188
-
189
- // Useful for debugging:
190
- // console.log( 'state =', state );
191
- // console.log( 'selectedMethod =', selectedMethod );
192
- // console.log( 'loadedMethod =', loadedMethod );
193
-
194
- if ( state === states.NOTLOADED ) {
195
- if ( 'PAYPAL' === selectedMethod ) {
196
- loadPayPalMethod();
197
- return;
198
- }
199
-
200
- if ( 'CARDS' === selectedMethod ) {
201
- loadCardsMethod();
202
- return;
203
- }
204
-
205
- return;
206
- }
207
-
208
- if ( state === states.LOADED ) {
209
- // Nothing checked anymore? Start unloading
210
- if ( ! selectedMethod ) {
211
- unloadMethod();
212
- return;
213
- }
214
-
215
- // Is what's loaded not the same as what's checked? Start unloading (so we can reload).
216
- if ( selectedMethod !== loadedMethod ) {
217
- unloadMethod();
218
- return;
219
- }
220
-
221
- // Does it look like the form got re-rendered on us? Start unloading (so we can reload).
222
- if ( ! paymentDiv.hasClass( 'wc_paypalbraintree_loaded' ) ) {
223
-
224
- // Check if last field is loaded from previous Braintree setup.
225
- // onReady can take some time to fire causing Braintree to attempt setup
226
- // again after a previous successful setup. No need to unload.
227
- if ( 0 != jQuery( '#wc-paypal-braintree-cvv' ).children().length ) {
228
- state = states.LOADED;
229
- return;
230
- }
231
-
232
- unloadMethod();
233
- return;
234
- }
235
- }
236
- };
237
-
238
- setInterval( checkSetup, 250 );
239
-
240
- $( document.body ).on( 'checkout_error', function() {
241
- $( '#paypalbraintree_nonce' ).remove();
242
- });
243
- } );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
assets/js/frontend/wc-braintree.min.js ADDED
@@ -0,0 +1 @@
 
1
+ (function(){var a=function(a,c){function d(){this.constructor=a}for(var e in c)b.call(c,e)&&(a[e]=c[e]);return d.prototype=c.prototype,a.prototype=new d,a.__super__=c.prototype,a},b={}.hasOwnProperty;jQuery(document).ready(function(b){"use strict";return window.WC_Braintree_Payment_Form_Handler=function(){function a(a){this.id=a.id,this.id_dasherized=a.id_dasherized,this.type=a.type,this.debug=a.debug,this.params=window.wc_braintree_params,"undefined"!=typeof braintree&&null!==braintree&&(b("form.checkout").length?this.handle_checkout_page():b("form#order_review").length?this.handle_pay_page():b("form#add_payment_method").length&&this.handle_add_payment_method_page())}return a.prototype.handle_checkout_page=function(){return this.form=b("form.checkout"),this.form_ui_selector=".woocommerce-checkout-payment",b(document.body).on("updated_checkout",function(a){return function(){return a.setup_braintree()}}(this)),b(document.body).on("updated_checkout",function(a){return function(){return a.handle_saved_payment_methods()}}(this)),b(document.body).on("checkout_error",function(a){return function(){return a.unblock_ui(),b("input[name=wc_"+a.id+"_payment_nonce]").val("")}}(this)),this.form.on("checkout_place_order_"+this.id,function(a){return function(){return a.block_ui(),a.verify_form()}}(this))},a.prototype.handle_pay_page=function(){return this.form=b("form#order_review"),this.form_ui_selector="#payment",this.handle_saved_payment_methods(),this.setup_braintree(),this.form.submit(function(a){return function(){if(a.block_ui(),a.verify_form())return HTMLFormElement.prototype.submit.call(a.form[0])}}(this))},a.prototype.handle_add_payment_method_page=function(){return this.form=b("form#add_payment_method"),this.form_ui_selector="#payment",this.setup_braintree(),this.form.submit(function(a){return function(){return!(a.is_braintree_selected()&&!a.has_payment_nonce())&&HTMLFormElement.prototype.submit.call(a.form[0])}}(this))},a.prototype.verify_form=function(){return!this.is_braintree_selected()||(!!this.using_payment_token()||!!this.has_payment_nonce()&&void 0)},a.prototype.submit_form=function(a){return b("input[name=wc_"+this.id+"_payment_nonce]").val(a),this.form.submit()},a.prototype.handle_saved_payment_methods=function(){var a;return a=b("div.js-wc-"+this.id_dasherized+"-new-payment-method-form"),b("input.js-wc-"+this.id_dasherized+"-payment-token").change(function(c){return function(){var d;return d=b("input.js-wc-"+c.id_dasherized+"-payment-token:checked").val(),d?a.slideUp(200):a.slideDown(200)}}(this)).change(),b("input#createaccount").change(function(a){return function(c){var d;return d=b("input.js-wc-"+a.id_dasherized+"-tokenize-payment-method").closest("p.form-row"),b(c.target).is(":checked")?(d.slideDown(),d.next().show()):(d.hide(),d.next().hide())}}(this)).change()},a.prototype.setup_braintree=function(){},a.prototype.refresh_braintree=function(){if(null!=this.integration)return this.block_ui(),this.integration.teardown(function(a){return function(){return a.integration=null,a.setup_braintree()}}(this))},a.prototype.teardown_braintree=function(){if(null!=this.integration)return this.block_ui(),this.integration.teardown(function(a){return function(){return a.integration=null,a.unblock_ui()}}(this))},a.prototype.on_payment_method_received=function(a){},a.prototype.on_error=function(a){if("VALIDATION"===a.type){if(!this.is_braintree_selected())return;if(this.id!==this.get_selected_gateway_id())return;this.render_error(this.get_error_message(a))}else this.log("configuration error",a.message);return this.unblock_ui()},a.prototype.get_error_message=function(a){},a.prototype.on_ready=function(a){return this.unblock_ui(),this.integration=a},a.prototype.block_ui=function(){return b(this.form_ui_selector).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},a.prototype.unblock_ui=function(){return b(this.form_ui_selector).unblock()},a.prototype.render_error=function(a){return b(".woocommerce-error, .woocommerce-message").remove(),this.form.prepend('<div class="woocommerce-error">'+a+"</div>").removeClass("processing").unblock(),b("html, body").animate({scrollTop:this.form.offset().top-100},1e3),b("input[name=wc_"+this.id+"_payment_nonce]").val(""),this.form.trigger("wc_"+this.id+"_rendered_error"),this.unblock_ui()},a.prototype.has_payment_nonce=function(){return this.form.find("input[name=wc_"+this.get_selected_gateway_id()+"_payment_nonce]").val()},a.prototype.using_payment_token=function(){return this.form.find("input.js-wc-"+this.get_selected_gateway_id_dasherized()+"-payment-token:checked").val()},a.prototype.get_selected_gateway_id=function(){return this.form.find("input[name=payment_method]:checked").val()},a.prototype.get_selected_gateway_id_dasherized=function(){return this.get_selected_gateway_id().replace(/_/g,"-")},a.prototype.is_braintree_selected=function(){var a;return"braintree_credit_card"===(a=this.form.find("input[name=payment_method]:checked").val())||"braintree_paypal"===a},a.prototype.is_credit_card_selected=function(){return"braintree_credit_card"===this.get_selected_gateway_id()},a.prototype.is_paypal_selected=function(){return"braintree_paypal"===this.get_selected_gateway_id()},a.prototype.log=function(a,b){if(this.debug)return console.log(a),console.log(b)},a}(),window.WC_Braintree_Credit_Card_Payment_Form_Handler=function(c){function d(a){this.csc_required=a.csc_required,this.hosted_fields_styles=a.hosted_fields_styles,this.threeds=a.threeds,d.__super__.constructor.call(this,a),this.is_3d_secure_enabled()&&this.setup_3d_secure()}return a(d,c),d.prototype.verify_form=function(){var a,c;return!this.is_braintree_selected()||(c=d.__super__.verify_form.call(this),!(this.csc_required&&!this.has_payment_nonce())&&(a=b("input.js-wc-braintree-credit-card-payment-token:checked"),this.should_verify_3d_secure_token(a)&&(this.verify_3d_secure(a.data("nonce"),a),c=!1),c))},d.prototype.setup_braintree=function(){var a;return this.integration?this.refresh_braintree():(this.block_ui(),a={number:{selector:"#wc-braintree-credit-card-account-number-hosted"},cvv:{selector:"#wc-braintree-credit-card-csc-hosted"},expirationDate:{selector:"#wc-braintree-credit-card-expiry-hosted"},styles:this.hosted_fields_styles,onFieldEvent:function(a){return function(b){return a.on_hosted_field_event(b)}}(this)},this.csc_required&&this.form.find("input.js-wc-"+this.id_dasherized+"-payment-token:checked").val()&&(delete a.number,delete a.expirationDate),this.csc_required||delete a.cvv,braintree.setup(this.params.client_token,"custom",{id:this.form[0],hostedFields:a,onPaymentMethodReceived:function(a){return function(b){return a.on_payment_method_received(b)}}(this),onError:function(a){return function(b){return a.on_error(b)}}(this),onReady:function(a){return function(b){return a.on_ready(b)}}(this)}))},d.prototype.on_ready=function(a){if(d.__super__.on_ready.call(this,a),!this.csc_required&&b("input.js-wc-braintree-credit-card-payment-token:checked").val())return this.teardown_braintree()},d.prototype.handle_saved_payment_methods=function(){var a,c;return d.__super__.handle_saved_payment_methods.call(this),c=b("div.js-wc-braintree-credit-card-new-payment-method-form"),a=b("div.wc-braintree-hosted-field-card-csc-parent"),b("input.js-wc-braintree-credit-card-payment-token").change(function(d){return function(){var e;return e=b("input.js-wc-braintree-credit-card-payment-token:checked").val(),e?d.csc_required&&a.hasClass("form-row-last")?(a.removeClass("form-row-last").addClass("form-row-first"),c.after(a),d.refresh_braintree()):void 0:d.csc_required&&a.hasClass("form-row-first")?(a.removeClass("form-row-first").addClass("form-row-last"),c.find("div.wc-braintree-hosted-field-card-expiry-parent").after(a),d.refresh_braintree()):d.setup_braintree()}}(this)).change()},d.prototype.get_error_message=function(a){var b,c,d,e;if(d=[],null!=a.details)for(e=a.details.invalidFieldKeys,b=0,c=e.length;b<c;b++)switch(e[b]){case"number":d.push(this.params.card_number_invalid);break;case"cvv":d.push(this.params.cvv_length_invalid);break;case"expirationDate":d.push(this.params.card_exp_date_invalid)}else switch(a.message){case"User did not enter a payment method":this.csc_required?this.using_payment_token()?d.push(this.params.cvv_missing):d.push(this.params.card_number_missing,this.params.card_exp_date_invalid,this.params.cvv_missing):d.push(this.params.card_number_missing,this.params.card_exp_date_invalid)}return d.length||d.push(a.message),d.join("<br/>")},d.prototype.on_payment_method_received=function(a){if(this.log("payment method received",a),null!=a.nonce)return this.should_verify_3d_secure(a)?this.verify_3d_secure(a.nonce):this.submit_form(a.nonce)},d.prototype.on_hosted_field_event=function(a){var c;if(c=b(".wc-braintree-hosted-field-card-number"),c.attr("class",function(a,b){return b.replace(/(^|\s)card-type-\S+/g,"")}),null!=a.card)return c.addClass("card-type-"+a.card.type)},d.prototype.is_3d_secure_enabled=function(){return this.threeds.enabled},d.prototype.setup_3d_secure=function(){return this.client=new braintree.api.Client({clientToken:this.params.client_token})},d.prototype.should_verify_3d_secure=function(a){var b;return b=a.details.cardType,this.is_3d_secure_enabled()&&"CreditCard"===a.type&&("Visa"===b||"MasterCard"===b)},d.prototype.should_verify_3d_secure_token=function(a){if(a.val()&&a.data("nonce")&&!a.data("verified"))return!0},d.prototype.verify_3d_secure=function(a,c){var d;return null==c&&(c=null),d=b("input[name=wc_braintree_credit_card_3d_secure_order_total]").val(),this.client.verify3DS({amount:d,creditCard:a},function(a){return function(d,e){return d?(a.render_error(d.message),a.log("3DS error",d)):(a.log("3DS response",e),a.threeds.liability_shift_always_required&&!e.verificationDetails.liabilityShifted&&a.render_error(a.threeds.failure_message),e.verificationDetails.liabilityShiftPossible&&!e.verificationDetails.liabilityShifted&&a.render_error(a.threeds.failure_message),null!=c&&c.data("verified",!0),b("input[name=wc_braintree_credit_card_3d_secure_verified]").val(1),a.submit_form(e.nonce))}}(this))},d}(WC_Braintree_Payment_Form_Handler),window.WC_Braintree_PayPal_Payment_Form_Handler=function(c){function d(a){this.must_login_message=a.must_login_message,this.must_login_add_method_message=a.must_login_add_method_message,d.__super__.constructor.call(this,a),b(document.body).on("click",'input[name="payment_method"], input.js-wc-braintree-paypal-payment-token',function(a){return function(){return!a.is_paypal_selected()||a.has_payment_nonce()||a.using_payment_token()?b("#place_order").show():b("#place_order").hide()}}(this))}return a(d,c),d.prototype.verify_form=function(){var a;return!this.is_braintree_selected()||(a=d.__super__.verify_form.call(this),this.has_payment_nonce()||this.render_error(this.must_login_message),a)},d.prototype.handle_add_payment_method_page=function(){return this.form=b("form#add_payment_method"),this.form_ui_selector="#payment",this.setup_braintree(),this.form.submit(function(a){return function(){return a.is_paypal_selected()&&(a.has_payment_nonce()||a.render_error(a.must_login_add_method_message)),!(a.is_braintree_selected()&&!a.has_payment_nonce())&&HTMLFormElement.prototype.submit.call(a.form[0])}}(this))},d.prototype.setup_braintree=function(){if(!this.has_payment_nonce())return this.block_ui(),braintree.setup(this.params.client_token,"paypal",{container:"wc_braintree_paypal_container",singleUse:this.is_single_use(),amount:this.get_order_amount(),currency:this.get_store_currency(),locale:this.get_store_locale(),onPaymentMethodReceived:function(a){return function(b){return a.on_payment_method_received(b)}}(this),onError:function(a){return function(b){return a.on_error(b)}}(this),onReady:function(a){return function(b){return a.on_ready(b)}}(this),onCancelled:function(a){return function(){return a.on_cancelled()}}(this),onUnsupported:function(a){return function(b){return a.on_unsupported(b)}}(this)})},d.prototype.on_cancelled=function(){if(b("input.js-wc-braintree-paypal-tokenize-payment-method").prop("disabled",!1),b("input[name=wc_braintree_paypal_payment_nonce]").val(""),this.is_paypal_selected())return b("#place_order").hide()},d.prototype.on_unsupported=function(a){return this.log("PayPal error",a),this.render_error(this.params.generic_error_message)},d.prototype.handle_saved_payment_methods=function(){return d.__super__.handle_saved_payment_methods.call(this),b("input.js-wc-braintree-paypal-tokenize-payment-method").change(function(a){return function(c){if(b(c.target).is(":visible"))return a.refresh_braintree()}}(this)).change()},d.prototype.on_payment_method_received=function(a){if(this.log("payment method received",a),null!=a.nonce)return this.is_single_use()&&b("input.js-wc-braintree-paypal-tokenize-payment-method").prop("disabled",!0),b("input[name=wc_braintree_paypal_payment_nonce]").val(a.nonce),b("#place_order").show()},d.prototype.is_single_use=function(){var a;return a=b("input[name=wc-braintree-paypal-tokenize-payment-method]"),0===a.length||("checkbox"===a.attr("type")?!a.is(":checked"):!a.val())},d.prototype.get_order_amount=function(){return b("input[name=wc_braintree_paypal_amount]").val()},d.prototype.get_store_currency=function(){return b("input[name=wc_braintree_paypal_currency]").val()},d.prototype.get_store_locale=function(){return b("input[name=wc_braintree_paypal_locale]").val()},d}(WC_Braintree_Payment_Form_Handler),window.WC_Braintree_PayPal_Cart_Handler=function(c){function d(a){d.__super__.constructor.call(this,a),this.form_ui_selector=".cart_totals",this.setup_braintree(),b(document.body).on("updated_cart_totals",function(a){return function(){return a.setup_braintree()}}(this))}return a(d,c),d.prototype.on_payment_method_received=function(a){if(this.log("payment method received",a),null!=a.nonce)return a.wp_nonce=this.params.cart_nonce,b.ajax({type:"POST",url:this.params.cart_handler_url,data:a,dataType:"json"}).done(function(a){return window.location=a.redirect_url})},d.prototype.is_single_use=function(){return"1"===b("input[name=wc_braintree_paypal_single_use]").val()},d.prototype.has_payment_nonce=function(){return!1},d}(WC_Braintree_PayPal_Payment_Form_Handler)})}).call(this);
braintree_sdk/.gitignore DELETED
@@ -1,6 +0,0 @@
1
- /vendor
2
- /docs
3
- /tags
4
- composer.lock
5
- composer.phar
6
- *.tgz
 
 
 
 
 
 
braintree_sdk/CHANGELOG.md DELETED
@@ -1,400 +0,0 @@
1
- ## 3.8.0
2
- * Add payment method revoke
3
- * Add support for options in `submit_for_settlement` transaction flows
4
- * Add verification create API
5
- * Update https certificate bundle
6
-
7
- ## 3.7.0
8
- * Add VenmoAccount
9
- * Allow order_id and descriptor to be passed in for Transaction submit_for_settlement
10
- * Add facilitator details onto transactions
11
- * Add check webhook constant
12
-
13
- ## 3.6.1
14
- * Fix PSR-0 style namespacing when using Symfony
15
-
16
- ## 3.6.0
17
- * Add support for proxy servers
18
- * Add PSR-4 namespacing support
19
- * Add support for AMEX Express Checkout
20
- * Add support for new fields in dispute webhooks (`dateWon`, `dateOpened`, `kind`)
21
- * Add transaction data to sucessful subscription webhook
22
-
23
- ## 3.5.0
24
- * Add support for raw ApplePay params on Transaction create
25
-
26
- ## 3.4.0
27
- * Add sourceDescription method to Android Pay and Apple Pay payment methods
28
- * Add new Android Pay test nonces
29
- * Add billing agreement ID to PayPal Account
30
- * Support amex rewards transactions
31
-
32
- ## 3.3.0
33
- * Add new test payment method nonces
34
- * Allow passing description on PayPal transactions
35
- * Add methods to change transaction settlement status in sandbox
36
- * Fix issue where customer with an id of 0 could not be found
37
- * Add Europe Bank Account functionality
38
-
39
- ## 3.2.0
40
- * Add additional search criteria
41
-
42
- ## 3.1.0
43
- * Add support for HHVM
44
- * Validate that configuration is valid before verifying webhooks
45
- * Make OAuth methods conform more to existing API
46
- * Expose customer paymentMethods as an attribute
47
-
48
- ## 3.0.1
49
- * Add support for Android Pay
50
-
51
- ## 3.0.0
52
- * Deprecate PHP 5.2 and 5.3
53
- * Validate webhook challenge payload
54
- * Bugfix for calling `__toString()` on objects that contain a `\DateTime`
55
-
56
- ## 2.40.0
57
- * Add missing criteria to credit card verification search
58
- * Bugfix for autoloading files with Composer
59
-
60
- ## 2.39.0
61
- * Add oauth functionality
62
- * Add 3DS info to the server side
63
-
64
- ## 2.38.0
65
- * Update payment instrument types and test nonces
66
- * Add missing valid params to PaymentMethodGateway
67
-
68
- ## 2.37.0
69
- * Add 3D Secure transaction fields
70
- * Add ability to create nonce from vaulted payment methods
71
-
72
- ## 2.36.0
73
- * Surface Apple Pay payment instrument name in responses
74
- * Support Coinbase payment instruments
75
-
76
- ## 2.35.2
77
- * Fix E_STRICT errors
78
- * Expose subscription status details
79
-
80
- ## 2.35.1
81
- * Bugfix for auto loading files
82
-
83
- ## 2.35.0
84
- * Allow PayPal fields in transaction.options.paypal
85
- * Add error code constants
86
- * Internal refactoring
87
-
88
- ## 2.34.0
89
- * Add risk_data to Transaction and Verification with Kount decision and id
90
- * Add verification_amount an option when creating a credit card
91
- * Add TravelCruise industry type to Transaction
92
- * Add room_rate to Lodging industry type
93
- * Add CreditCard#verification as the latest verification on that credit card
94
- * Add ApplePay support to all endpoints that may return ApplePayCard objects
95
- * Add prefix to sample Webhook to simulate webhook query params
96
-
97
- ## 2.33.0
98
- * Allow descriptor to be passed in Funding Details options params for Merchant Account create and update.
99
-
100
- ## 2.32.0
101
- * Add additionalProcessorResponse to Transaction
102
-
103
- ## 2.31.1
104
- * Allow payee_email to be passed in options params for Transaction create
105
-
106
- ## 2.31.0
107
- * Added paypal specific fields to transaction calls
108
- * Added SettlementPending, SettlementDeclined transaction statuses
109
-
110
- ## 2.30.0
111
- * Add descriptor url support
112
-
113
- ## 2.29.0
114
- * Allow credit card verification options to be passed outside of the nonce for PaymentMethod.create
115
- * Allow billing_address parameters and billing_address_id to be passed outside of the nonce for PaymentMethod.create
116
- * Add Subscriptions to paypal accounts
117
- * Add PaymentMethod.update
118
- * Add fail_on_duplicate_payment_method option to PaymentMethod.create
119
-
120
- ## 2.28.0
121
- * Adds support for v.zero SDKs.
122
-
123
- ## 2.27.2
124
-
125
- * Make webhook parsing more robust with newlines
126
- * Add messages to InvalidSignature exceptions
127
-
128
- ## 2.27.1
129
-
130
- * Updated secureCompare to correctly compare strings in consistent time
131
- * Add better error messages around webhook verification
132
-
133
- ## 2.27.0
134
-
135
- * Include Dispute information on Transaction
136
- * Search for Transactions disputed on a certain date
137
-
138
- ## 2.26.0
139
-
140
- * Disbursement Webhooks
141
-
142
- ## 2.25.1
143
-
144
- * Fix factories on AddOn and Discount (thanks [stewe](https://github.com/stewe))
145
- * Allow billingAddressId on transaction create
146
-
147
- ## 2.25.0
148
-
149
- * Merchant account find API
150
-
151
- ## 2.24.0
152
-
153
- * Merchant account update API
154
- * Merchant account create API v2
155
-
156
- ## 2.23.1
157
-
158
- * Update configuration URLs
159
-
160
- ## 2.23.0
161
-
162
- * Official Partnership support
163
-
164
- ## 2.22.2
165
-
166
- * Add Partner Merchant Declined webhook
167
- * use preg_callback_replace instead of preg_replace (thanks [jonthornton](https://github.com/jonthornton)!)
168
-
169
- ## 2.22.1
170
-
171
- * Adds missing test contstant to library namespace
172
-
173
- ## 2.22.0
174
-
175
- * Adds holdInEscrow method
176
- * Add error codes for verification not supported error
177
- * Add companyName and taxId to merchant account create
178
- * Adds cancelRelease method
179
- * Adds releaseFromEscrow functionality
180
- * Adds phone to merchant account signature.
181
- * Adds merchant account phone error code.
182
- * Fix casing issues with Braintree\_Http and Braintree\_Util references (thanks [steven-hadfield](https://github.com/steven-hadfield)!)
183
- * Fixed transaction initialization arguments to be optional (thanks [karolsojko](https://github.com/karolsojko)!)
184
-
185
- ## 2.21.0
186
-
187
- * Enable device data.
188
-
189
- ## 2.20.0
190
-
191
- * Fixed getting custom fields with valueForHtmlField. [Thanks to Miguel Manso for the fix.](https://github.com/mumia)
192
- * Adds disbursement details to transactions.
193
- * Adds image url to transactions.
194
-
195
- ## 2.19.0
196
-
197
- * Adds channel field to transactions.
198
-
199
- ## 2.18.0
200
-
201
- * Adds country of issuance and issuing bank bin database fields
202
-
203
- ## 2.17.0
204
-
205
- * Adds verification search
206
-
207
- ## 2.16.0
208
-
209
- * Additional card information, such as prepaid, debit, commercial, Durbin regulated, healthcare, and payroll, are returned on credit card responses
210
- * Allows transactions to be specified as recurring
211
-
212
- ## 2.15.0
213
-
214
- * Adds prepaid field to credit cards (possible values include Yes, No, Unknown)
215
-
216
- ## 2.14.1
217
-
218
- * Adds composer support (thanks [till](https://github.com/till))
219
- * Fixes erroneous version number
220
- * Braintree_Plan::all() returns empty array if no plans exist
221
-
222
- ## 2.14.0
223
-
224
- * Adds webhook gateways for parsing, verifying, and testing notifications
225
-
226
- ## 2.13.0
227
-
228
- * Adds search for duplicate credit cards given a payment method token
229
- * Adds flag to fail saving credit card to vault if card is duplicate
230
-
231
- ## 2.12.5
232
-
233
- * Exposes plan_id on transactions
234
-
235
- ## 2.12.4
236
-
237
- * Added error code for invalid purchase order number
238
-
239
- ## 2.12.3
240
-
241
- * Fixed problematic case in ResourceCollection when no results are returned from a search.
242
-
243
- ## 2.12.2
244
-
245
- * Fixed customer search, which returned customers when no customers matched search criteria
246
-
247
- ## 2.12.1
248
-
249
- * Added new error message for merchant accounts that do not support refunds
250
-
251
- ## 2.12.0
252
-
253
- * Added ability to retrieve all Plans, AddOns, and Discounts
254
- * Added Transaction cloning
255
-
256
- ## 2.11.0
257
-
258
- * Added Braintree_SettlementBatchSummary
259
-
260
- ## 2.10.1
261
-
262
- * Wrap dependency requirement in a function, to prevent pollution of the global namespace
263
-
264
- ## 2.10.0
265
-
266
- * Added subscriptionDetails to Transaction
267
- * Added flag to store in vault only when a transaction is successful
268
- * Added new error code
269
-
270
- ## 2.9.0
271
-
272
- * Added a new transaction state, AUTHORIZATION_EXPIRED.
273
- * Enabled searching by authorizationExpiredAt.
274
-
275
- ## 2.8.0
276
-
277
- * Added next_billing_date and transaction_id to subscription search
278
- * Added address_country_name to customer search
279
- * Added new error codes
280
-
281
- ## 2.7.0
282
-
283
- * Added Customer search
284
- * Added dynamic descriptors to Subscriptions and Transactions
285
- * Added level 2 fields to Transactions:
286
- * tax_amount
287
- * tax_exempt
288
- * purchase_order_number
289
-
290
- ## 2.6.1
291
-
292
- * Added billingAddressId to allowed parameters for credit cards create and update
293
- * Allow searching on subscriptions that are currently in a trial period using inTrialPeriod
294
-
295
- ## 2.6.0
296
-
297
- * Added ability to perform multiple partial refunds on Braintree_Transactions
298
- * Allow passing expirationMonth and expirationYear separately when creating Braintree_Transactions
299
- * Added revertSubscriptionOnProrationFailure flag to Braintree_Subscription update that specifies how a Subscription should react to a failed proration charge
300
- * Deprecated Braintree_Subscription nextBillAmount in favor of nextBillingPeriodAmount
301
- * Deprecated Braintree_Transaction refundId in favor of refundIds
302
- * Added new fields to Braintree_Subscription:
303
- * balance
304
- * paidThroughDate
305
- * nextBillingPeriodAmount
306
-
307
- ## 2.5.0
308
-
309
- * Added Braintree_AddOns/Braintree_Discounts
310
- * Enhanced Braintree_Subscription search
311
- * Enhanced Braintree_Transaction search
312
- * Added constants for Braintree_Result_CreditCardVerification statuses
313
- * Added EXPIRED and PENDING statuses to Braintree_Subscription
314
- * Allowed prorateCharges to be specified on Braintree_Subscription update
315
- * Added Braintree_AddOn/Braintree_Discount details to Braintree_Transactions that were created from a Braintree_Subscription
316
- * Removed 13 digit Visa Sandbox Credit Card number and replaced it with a 16 digit Visa
317
- * Added new fields to Braintree_Subscription:
318
- * billingDayOfMonth
319
- * daysPastDue
320
- * firstBillingDate
321
- * neverExpires
322
- * numberOfBillingCycles
323
-
324
- ## 2.4.0
325
-
326
- * Added ability to specify country using countryName, countryCodeAlpha2, countryCodeAlpha3, or countryCodeNumeric (see [ISO_3166-1](http://en.wikipedia.org/wiki/ISO_3166-1))
327
- * Added gatewayRejectionReason to Braintree_Transaction and Braintree_Verification
328
- * Added unified message to result objects
329
-
330
- ## 2.3.0
331
-
332
- * Added unified Braintree_TransparentRedirect url and confirm methods and deprecated old methods
333
- * Added functions to Braintree_CreditCard to allow searching on expiring and expired credit cards
334
- * Allow card verification against a specified merchant account
335
- * Added ability to update a customer, credit card, and billing address in one request
336
- * Allow updating the paymentMethodToken on a subscription
337
-
338
- ## 2.2.0
339
-
340
- * Prevent race condition when pulling back collection results -- search results represent the state of the data at the time the query was run
341
- * Rename ResourceCollection's approximate_size to maximum_size because items that no longer match the query will not be returned in the result set
342
- * Correctly handle HTTP error 426 (Upgrade Required) -- the error code is returned when your client library version is no long compatible with the gateway
343
- * Add the ability to specify merchant_account_id when verifying credit cards
344
- * Add subscription_id to transactions created from subscriptions
345
-
346
- ## 2.1.0
347
-
348
- * Added transaction advanced search
349
- * Added ability to partially refund transactions
350
- * Added ability to manually retry past-due subscriptions
351
- * Added new transaction error codes
352
- * Allow merchant account to be specified when creating transactions
353
- * Allow creating a transaction with a vault customer and new payment method
354
- * Allow existing billing address to be updated when updating credit card
355
- * Correctly handle xml with nil=true
356
-
357
- ## 2.0.0
358
-
359
- * Updated success? on transaction responses to return false on declined transactions
360
- * Search results now include Enumerable and will automatically paginate data
361
- * Added credit_card[cardholder_name] to allowed transaction params and CreditCardDetails (thanks [chrismcc](http://github.com/chrismcc))
362
- * Fixed a bug with Customer::all
363
- * Added constants for error codes
364
-
365
- ## 1.2.1
366
-
367
- * Added methods to get both shallow and deep errors from a Braintree_ValidationErrorCollection
368
- * Added the ability to make a credit card the default card for a customer
369
- * Added constants for transaction statuses
370
- * Updated Quick Start in README.md to show a workflow with error checking
371
-
372
- ## 1.2.0
373
-
374
- * Added subscription search
375
- * Provide access to associated subscriptions from CreditCard
376
- * Switched from using Zend framework for HTTP requests to using curl extension
377
- * Fixed a bug in Transparent Redirect when arg_separator.output is configured as &amp; instead of &
378
- * Increased http request timeout
379
- * Fixed a bug where ForgedQueryString exception was being raised instead of DownForMaintenance
380
- * Updated SSL CA files
381
-
382
- ## 1.1.1
383
-
384
- * Added Braintree_Transaction::refund
385
- * Added Braintree_Transaction::submitForSettlementNoValidate
386
- * Fixed a bug in errors->onHtmlField when checking for errors on custom fields when there are none
387
- * Added support for passing merchantAccountId for Transaction and Subscription
388
-
389
- ## 1.1.0
390
-
391
- * Added recurring billing support
392
-
393
- ## 1.0.1
394
-
395
- * Fixed bug with Braintree_Error_ErrorCollection.deepSize
396
- * Added methods for accessing validation errors and params by html field name
397
-
398
- ## 1.0.0
399
-
400
- * Initial release
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/LICENSE DELETED
@@ -1,22 +0,0 @@
1
- Copyright (c) 2014 Braintree, a division of PayPal, Inc.
2
-
3
- Permission is hereby granted, free of charge, to any person
4
- obtaining a copy of this software and associated documentation
5
- files (the "Software"), to deal in the Software without
6
- restriction, including without limitation the rights to use,
7
- copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- copies of the Software, and to permit persons to whom the
9
- Software is furnished to do so, subject to the following
10
- conditions:
11
-
12
- The above copyright notice and this permission notice shall be
13
- included in all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- OTHER DEALINGS IN THE SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/README.md DELETED
@@ -1,74 +0,0 @@
1
- # Braintree PHP Client Library
2
-
3
- The Braintree PHP library provides integration access to the Braintree Gateway.
4
-
5
- ## Dependencies
6
-
7
- PHP version >= 5.4.0 is required.
8
-
9
- The following PHP extensions are required:
10
-
11
- * curl
12
- * dom
13
- * hash
14
- * openssl
15
- * xmlwriter
16
-
17
- ## Quick Start Example
18
-
19
- ```php
20
- <?php
21
-
22
- require_once 'PATH_TO_BRAINTREE/lib/Braintree.php';
23
-
24
- Braintree\Configuration::environment('sandbox');
25
- Braintree\Configuration::merchantId('your_merchant_id');
26
- Braintree\Configuration::publicKey('your_public_key');
27
- Braintree\Configuration::privateKey('your_private_key');
28
-
29
- $result = Braintree\Transaction::sale([
30
- 'amount' => '1000.00',
31
- 'paymentMethodNonce' => 'nonceFromTheClient',
32
- 'options' => [ 'submitForSettlement' => true ]
33
- ]);
34
-
35
- if ($result->success) {
36
- print_r("success!: " . $result->transaction->id);
37
- } else if ($result->transaction) {
38
- print_r("Error processing transaction:");
39
- print_r("\n code: " . $result->transaction->processorResponseCode);
40
- print_r("\n text: " . $result->transaction->processorResponseText);
41
- } else {
42
- print_r("Validation errors: \n");
43
- print_r($result->errors->deepAll());
44
- }
45
- ```
46
-
47
- ## HHVM Support
48
-
49
- The Braintree PHP library will run on HHVM >= 3.4.2.
50
-
51
- ## Legacy PHP Support
52
-
53
- Version [2.40.0](https://github.com/braintree/braintree_php/releases/tag/2.40.0) is compatible with PHP 5.2 and 5.3. You can find it on our releases page.
54
-
55
- ## Documentation
56
-
57
- * [Official documentation](https://developers.braintreepayments.com/php/sdk/server/overview)
58
-
59
- ## Testing
60
-
61
- The unit specs can be run by anyone on any system, but the integration specs are meant to be run against a local development server of our gateway code. These integration specs are not meant for public consumption and will likely fail if run on your system. To run unit tests use rake: `rake test:unit`.
62
-
63
- The benefit of the `rake` tasks is that testing covers default `hhvm` and `php` interpreters. However, if you want to run tests manually simply use the following command:
64
- ```
65
- phpunit tests/unit/
66
- ```
67
-
68
- ## Open Source Attribution
69
-
70
- A list of open source projects that help power Braintree can be found [here](https://www.braintreepayments.com/developers/open-source).
71
-
72
- ## License
73
-
74
- See the LICENSE file.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/Rakefile DELETED
@@ -1,81 +0,0 @@
1
- task :default => :test
2
- task :test => %w[test:unit test:integration]
3
-
4
- namespace :test do
5
- task :unit => %w[test:php:unit test:hhvm:unit]
6
- task :integration => %w[test:php:integration test:hhvm:integration]
7
-
8
- namespace :php do
9
- desc "print PHP version"
10
- task :version do
11
- print_php_version("php")
12
- end
13
-
14
- desc "run unit tests under PHP"
15
- task :unit => :version do
16
- run_php_test_suite("php", "unit")
17
- end
18
-
19
- desc "run integration tests under PHP"
20
- task :integration do
21
- run_php_test_suite("php", "integration")
22
- end
23
- end
24
-
25
- namespace :hhvm do
26
- desc "print HHVM version"
27
- task :version do
28
- print_php_version("hhvm")
29
- end
30
-
31
- desc "run tests under HHVM"
32
- task :test => [:unit, :integration]
33
-
34
- desc "run unit tests under HHVM"
35
- task :unit => :version do
36
- run_php_test_suite("hhvm", "unit")
37
- end
38
-
39
- desc "run integration tests under HHVM"
40
- task :integration do
41
- run_php_test_suite("hhvm", "integration")
42
- end
43
- end
44
-
45
- desc "run tests under PHP"
46
- task :php => %w[php:unit php:integration]
47
-
48
- desc "run tests under HHVM"
49
- task :hhvm => %w[hhvm:unit hhvm:integration]
50
-
51
- desc "run a single test file"
52
- task :file, :file_path do |t, args|
53
- run_php_test_file(args[:file_path])
54
- end
55
-
56
- desc "run a single test"
57
- task :single, :test_name do |t, args|
58
- run_php_test(args[:test_name])
59
- end
60
- end
61
-
62
- desc "update the copyright year"
63
- task :copyright, :from_year, :to_year do |t, args|
64
- sh "find tests lib -type f -name '*.php' -exec sed -i 's/#{args[:from_year]} Braintree/#{args[:to_year]} Braintree/g' {} +"
65
- end
66
-
67
- def print_php_version(interpreter)
68
- sh "#{interpreter} --version"
69
- end
70
-
71
- def run_php_test_suite(interpreter, test_suite)
72
- sh "#{interpreter} ./vendor/bin/phpunit --testsuite #{test_suite}"
73
- end
74
-
75
- def run_php_test_file(test_file)
76
- sh "./vendor/bin/phpunit #{test_file}"
77
- end
78
-
79
- def run_php_test(test_name)
80
- sh "./vendor/bin/phpunit --filter #{test_name}"
81
- end
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/ci.sh DELETED
@@ -1,11 +0,0 @@
1
- #!/bin/bash
2
-
3
- curl -sS https://getcomposer.org/installer | php -d suhosin.executor.include.whitelist=phar
4
-
5
- php -d suhosin.executor.include.whitelist=phar ./composer.phar install
6
-
7
- if [ "$1" == "hhvm" ]; then
8
- rake test:hhvm --trace
9
- else
10
- rake test:php --trace
11
- fi
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/composer.json DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "name": "braintree/braintree_php",
3
- "type": "library",
4
- "description": "Braintree PHP Client Library",
5
- "license": "MIT",
6
- "authors": [
7
- {
8
- "name": "Braintree",
9
- "homepage": "http://www.braintreepayments.com"
10
- }
11
- ],
12
- "require": {
13
- "php": ">=5.4.0",
14
- "ext-curl": "*",
15
- "ext-dom": "*",
16
- "ext-hash": "*",
17
- "ext-openssl": "*",
18
- "ext-xmlwriter": "*"
19
- },
20
- "require-dev": {
21
- "phpunit/phpunit": "3.7.*"
22
- },
23
- "autoload": {
24
- "psr-0": {
25
- "Braintree": "lib/"
26
- },
27
- "psr-4": {
28
- "Braintree\\": "lib/Braintree"
29
- }
30
- },
31
- "autoload-dev": {
32
- "psr-4": {
33
- "Test\\": "tests"
34
- }
35
- }
36
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/phpunit.xml.dist DELETED
@@ -1,24 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <phpunit backupGlobals="false"
3
- backupStaticAttributes="false"
4
- bootstrap="./vendor/autoload.php"
5
- convertErrorsToExceptions="true"
6
- convertNoticesToExceptions="true"
7
- convertWarningsToExceptions="true"
8
- processIsolation="false"
9
- stopOnFailure="false"
10
- syntaxCheck="false">
11
-
12
- <php>
13
- <ini name="error_reporting" value="32767"/>
14
- </php>
15
-
16
- <testsuites>
17
- <testsuite name="unit">
18
- <directory>./tests/unit</directory>
19
- </testsuite>
20
- <testsuite name="integration">
21
- <directory>./tests/integration</directory>
22
- </testsuite>
23
- </testsuites>
24
- </phpunit>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/Braintree/CreditCardDefaults.php DELETED
@@ -1,8 +0,0 @@
1
- <?php
2
- namespace Test\Braintree;
3
-
4
- class CreditCardDefaults
5
- {
6
- const ISSUING_BANK = "NETWORK ONLY";
7
- const COUNTRY_OF_ISSUANCE = "USA";
8
- }
 
 
 
 
 
 
 
 
braintree_sdk/tests/Braintree/CreditCardNumbers/CardTypeIndicators.php DELETED
@@ -1,15 +0,0 @@
1
- <?php
2
- namespace Test\Braintree\CreditCardNumbers;
3
-
4
- class CardTypeIndicators {
5
- const PREPAID = "4111111111111210";
6
- const COMMERCIAL = "4111111111131010";
7
- const PAYROLL = "4111111114101010";
8
- const HEALTHCARE = "4111111510101010";
9
- const DURBIN_REGULATED = "4111161010101010";
10
- const DEBIT = "4117101010101010";
11
- const UNKNOWN = "4111111111112101";
12
- const NO = "4111111111310101";
13
- const ISSUING_BANK = "4111111141010101";
14
- const COUNTRY_OF_ISSUANCE = "4111111111121102";
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/Braintree/OAuthTestHelper.php DELETED
@@ -1,35 +0,0 @@
1
- <?php
2
- namespace Test\Braintree;
3
-
4
- use Braintree;
5
-
6
- class OAuthTestHelper
7
- {
8
- public static function createGrant($gateway, $params)
9
- {
10
- $http = new Braintree\Http($gateway->config);
11
- $http->useClientCredentials();
12
- $response = $http->post('/oauth_testing/grants', ['grant' => $params]);
13
- return $response['grant']['code'];
14
- }
15
-
16
- public static function createCredentials($params)
17
- {
18
- $gateway = new Braintree\Gateway([
19
- 'clientId' => $params['clientId'],
20
- 'clientSecret' => $params['clientSecret']
21
- ]);
22
-
23
- $code = OAuthTestHelper::createGrant($gateway, [
24
- 'merchant_public_id' => $params['merchantId'],
25
- 'scope' => 'read_write'
26
- ]);
27
-
28
- $credentials = $gateway->oauth()->createTokenFromCode([
29
- 'code' => $code,
30
- 'scope' => 'read_write',
31
- ]);
32
-
33
- return $credentials;
34
- }
35
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/Helper.php DELETED
@@ -1,136 +0,0 @@
1
- <?php
2
- namespace Test;
3
-
4
- require_once __DIR__ . '/Setup.php';
5
-
6
- use DateTime;
7
- use DateTimeZone;
8
- use Braintree;
9
-
10
- class Helper
11
- {
12
- public static function testMerchantConfig()
13
- {
14
- Braintree\Configuration::reset();
15
-
16
- Braintree\Configuration::environment('development');
17
- Braintree\Configuration::merchantId('test_merchant_id');
18
- Braintree\Configuration::publicKey('test_public_key');
19
- Braintree\Configuration::privateKey('test_private_key');
20
- }
21
-
22
- public static function defaultMerchantAccountId()
23
- {
24
- return 'sandbox_credit_card';
25
- }
26
-
27
- public static function nonDefaultMerchantAccountId()
28
- {
29
- return 'sandbox_credit_card_non_default';
30
- }
31
-
32
- public static function nonDefaultSubMerchantAccountId()
33
- {
34
- return 'sandbox_sub_merchant_account';
35
- }
36
-
37
- public static function threeDSecureMerchantAccountId()
38
- {
39
- return 'three_d_secure_merchant_account';
40
- }
41
-
42
- public static function fakeAmexDirectMerchantAccountId()
43
- {
44
- return 'fake_amex_direct_usd';
45
- }
46
-
47
- public static function fakeVenmoAccountMerchantAccountId()
48
- {
49
- return 'fake_first_data_venmo_account';
50
- }
51
-
52
- public static function createViaTr($regularParams, $trParams)
53
- {
54
- $trData = Braintree\TransparentRedirect::transactionData(
55
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
56
- );
57
- return self::submitTrRequest(
58
- Braintree\TransparentRedirect::url(),
59
- $regularParams,
60
- $trData
61
- );
62
- }
63
-
64
- public static function submitTrRequest($url, $regularParams, $trData)
65
- {
66
- $curl = curl_init();
67
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
68
- curl_setopt($curl, CURLOPT_URL, $url);
69
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
70
- curl_setopt($curl, CURLOPT_HEADER, true);
71
- // curl_setopt($curl, CURLOPT_VERBOSE, true);
72
- curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array_merge($regularParams, ['tr_data' => $trData])));
73
- curl_setopt($curl, CURLOPT_HTTPHEADER, [
74
- 'Content-Type: application/x-www-form-urlencoded'
75
- ]);
76
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
77
- $response = curl_exec($curl);
78
- curl_close($curl);
79
- preg_match('/Location: .*\?(.*)/i', $response, $match);
80
- return trim($match[1]);
81
- }
82
-
83
- public static function suppressDeprecationWarnings()
84
- {
85
- set_error_handler("Test\Helper::_errorHandler", E_USER_NOTICE);
86
- }
87
-
88
- public static function _errorHandler($errno, $errstr, $errfile, $errline)
89
- {
90
- if (preg_match('/^DEPRECATED/', $errstr) == 0) {
91
- trigger_error('Unknown error received: ' . $errstr, E_USER_ERROR);
92
- }
93
- }
94
-
95
- public static function includes($collection, $targetItem)
96
- {
97
- foreach ($collection AS $item) {
98
- if ($item->id == $targetItem->id) {
99
- return true;
100
- }
101
- }
102
- return false;
103
- }
104
-
105
- public static function assertPrintable($object)
106
- {
107
- " " . $object;
108
- }
109
-
110
- public static function escrow($transactionId)
111
- {
112
- $http = new Braintree\Http(Braintree\Configuration::$global);
113
- $path = Braintree\Configuration::$global->merchantPath() . '/transactions/' . $transactionId . '/escrow';
114
- $http->put($path);
115
- }
116
-
117
- public static function create3DSVerification($merchantAccountId, $params)
118
- {
119
- $http = new Braintree\Http(Braintree\Configuration::$global);
120
- $path = Braintree\Configuration::$global->merchantPath() . '/three_d_secure/create_verification/' . $merchantAccountId;
121
- $response = $http->post($path, ['threeDSecureVerification' => $params]);
122
- return $response['threeDSecureVerification']['threeDSecureToken'];
123
- }
124
-
125
- public static function nowInEastern()
126
- {
127
- $eastern = new DateTimeZone('America/New_York');
128
- $now = new DateTime('now', $eastern);
129
- return $now->format('Y-m-d');
130
- }
131
-
132
- public static function decodedClientToken($params=[]) {
133
- $encodedClientToken = Braintree\ClientToken::generate($params);
134
- return base64_decode($encodedClientToken);
135
- }
136
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/SanityTest.php DELETED
@@ -1,20 +0,0 @@
1
- <?php
2
-
3
- class SanityTest extends PHPUnit_Framework_TestCase
4
- {
5
- public function testLibraryWorksWithComposer()
6
- {
7
- if (version_compare(PHP_VERSION, "5.4.0", "<")) {
8
- $this->markTestSkipped("Requires PHP >=5.4");
9
- }
10
-
11
- $returnValue = null;
12
-
13
- $testFile = escapeshellarg(realpath(__DIR__ . '/Braintree/fixtures/composer_implementation.php'));
14
- $command = sprintf('%s %s', PHP_BINARY, $testFile);
15
-
16
- system($command, $returnValue);
17
-
18
- $this->assertEquals(0, $returnValue);
19
- }
20
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/Setup.php DELETED
@@ -1,32 +0,0 @@
1
- <?php
2
- namespace Test;
3
-
4
- require_once __DIR__ . '/Helper.php';
5
- require_once __DIR__ . '/integration/HttpClientApi.php';
6
- require_once __DIR__ . '/integration/SubscriptionHelper.php';
7
- require_once __DIR__ . '/Braintree/CreditCardNumbers/CardTypeIndicators.php';
8
- require_once __DIR__ . '/Braintree/CreditCardDefaults.php';
9
- require_once __DIR__ . '/Braintree/OAuthTestHelper.php';
10
-
11
- date_default_timezone_set('UTC');
12
-
13
- use Braintree\Configuration;
14
- use PHPUnit_Framework_TestCase;
15
-
16
- class Setup extends PHPUnit_Framework_TestCase
17
- {
18
- public function __construct()
19
- {
20
- self::integrationMerchantConfig();
21
- }
22
-
23
- public static function integrationMerchantConfig()
24
- {
25
- Configuration::reset();
26
-
27
- Configuration::environment('development');
28
- Configuration::merchantId('integration_merchant_id');
29
- Configuration::publicKey('integration_public_key');
30
- Configuration::privateKey('integration_private_key');
31
- }
32
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/AddOnsTest.php DELETED
@@ -1,88 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class AddOnsTest extends Setup
10
- {
11
- public function testAll_returnsAllAddOns()
12
- {
13
- $newId = strval(rand());
14
-
15
- $addOnParams = [
16
- "amount" => "100.00",
17
- "description" => "some description",
18
- "id" => $newId,
19
- "kind" => "add_on",
20
- "name" => "php_add_on",
21
- "neverExpires" => "false",
22
- "numberOfBillingCycles" => "1"
23
- ];
24
-
25
- $http = new Braintree\Http(Braintree\Configuration::$global);
26
- $path = Braintree\Configuration::$global->merchantPath() . "/modifications/create_modification_for_tests";
27
- $http->post($path, ["modification" => $addOnParams]);
28
-
29
- $addOns = Braintree\AddOn::all();
30
-
31
- foreach ($addOns as $addOn)
32
- {
33
- if ($addOn->id == $newId)
34
- {
35
- $actualAddOn = $addOn;
36
- }
37
- }
38
-
39
- $this->assertNotNull($actualAddOn);
40
- $this->assertEquals($addOnParams["amount"], $actualAddOn->amount);
41
- $this->assertEquals($addOnParams["description"], $actualAddOn->description);
42
- $this->assertEquals($addOnParams["id"], $actualAddOn->id);
43
- $this->assertEquals($addOnParams["kind"], $actualAddOn->kind);
44
- $this->assertEquals($addOnParams["name"], $actualAddOn->name);
45
- $this->assertFalse($actualAddOn->neverExpires);
46
- $this->assertEquals($addOnParams["numberOfBillingCycles"], $actualAddOn->numberOfBillingCycles);
47
- }
48
-
49
- public function testGatewayAll_returnsAllAddOns()
50
- {
51
- $newId = strval(rand());
52
-
53
- $addOnParams = [
54
- "amount" => "100.00",
55
- "description" => "some description",
56
- "id" => $newId,
57
- "kind" => "add_on",
58
- "name" => "php_add_on",
59
- "neverExpires" => "false",
60
- "numberOfBillingCycles" => "1"
61
- ];
62
-
63
- $http = new Braintree\Http(Braintree\Configuration::$global);
64
- $path = Braintree\Configuration::$global->merchantPath() . "/modifications/create_modification_for_tests";
65
- $http->post($path, ["modification" => $addOnParams]);
66
-
67
- $gateway = new Braintree\Gateway([
68
- 'environment' => 'development',
69
- 'merchantId' => 'integration_merchant_id',
70
- 'publicKey' => 'integration_public_key',
71
- 'privateKey' => 'integration_private_key'
72
- ]);
73
- $addOns = $gateway->addOn()->all();
74
-
75
- foreach ($addOns as $addOn)
76
- {
77
- if ($addOn->id == $newId)
78
- {
79
- $actualAddOn = $addOn;
80
- }
81
- }
82
-
83
- $this->assertNotNull($actualAddOn);
84
- $this->assertEquals($addOnParams["amount"], $actualAddOn->amount);
85
- $this->assertEquals($addOnParams["description"], $actualAddOn->description);
86
- $this->assertEquals($addOnParams["id"], $actualAddOn->id);
87
- }
88
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/AddressTest.php DELETED
@@ -1,303 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class AddressTest extends Setup
10
- {
11
- public function testCreate()
12
- {
13
- $customer = Braintree\Customer::createNoValidate();
14
- $result = Braintree\Address::create([
15
- 'customerId' => $customer->id,
16
- 'firstName' => 'Dan',
17
- 'lastName' => 'Smith',
18
- 'company' => 'Braintree',
19
- 'streetAddress' => '1 E Main St',
20
- 'extendedAddress' => 'Apt 1F',
21
- 'locality' => 'Chicago',
22
- 'region' => 'IL',
23
- 'postalCode' => '60622',
24
- 'countryName' => 'Vatican City',
25
- 'countryCodeAlpha2' => 'VA',
26
- 'countryCodeAlpha3' => 'VAT',
27
- 'countryCodeNumeric' => '336'
28
- ]);
29
- $this->assertTrue($result->success);
30
- $address = $result->address;
31
- $this->assertEquals('Dan', $address->firstName);
32
- $this->assertEquals('Smith', $address->lastName);
33
- $this->assertEquals('Braintree', $address->company);
34
- $this->assertEquals('1 E Main St', $address->streetAddress);
35
- $this->assertEquals('Apt 1F', $address->extendedAddress);
36
- $this->assertEquals('Chicago', $address->locality);
37
- $this->assertEquals('IL', $address->region);
38
- $this->assertEquals('60622', $address->postalCode);
39
- $this->assertEquals('Vatican City', $address->countryName);
40
- $this->assertEquals('VA', $address->countryCodeAlpha2);
41
- $this->assertEquals('VAT', $address->countryCodeAlpha3);
42
- $this->assertEquals('336', $address->countryCodeNumeric);
43
- }
44
-
45
- public function testGatewayCreate()
46
- {
47
- $customer = Braintree\Customer::createNoValidate();
48
-
49
- $gateway = new Braintree\Gateway([
50
- 'environment' => 'development',
51
- 'merchantId' => 'integration_merchant_id',
52
- 'publicKey' => 'integration_public_key',
53
- 'privateKey' => 'integration_private_key'
54
- ]);
55
- $result = $gateway->address()->create([
56
- 'customerId' => $customer->id,
57
- 'streetAddress' => '1 E Main St',
58
- 'locality' => 'Chicago',
59
- 'region' => 'IL',
60
- 'postalCode' => '60622',
61
- ]);
62
-
63
- $this->assertTrue($result->success);
64
- $address = $result->address;
65
- $this->assertEquals('1 E Main St', $address->streetAddress);
66
- $this->assertEquals('Chicago', $address->locality);
67
- $this->assertEquals('IL', $address->region);
68
- $this->assertEquals('60622', $address->postalCode);
69
- }
70
-
71
- public function testCreate_withValidationErrors()
72
- {
73
- $customer = Braintree\Customer::createNoValidate();
74
- $result = Braintree\Address::create([
75
- 'customerId' => $customer->id,
76
- 'countryName' => 'Invalid States of America'
77
- ]);
78
- $this->assertFalse($result->success);
79
- $countryErrors = $result->errors->forKey('address')->onAttribute('countryName');
80
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, $countryErrors[0]->code);
81
- }
82
-
83
- public function testCreate_withValidationErrors_onCountryCodes()
84
- {
85
- $customer = Braintree\Customer::createNoValidate();
86
- $result = Braintree\Address::create([
87
- 'customerId' => $customer->id,
88
- 'countryCodeAlpha2' => 'ZZ'
89
- ]);
90
- $this->assertFalse($result->success);
91
- $countryErrors = $result->errors->forKey('address')->onAttribute('countryCodeAlpha2');
92
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED, $countryErrors[0]->code);
93
- }
94
-
95
- public function testCreateNoValidate()
96
- {
97
- $customer = Braintree\Customer::createNoValidate();
98
- $address = Braintree\Address::createNoValidate([
99
- 'customerId' => $customer->id,
100
- 'firstName' => 'Dan',
101
- 'lastName' => 'Smith',
102
- 'company' => 'Braintree',
103
- 'streetAddress' => '1 E Main St',
104
- 'extendedAddress' => 'Apt 1F',
105
- 'locality' => 'Chicago',
106
- 'region' => 'IL',
107
- 'postalCode' => '60622',
108
- 'countryName' => 'United States of America'
109
- ]);
110
- $this->assertEquals('Dan', $address->firstName);
111
- $this->assertEquals('Smith', $address->lastName);
112
- $this->assertEquals('Braintree', $address->company);
113
- $this->assertEquals('1 E Main St', $address->streetAddress);
114
- $this->assertEquals('Apt 1F', $address->extendedAddress);
115
- $this->assertEquals('Chicago', $address->locality);
116
- $this->assertEquals('IL', $address->region);
117
- $this->assertEquals('60622', $address->postalCode);
118
- $this->assertEquals('United States of America', $address->countryName);
119
- }
120
-
121
- public function testCreateNoValidate_withValidationErrors()
122
- {
123
- $customer = Braintree\Customer::createNoValidate();
124
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
125
- Braintree\Address::createNoValidate([
126
- 'customerId' => $customer->id,
127
- 'countryName' => 'Invalid States of America'
128
- ]);
129
- }
130
-
131
- public function testDelete()
132
- {
133
- $customer = Braintree\Customer::createNoValidate();
134
- $address = Braintree\Address::createNoValidate([
135
- 'customerId' => $customer->id,
136
- 'streetAddress' => '1 E Main St'
137
- ]);
138
- Braintree\Address::find($customer->id, $address->id);
139
- Braintree\Address::delete($customer->id, $address->id);
140
- $this->setExpectedException('Braintree\Exception\NotFound');
141
- Braintree\Address::find($customer->id, $address->id);
142
- }
143
-
144
- public function testFind()
145
- {
146
- $customer = Braintree\Customer::createNoValidate();
147
- $result = Braintree\Address::create([
148
- 'customerId' => $customer->id,
149
- 'firstName' => 'Dan',
150
- 'lastName' => 'Smith',
151
- 'company' => 'Braintree',
152
- 'streetAddress' => '1 E Main St',
153
- 'extendedAddress' => 'Apt 1F',
154
- 'locality' => 'Chicago',
155
- 'region' => 'IL',
156
- 'postalCode' => '60622',
157
- 'countryName' => 'United States of America'
158
- ]);
159
- $this->assertTrue($result->success);
160
- $address = Braintree\Address::find($customer->id, $result->address->id);
161
- $this->assertEquals('Dan', $address->firstName);
162
- $this->assertEquals('Smith', $address->lastName);
163
- $this->assertEquals('Braintree', $address->company);
164
- $this->assertEquals('1 E Main St', $address->streetAddress);
165
- $this->assertEquals('Apt 1F', $address->extendedAddress);
166
- $this->assertEquals('Chicago', $address->locality);
167
- $this->assertEquals('IL', $address->region);
168
- $this->assertEquals('60622', $address->postalCode);
169
- $this->assertEquals('United States of America', $address->countryName);
170
- }
171
-
172
- public function testFind_whenNotFound()
173
- {
174
- $customer = Braintree\Customer::createNoValidate();
175
- $this->setExpectedException('Braintree\Exception\NotFound');
176
- Braintree\Address::find($customer->id, 'does-not-exist');
177
- }
178
-
179
- public function testUpdate()
180
- {
181
- $customer = Braintree\Customer::createNoValidate();
182
- $address = Braintree\Address::createNoValidate([
183
- 'customerId' => $customer->id,
184
- 'firstName' => 'Old First',
185
- 'lastName' => 'Old Last',
186
- 'company' => 'Old Company',
187
- 'streetAddress' => '1 E Old St',
188
- 'extendedAddress' => 'Apt Old',
189
- 'locality' => 'Old Chicago',
190
- 'region' => 'Old Region',
191
- 'postalCode' => 'Old Postal',
192
- 'countryName' => 'United States of America',
193
- 'countryCodeAlpha2' => 'US',
194
- 'countryCodeAlpha3' => 'USA',
195
- 'countryCodeNumeric' => '840'
196
- ]);
197
- $result = Braintree\Address::update($customer->id, $address->id, [
198
- 'firstName' => 'New First',
199
- 'lastName' => 'New Last',
200
- 'company' => 'New Company',
201
- 'streetAddress' => '1 E New St',
202
- 'extendedAddress' => 'Apt New',
203
- 'locality' => 'New Chicago',
204
- 'region' => 'New Region',
205
- 'postalCode' => 'New Postal',
206
- 'countryName' => 'Mexico',
207
- 'countryCodeAlpha2' => 'MX',
208
- 'countryCodeAlpha3' => 'MEX',
209
- 'countryCodeNumeric' => '484'
210
- ]);
211
- $this->assertTrue($result->success);
212
- $address = $result->address;
213
- $this->assertEquals('New First', $address->firstName);
214
- $this->assertEquals('New Last', $address->lastName);
215
- $this->assertEquals('New Company', $address->company);
216
- $this->assertEquals('1 E New St', $address->streetAddress);
217
- $this->assertEquals('Apt New', $address->extendedAddress);
218
- $this->assertEquals('New Chicago', $address->locality);
219
- $this->assertEquals('New Region', $address->region);
220
- $this->assertEquals('New Postal', $address->postalCode);
221
- $this->assertEquals('Mexico', $address->countryName);
222
- $this->assertEquals('MX', $address->countryCodeAlpha2);
223
- $this->assertEquals('MEX', $address->countryCodeAlpha3);
224
- $this->assertEquals('484', $address->countryCodeNumeric);
225
- }
226
-
227
- public function testUpdate_withValidationErrors()
228
- {
229
- $customer = Braintree\Customer::createNoValidate();
230
- $address = Braintree\Address::createNoValidate([
231
- 'customerId' => $customer->id,
232
- 'streetAddress' => '1 E Main St'
233
- ]);
234
- $result = Braintree\Address::update(
235
- $customer->id,
236
- $address->id,
237
- [
238
- 'countryName' => 'Invalid States of America'
239
- ]
240
- );
241
- $this->assertFalse($result->success);
242
- $countryErrors = $result->errors->forKey('address')->onAttribute('countryName');
243
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, $countryErrors[0]->code);
244
- }
245
-
246
- public function testUpdate_withValidationErrors_onCountry()
247
- {
248
- $customer = Braintree\Customer::createNoValidate();
249
- $address = Braintree\Address::createNoValidate([
250
- 'customerId' => $customer->id,
251
- 'streetAddress' => '1 E Main St'
252
- ]);
253
- $result = Braintree\Address::update(
254
- $customer->id,
255
- $address->id,
256
- [
257
- 'countryCodeAlpha2' => 'MU',
258
- 'countryCodeAlpha3' => 'MYT'
259
- ]
260
- );
261
- $this->assertFalse($result->success);
262
- $countryErrors = $result->errors->forKey('address')->onAttribute('base');
263
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_INCONSISTENT_COUNTRY, $countryErrors[0]->code);
264
- }
265
-
266
-
267
- public function testUpdateNoValidate()
268
- {
269
- $customer = Braintree\Customer::createNoValidate();
270
- $createdAddress = Braintree\Address::createNoValidate([
271
- 'customerId' => $customer->id,
272
- 'firstName' => 'Old First',
273
- 'lastName' => 'Old Last',
274
- 'company' => 'Old Company',
275
- 'streetAddress' => '1 E Old St',
276
- 'extendedAddress' => 'Apt Old',
277
- 'locality' => 'Old Chicago',
278
- 'region' => 'Old Region',
279
- 'postalCode' => 'Old Postal',
280
- 'countryName' => 'United States of America'
281
- ]);
282
- $address = Braintree\Address::updateNoValidate($customer->id, $createdAddress->id, [
283
- 'firstName' => 'New First',
284
- 'lastName' => 'New Last',
285
- 'company' => 'New Company',
286
- 'streetAddress' => '1 E New St',
287
- 'extendedAddress' => 'Apt New',
288
- 'locality' => 'New Chicago',
289
- 'region' => 'New Region',
290
- 'postalCode' => 'New Postal',
291
- 'countryName' => 'Mexico'
292
- ]);
293
- $this->assertEquals('New First', $address->firstName);
294
- $this->assertEquals('New Last', $address->lastName);
295
- $this->assertEquals('New Company', $address->company);
296
- $this->assertEquals('1 E New St', $address->streetAddress);
297
- $this->assertEquals('Apt New', $address->extendedAddress);
298
- $this->assertEquals('New Chicago', $address->locality);
299
- $this->assertEquals('New Region', $address->region);
300
- $this->assertEquals('New Postal', $address->postalCode);
301
- $this->assertEquals('Mexico', $address->countryName);
302
- }
303
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/ClientTokenTest.php DELETED
@@ -1,188 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class ClientTokenTest extends Setup
11
- {
12
- public function test_ClientTokenAuthorizesRequest()
13
- {
14
- $clientToken = Test\Helper::decodedClientToken();
15
- $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
16
- $http = new HttpClientApi(Braintree\Configuration::$global);
17
- $response = $http->get_cards([
18
- "authorization_fingerprint" => $authorizationFingerprint,
19
- "shared_customer_identifier" => "fake_identifier",
20
- "shared_customer_identifier_type" => "testing",
21
- ]);
22
-
23
- $this->assertEquals(200, $response["status"]);
24
- }
25
-
26
- public function test_VersionOptionSupported()
27
- {
28
- $clientToken = Braintree\ClientToken::generate(["version" => 1]);
29
- $version = json_decode($clientToken)->version;
30
- $this->assertEquals(1, $version);
31
- }
32
-
33
- public function test_VersionDefaultsToTwo()
34
- {
35
- $encodedClientToken = Braintree\ClientToken::generate();
36
- $clientToken = base64_decode($encodedClientToken);
37
- $version = json_decode($clientToken)->version;
38
- $this->assertEquals(2, $version);
39
- }
40
-
41
- public function testGateway_VersionDefaultsToTwo()
42
- {
43
- $gateway = new Braintree\Gateway([
44
- 'environment' => 'development',
45
- 'merchantId' => 'integration_merchant_id',
46
- 'publicKey' => 'integration_public_key',
47
- 'privateKey' => 'integration_private_key',
48
- ]);
49
- $encodedClientToken = $gateway->clientToken()->generate();
50
- $clientToken = base64_decode($encodedClientToken);
51
- $version = json_decode($clientToken)->version;
52
- $this->assertEquals(2, $version);
53
- }
54
-
55
- public function test_GatewayRespectsVerifyCard()
56
- {
57
- $result = Braintree\Customer::create();
58
- $this->assertTrue($result->success);
59
- $customerId = $result->customer->id;
60
-
61
- $clientToken = Test\Helper::decodedClientToken([
62
- "customerId" => $customerId,
63
- "options" => [
64
- "verifyCard" => true
65
- ]
66
- ]);
67
- $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
68
-
69
- $http = new HttpClientApi(Braintree\Configuration::$global);
70
- $response = $http->post('/client_api/v1/payment_methods/credit_cards.json', json_encode([
71
- "credit_card" => [
72
- "number" => "4000111111111115",
73
- "expirationDate" => "11/2099"
74
- ],
75
- "authorization_fingerprint" => $authorizationFingerprint,
76
- "shared_customer_identifier" => "fake_identifier",
77
- "shared_customer_identifier_type" => "testing"
78
- ]));
79
-
80
- $this->assertEquals(422, $response["status"]);
81
- }
82
-
83
- public function test_GatewayRespectsFailOnDuplicatePaymentMethod()
84
- {
85
- $result = Braintree\Customer::create();
86
- $this->assertTrue($result->success);
87
- $customerId = $result->customer->id;
88
-
89
- $clientToken = Test\Helper::decodedClientToken([
90
- "customerId" => $customerId,
91
- ]);
92
- $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
93
-
94
- $http = new HttpClientApi(Braintree\Configuration::$global);
95
- $response = $http->post('/client_api/v1/payment_methods/credit_cards.json', json_encode([
96
- "credit_card" => [
97
- "number" => "4242424242424242",
98
- "expirationDate" => "11/2099"
99
- ],
100
- "authorization_fingerprint" => $authorizationFingerprint,
101
- "shared_customer_identifier" => "fake_identifier",
102
- "shared_customer_identifier_type" => "testing"
103
- ]));
104
- $this->assertEquals(201, $response["status"]);
105
-
106
- $clientToken = Test\Helper::decodedClientToken([
107
- "customerId" => $customerId,
108
- "options" => [
109
- "failOnDuplicatePaymentMethod" => true
110
- ]
111
- ]);
112
- $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
113
-
114
- $http = new HttpClientApi(Braintree\Configuration::$global);
115
- $response = $http->post('/client_api/v1/payment_methods/credit_cards.json', json_encode([
116
- "credit_card" => [
117
- "number" => "4242424242424242",
118
- "expirationDate" => "11/2099"
119
- ],
120
- "authorization_fingerprint" => $authorizationFingerprint,
121
- "shared_customer_identifier" => "fake_identifier",
122
- "shared_customer_identifier_type" => "testing"
123
- ]));
124
- $this->assertEquals(422, $response["status"]);
125
- }
126
-
127
- public function test_GatewayRespectsMakeDefault()
128
- {
129
- $result = Braintree\Customer::create();
130
- $this->assertTrue($result->success);
131
- $customerId = $result->customer->id;
132
-
133
- $result = Braintree\CreditCard::create([
134
- 'customerId' => $customerId,
135
- 'number' => '4111111111111111',
136
- 'expirationDate' => '11/2099'
137
- ]);
138
- $this->assertTrue($result->success);
139
-
140
- $clientToken = Test\Helper::decodedClientToken([
141
- "customerId" => $customerId,
142
- "options" => [
143
- "makeDefault" => true
144
- ]
145
- ]);
146
- $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
147
-
148
- $http = new HttpClientApi(Braintree\Configuration::$global);
149
- $response = $http->post('/client_api/v1/payment_methods/credit_cards.json', json_encode([
150
- "credit_card" => [
151
- "number" => "4242424242424242",
152
- "expirationDate" => "11/2099"
153
- ],
154
- "authorization_fingerprint" => $authorizationFingerprint,
155
- "shared_customer_identifier" => "fake_identifier",
156
- "shared_customer_identifier_type" => "testing"
157
- ]));
158
-
159
- $this->assertEquals(201, $response["status"]);
160
-
161
- $customer = Braintree\Customer::find($customerId);
162
- $this->assertEquals(2, count($customer->creditCards));
163
- foreach ($customer->creditCards as $creditCard) {
164
- if ($creditCard->last4 == "4242") {
165
- $this->assertTrue($creditCard->default);
166
- }
167
- }
168
- }
169
-
170
- public function test_ClientTokenAcceptsMerchantAccountId()
171
- {
172
- $clientToken = Test\Helper::decodedClientToken([
173
- 'merchantAccountId' => 'my_merchant_account'
174
- ]);
175
- $merchantAccountId = json_decode($clientToken)->merchantAccountId;
176
-
177
- $this->assertEquals('my_merchant_account', $merchantAccountId);
178
- }
179
-
180
- public function test_GenerateRaisesExceptionOnGateway422()
181
- {
182
- $this->setExpectedException('InvalidArgumentException', 'customer_id');
183
-
184
- Braintree\ClientToken::generate([
185
- "customerId" => "not_a_customer"
186
- ]);
187
- }
188
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/CreditCardTest.php DELETED
@@ -1,1319 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Braintree\CreditCardNumbers\CardTypeIndicators;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class CreditCardTest extends Setup
12
- {
13
- public function testCreate()
14
- {
15
- $customer = Braintree\Customer::createNoValidate();
16
- $result = Braintree\CreditCard::create([
17
- 'customerId' => $customer->id,
18
- 'cardholderName' => 'Cardholder',
19
- 'number' => '5105105105105100',
20
- 'expirationDate' => '05/12'
21
- ]);
22
- $this->assertTrue($result->success);
23
- $this->assertEquals($customer->id, $result->creditCard->customerId);
24
- $this->assertEquals('510510', $result->creditCard->bin);
25
- $this->assertEquals('5100', $result->creditCard->last4);
26
- $this->assertEquals('Cardholder', $result->creditCard->cardholderName);
27
- $this->assertEquals('05/2012', $result->creditCard->expirationDate);
28
- $this->assertEquals(1, preg_match('/\A\w{32}\z/', $result->creditCard->uniqueNumberIdentifier));
29
- $this->assertFalse($result->creditCard->isVenmoSdk());
30
- $this->assertEquals(1, preg_match('/png/', $result->creditCard->imageUrl));
31
- }
32
-
33
- public function testGatewayCreate()
34
- {
35
- $customer = Braintree\Customer::createNoValidate();
36
-
37
- $gateway = new Braintree\Gateway([
38
- 'environment' => 'development',
39
- 'merchantId' => 'integration_merchant_id',
40
- 'publicKey' => 'integration_public_key',
41
- 'privateKey' => 'integration_private_key'
42
- ]);
43
- $result = $gateway->creditCard()->create([
44
- 'customerId' => $customer->id,
45
- 'cardholderName' => 'Cardholder',
46
- 'number' => '5105105105105100',
47
- 'expirationDate' => '05/12'
48
- ]);
49
-
50
- $this->assertTrue($result->success);
51
- $this->assertEquals($customer->id, $result->creditCard->customerId);
52
- $this->assertEquals('510510', $result->creditCard->bin);
53
- $this->assertEquals('5100', $result->creditCard->last4);
54
- $this->assertEquals('Cardholder', $result->creditCard->cardholderName);
55
- $this->assertEquals('05/2012', $result->creditCard->expirationDate);
56
- }
57
-
58
- public function testCreate_withDefault()
59
- {
60
- $customer = Braintree\Customer::createNoValidate();
61
- $card1 = Braintree\CreditCard::create([
62
- 'customerId' => $customer->id,
63
- 'cardholderName' => 'Cardholder',
64
- 'number' => '5105105105105100',
65
- 'expirationDate' => '05/12'
66
- ])->creditCard;
67
- $this->assertTrue($card1->isDefault());
68
-
69
- $card2 = Braintree\CreditCard::create([
70
- 'customerId' => $customer->id,
71
- 'cardholderName' => 'Cardholder',
72
- 'number' => '5105105105105100',
73
- 'expirationDate' => '05/12',
74
- 'options' => [
75
- 'makeDefault' => true
76
- ]
77
- ])->creditCard;
78
-
79
- $card1 = Braintree\CreditCard::find($card1->token);
80
- $this->assertFalse($card1->isDefault());
81
- $this->assertTrue($card2->isDefault());
82
- }
83
-
84
- public function testCreateWithVerificationAmount()
85
- {
86
- $customer = Braintree\Customer::createNoValidate();
87
- $result = Braintree\CreditCard::create([
88
- 'customerId' => $customer->id,
89
- 'cardholderName' => 'Cardholder',
90
- 'number' => '4111111111111111',
91
- 'expirationDate' => '05/12',
92
- 'options' => [
93
- 'verificationAmount' => '5.00',
94
- 'verifyCard' => true
95
- ]
96
- ]);
97
- $this->assertTrue($result->success);
98
- $this->assertEquals($customer->id, $result->creditCard->customerId);
99
- $this->assertEquals('411111', $result->creditCard->bin);
100
- $this->assertEquals('1111', $result->creditCard->last4);
101
- $this->assertEquals('Cardholder', $result->creditCard->cardholderName);
102
- $this->assertEquals('05/2012', $result->creditCard->expirationDate);
103
- $this->assertEquals(1, preg_match('/\A\w{32}\z/', $result->creditCard->uniqueNumberIdentifier));
104
- $this->assertFalse($result->creditCard->isVenmoSdk());
105
- $this->assertEquals(1, preg_match('/png/', $result->creditCard->imageUrl));
106
- }
107
-
108
- public function testAddCardToExistingCustomerUsingNonce()
109
- {
110
- $customer = Braintree\Customer::createNoValidate();
111
- $http = new HttpClientApi(Braintree\Configuration::$global);
112
- $nonce = $http->nonce_for_new_card([
113
- "credit_card" => [
114
- "number" => "4111111111111111",
115
- "expirationMonth" => "11",
116
- "expirationYear" => "2099"
117
- ],
118
- "share" => true
119
- ]);
120
-
121
- $result = Braintree\CreditCard::create([
122
- 'customerId' => $customer->id,
123
- 'paymentMethodNonce' => $nonce
124
- ]);
125
-
126
- $this->assertSame("411111", $result->creditCard->bin);
127
- $this->assertSame("1111", $result->creditCard->last4);
128
- }
129
-
130
- public function testCreate_withSecurityParams()
131
- {
132
- $customer = Braintree\Customer::createNoValidate();
133
- $result = Braintree\CreditCard::create([
134
- 'customerId' => $customer->id,
135
- 'deviceSessionId' => 'abc_123',
136
- 'fraudMerchantId' => '456',
137
- 'cardholderName' => 'Cardholder',
138
- 'number' => '5105105105105100',
139
- 'expirationDate' => '05/12'
140
- ]);
141
-
142
- $this->assertTrue($result->success);
143
- }
144
-
145
- public function testCreate_withExpirationMonthAndYear()
146
- {
147
- $customer = Braintree\Customer::createNoValidate();
148
- $result = Braintree\CreditCard::create([
149
- 'customerId' => $customer->id,
150
- 'cardholderName' => 'Cardholder',
151
- 'number' => '5105105105105100',
152
- 'expirationMonth' => '05',
153
- 'expirationYear' => '2011'
154
- ]);
155
- $this->assertTrue($result->success);
156
- $this->assertEquals($customer->id, $result->creditCard->customerId);
157
- $this->assertEquals('510510', $result->creditCard->bin);
158
- $this->assertEquals('5100', $result->creditCard->last4);
159
- $this->assertEquals('Cardholder', $result->creditCard->cardholderName);
160
- $this->assertEquals('05/2011', $result->creditCard->expirationDate);
161
- }
162
-
163
- public function testCreate_withSpecifyingToken()
164
- {
165
- $token = strval(rand());
166
- $customer = Braintree\Customer::createNoValidate();
167
- $result = Braintree\CreditCard::create([
168
- 'customerId' => $customer->id,
169
- 'number' => '5105105105105100',
170
- 'expirationDate' => '05/2011',
171
- 'token' => $token
172
- ]);
173
- $this->assertTrue($result->success);
174
- $this->assertEquals($token, $result->creditCard->token);
175
- $this->assertEquals($token, Braintree\CreditCard::find($token)->token);
176
- }
177
-
178
- public function testCreate_withDuplicateCardCheck()
179
- {
180
- $customer = Braintree\Customer::createNoValidate();
181
-
182
- $attributes = [
183
- 'customerId' => $customer->id,
184
- 'number' => '5105105105105100',
185
- 'expirationDate' => '05/2011',
186
- 'options' => ['failOnDuplicatePaymentMethod' => true]
187
- ];
188
- Braintree\CreditCard::create($attributes);
189
-
190
- $result = Braintree\CreditCard::create($attributes);
191
- $this->assertFalse($result->success);
192
- $errors = $result->errors->forKey('creditCard')->onAttribute('number');
193
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_DUPLICATE_CARD_EXISTS, $errors[0]->code);
194
- $this->assertEquals(1, preg_match('/Duplicate card exists in the vault\./', $result->message));
195
- }
196
-
197
- public function testCreate_withCardVerification()
198
- {
199
- $customer = Braintree\Customer::createNoValidate();
200
- $result = Braintree\CreditCard::create([
201
- 'customerId' => $customer->id,
202
- 'number' => '5105105105105100',
203
- 'expirationDate' => '05/2011',
204
- 'options' => ['verifyCard' => true]
205
- ]);
206
- $this->assertFalse($result->success);
207
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
208
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
209
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
210
- $this->assertEquals('I', $result->creditCardVerification->cvvResponseCode);
211
- $this->assertEquals(null, $result->creditCardVerification->avsErrorResponseCode);
212
- $this->assertEquals('I', $result->creditCardVerification->avsPostalCodeResponseCode);
213
- $this->assertEquals('I', $result->creditCardVerification->avsStreetAddressResponseCode);
214
- $this->assertEquals(Braintree\CreditCard::PREPAID_UNKNOWN, $result->creditCardVerification->creditCard['prepaid']);
215
- }
216
-
217
- public function testCreate_withCardVerificationReturnsVerificationWithRiskData()
218
- {
219
- $customer = Braintree\Customer::createNoValidate();
220
- $result = Braintree\CreditCard::create([
221
- 'customerId' => $customer->id,
222
- 'number' => '4111111111111111',
223
- 'expirationDate' => '05/2011',
224
- 'options' => ['verifyCard' => true]
225
- ]);
226
- $this->assertTrue($result->success);
227
- $this->assertNotNull($result->creditCard->verification->riskData);
228
- $this->assertNotNull($result->creditCard->verification->riskData->decision);
229
- }
230
-
231
- public function testCreate_withCardVerificationAndOverriddenAmount()
232
- {
233
- $customer = Braintree\Customer::createNoValidate();
234
- $result = Braintree\CreditCard::create([
235
- 'customerId' => $customer->id,
236
- 'number' => '5105105105105100',
237
- 'expirationDate' => '05/2011',
238
- 'options' => ['verifyCard' => true, 'verificationAmount' => '1.02']
239
- ]);
240
- $this->assertFalse($result->success);
241
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
242
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
243
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
244
- $this->assertEquals('I', $result->creditCardVerification->cvvResponseCode);
245
- $this->assertEquals(null, $result->creditCardVerification->avsErrorResponseCode);
246
- $this->assertEquals('I', $result->creditCardVerification->avsPostalCodeResponseCode);
247
- $this->assertEquals('I', $result->creditCardVerification->avsStreetAddressResponseCode);
248
- $this->assertEquals(Braintree\CreditCard::PREPAID_UNKNOWN, $result->creditCardVerification->creditCard['prepaid']);
249
- }
250
-
251
- public function testCreate_withCardVerificationAndSpecificMerchantAccount()
252
- {
253
- $customer = Braintree\Customer::createNoValidate();
254
- $result = Braintree\CreditCard::create([
255
- 'customerId' => $customer->id,
256
- 'number' => '5105105105105100',
257
- 'expirationDate' => '05/2011',
258
- 'options' => ['verificationMerchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(), 'verifyCard' => true],
259
- ]);
260
- $this->assertFalse($result->success);
261
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
262
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
263
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
264
- $this->assertEquals('I', $result->creditCardVerification->cvvResponseCode);
265
- $this->assertEquals(null, $result->creditCardVerification->avsErrorResponseCode);
266
- $this->assertEquals('I', $result->creditCardVerification->avsPostalCodeResponseCode);
267
- $this->assertEquals('I', $result->creditCardVerification->avsStreetAddressResponseCode);
268
- }
269
-
270
- public function testCreate_withBillingAddress()
271
- {
272
- $customer = Braintree\Customer::createNoValidate();
273
- $result = Braintree\CreditCard::create([
274
- 'customerId' => $customer->id,
275
- 'cardholderName' => 'Peter Tomlin',
276
- 'number' => '5105105105105100',
277
- 'expirationDate' => '05/12',
278
- 'billingAddress' => [
279
- 'firstName' => 'Drew',
280
- 'lastName' => 'Smith',
281
- 'company' => 'Smith Co.',
282
- 'streetAddress' => '1 E Main St',
283
- 'extendedAddress' => 'Suite 101',
284
- 'locality' => 'Chicago',
285
- 'region' => 'IL',
286
- 'postalCode' => '60622',
287
- 'countryName' => 'Micronesia',
288
- 'countryCodeAlpha2' => 'FM',
289
- 'countryCodeAlpha3' => 'FSM',
290
- 'countryCodeNumeric' => '583'
291
- ]
292
- ]);
293
- $this->assertTrue($result->success);
294
- $this->assertEquals($customer->id, $result->creditCard->customerId);
295
- $this->assertEquals('510510', $result->creditCard->bin);
296
- $this->assertEquals('5100', $result->creditCard->last4);
297
- $this->assertEquals('Peter Tomlin', $result->creditCard->cardholderName);
298
- $this->assertEquals('05/2012', $result->creditCard->expirationDate);
299
- $address = $result->creditCard->billingAddress;
300
- $this->assertEquals('Drew', $address->firstName);
301
- $this->assertEquals('Smith', $address->lastName);
302
- $this->assertEquals('Smith Co.', $address->company);
303
- $this->assertEquals('1 E Main St', $address->streetAddress);
304
- $this->assertEquals('Suite 101', $address->extendedAddress);
305
- $this->assertEquals('Chicago', $address->locality);
306
- $this->assertEquals('IL', $address->region);
307
- $this->assertEquals('60622', $address->postalCode);
308
- $this->assertEquals('Micronesia', $address->countryName);
309
- $this->assertEquals('FM', $address->countryCodeAlpha2);
310
- $this->assertEquals('FSM', $address->countryCodeAlpha3);
311
- $this->assertEquals('583', $address->countryCodeNumeric);
312
- }
313
-
314
- public function testCreate_withExistingBillingAddress()
315
- {
316
- $customer = Braintree\Customer::createNoValidate();
317
- $existingAddress = Braintree\Address::createNoValidate([
318
- 'customerId' => $customer->id,
319
- 'firstName' => 'John'
320
- ]);
321
- $result = Braintree\CreditCard::create([
322
- 'customerId' => $customer->id,
323
- 'number' => '5105105105105100',
324
- 'expirationDate' => '05/12',
325
- 'billingAddressId' => $existingAddress->id
326
- ]);
327
- $this->assertTrue($result->success);
328
- $address = $result->creditCard->billingAddress;
329
- $this->assertEquals($existingAddress->id, $address->id);
330
- $this->assertEquals('John', $address->firstName);
331
- }
332
-
333
- public function testCreate_withValidationErrors()
334
- {
335
- $customer = Braintree\Customer::createNoValidate();
336
- $result = Braintree\CreditCard::create([
337
- 'expirationDate' => 'invalid',
338
- 'billingAddress' => [
339
- 'countryName' => 'Tuvalu',
340
- 'countryCodeAlpha2' => 'US'
341
- ]
342
- ]);
343
- $this->assertFalse($result->success);
344
- $errors = $result->errors->forKey('creditCard')->onAttribute('expirationDate');
345
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, $errors[0]->code);
346
- $this->assertEquals(1, preg_match('/Credit card number is required\./', $result->message));
347
- $this->assertEquals(1, preg_match('/Customer ID is required\./', $result->message));
348
- $this->assertEquals(1, preg_match('/Expiration date is invalid\./', $result->message));
349
-
350
- $errors = $result->errors->forKey('creditCard')->forKey('billingAddress')->onAttribute('base');
351
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_INCONSISTENT_COUNTRY, $errors[0]->code);
352
- }
353
-
354
- public function testCreate_withVenmoSdkPaymentMethodCode()
355
- {
356
- $customer = Braintree\Customer::createNoValidate();
357
- $result = Braintree\CreditCard::create([
358
- 'customerId' => $customer->id,
359
- 'venmoSdkPaymentMethodCode' => Braintree\Test\VenmoSdk::generateTestPaymentMethodCode('378734493671000')
360
- ]);
361
- $this->assertTrue($result->success);
362
- $this->assertEquals("378734", $result->creditCard->bin);
363
- }
364
-
365
- public function testCreate_with_invalid_venmoSdkPaymentMethodCode()
366
- {
367
- $customer = Braintree\Customer::createNoValidate();
368
- $result = Braintree\CreditCard::create([
369
- 'customerId' => $customer->id,
370
- 'venmoSdkPaymentMethodCode' => Braintree\Test\VenmoSdk::getInvalidPaymentMethodCode(),
371
- ]);
372
- $this->assertFalse($result->success);
373
- $errors = $result->errors->forKey('creditCard')->onAttribute('venmoSdkPaymentMethodCode');
374
- $this->assertEquals($errors[0]->code, Braintree\Error\Codes::CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE);
375
-
376
- }
377
-
378
- public function testCreate_with_venmoSdkSession()
379
- {
380
- $customer = Braintree\Customer::createNoValidate();
381
- $result = Braintree\CreditCard::create([
382
- 'customerId' => $customer->id,
383
- 'number' => '5105105105105100',
384
- 'expirationDate' => '05/12',
385
- 'options' => [
386
- 'venmoSdkSession' => Braintree\Test\VenmoSdk::getTestSession()
387
- ]
388
- ]);
389
- $this->assertTrue($result->success);
390
- $this->assertTrue($result->creditCard->isVenmoSdk());
391
- }
392
-
393
- public function testCreate_with_invalidVenmoSdkSession()
394
- {
395
- $customer = Braintree\Customer::createNoValidate();
396
- $result = Braintree\CreditCard::create([
397
- 'customerId' => $customer->id,
398
- 'number' => '5105105105105100',
399
- 'expirationDate' => '05/12',
400
- 'options' => [
401
- 'venmoSdkSession' => Braintree\Test\VenmoSdk::getInvalidTestSession(),
402
- ]
403
- ]);
404
- $this->assertTrue($result->success);
405
- $this->assertFalse($result->creditCard->isVenmoSdk());
406
- }
407
-
408
- public function testCreateNoValidate_throwsIfValidationsFail()
409
- {
410
-
411
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
412
- $customer = Braintree\Customer::createNoValidate();
413
- Braintree\CreditCard::createNoValidate([
414
- 'expirationDate' => 'invalid',
415
- ]);
416
- }
417
-
418
- public function testCreateNoValidate_returnsCreditCardIfValid()
419
- {
420
- $customer = Braintree\Customer::createNoValidate();
421
- $creditCard = Braintree\CreditCard::createNoValidate([
422
- 'customerId' => $customer->id,
423
- 'cardholderName' => 'Cardholder',
424
- 'number' => '5105105105105100',
425
- 'expirationDate' => '05/12'
426
- ]);
427
- $this->assertEquals($customer->id, $creditCard->customerId);
428
- $this->assertEquals('510510', $creditCard->bin);
429
- $this->assertEquals('5100', $creditCard->last4);
430
- $this->assertEquals('Cardholder', $creditCard->cardholderName);
431
- $this->assertEquals('05/2012', $creditCard->expirationDate);
432
- }
433
-
434
- public function testCreateFromTransparentRedirect()
435
- {
436
- Test\Helper::suppressDeprecationWarnings();
437
- $customer = Braintree\Customer::createNoValidate();
438
- $queryString = $this->createCreditCardViaTr(
439
- [
440
- 'credit_card' => [
441
- 'number' => '5105105105105100',
442
- 'expiration_date' => '05/12'
443
- ]
444
- ],
445
- [
446
- 'creditCard' => [
447
- 'customerId' => $customer->id
448
- ]
449
- ]
450
- );
451
- $result = Braintree\CreditCard::createFromTransparentRedirect($queryString);
452
- $this->assertTrue($result->success);
453
- $this->assertEquals('510510', $result->creditCard->bin);
454
- $this->assertEquals('5100', $result->creditCard->last4);
455
- $this->assertEquals('05/2012', $result->creditCard->expirationDate);
456
- }
457
-
458
- public function testCreateFromTransparentRedirect_withDefault()
459
- {
460
- Test\Helper::suppressDeprecationWarnings();
461
- $customer = Braintree\Customer::createNoValidate();
462
- $queryString = $this->createCreditCardViaTr(
463
- [
464
- 'credit_card' => [
465
- 'number' => '5105105105105100',
466
- 'expiration_date' => '05/12',
467
- 'options' => ['make_default' => true]
468
- ]
469
- ],
470
- [
471
- 'creditCard' => [
472
- 'customerId' => $customer->id
473
- ]
474
- ]
475
- );
476
- $result = Braintree\CreditCard::createFromTransparentRedirect($queryString);
477
- $this->assertTrue($result->creditCard->isDefault());
478
- }
479
-
480
- public function testUpdateFromTransparentRedirect()
481
- {
482
- $customer = Braintree\Customer::createNoValidate();
483
- $creditCard = Braintree\CreditCard::createNoValidate([
484
- 'customerId' => $customer->id,
485
- 'number' => '5105105105105100',
486
- 'expirationDate' => '05/12'
487
- ]);
488
- $queryString = $this->updateCreditCardViaTr(
489
- [
490
- 'credit_card' => [
491
- 'number' => '4111111111111111',
492
- 'expiration_date' => '01/11'
493
- ]
494
- ],
495
- ['paymentMethodToken' => $creditCard->token]
496
- );
497
- $result = Braintree\CreditCard::updateFromTransparentRedirect($queryString);
498
- $this->assertTrue($result->success);
499
- $this->assertEquals('411111', $result->creditCard->bin);
500
- $this->assertEquals('1111', $result->creditCard->last4);
501
- $this->assertEquals('01/2011', $result->creditCard->expirationDate);
502
- }
503
-
504
- public function testUpdateFromTransparentRedirect_withDefault()
505
- {
506
- $customer = Braintree\Customer::createNoValidate();
507
- $card1 = Braintree\CreditCard::createNoValidate([
508
- 'customerId' => $customer->id,
509
- 'number' => '5105105105105100',
510
- 'expirationDate' => '05/12'
511
- ]);
512
- $card2 = Braintree\CreditCard::createNoValidate([
513
- 'customerId' => $customer->id,
514
- 'number' => '5105105105105100',
515
- 'expirationDate' => '05/12'
516
- ]);
517
- $this->assertFalse($card2->isDefault());
518
-
519
- $queryString = $this->updateCreditCardViaTr(
520
- [
521
- 'credit_card' => [
522
- 'options' => [
523
- 'make_default' => true
524
- ]
525
- ]
526
- ],
527
- ['paymentMethodToken' => $card2->token]
528
- );
529
- $result = Braintree\CreditCard::updateFromTransparentRedirect($queryString);
530
- $this->assertFalse(Braintree\CreditCard::find($card1->token)->isDefault());
531
- $this->assertTrue(Braintree\CreditCard::find($card2->token)->isDefault());
532
- }
533
-
534
- public function testUpdateFromTransparentRedirect_andUpdateExistingBillingAddress()
535
- {
536
- $customer = Braintree\Customer::createNoValidate();
537
- $card = Braintree\CreditCard::createNoValidate([
538
- 'customerId' => $customer->id,
539
- 'number' => '5105105105105100',
540
- 'expirationDate' => '05/12',
541
- 'billingAddress' => [
542
- 'firstName' => 'Drew',
543
- 'lastName' => 'Smith',
544
- 'company' => 'Smith Co.',
545
- 'streetAddress' => '123 Old St',
546
- 'extendedAddress' => 'Suite 101',
547
- 'locality' => 'Chicago',
548
- 'region' => 'IL',
549
- 'postalCode' => '60622',
550
- 'countryName' => 'United States of America'
551
- ]
552
- ]);
553
-
554
- $queryString = $this->updateCreditCardViaTr(
555
- [],
556
- [
557
- 'paymentMethodToken' => $card->token,
558
- 'creditCard' => [
559
- 'billingAddress' => [
560
- 'streetAddress' => '123 New St',
561
- 'locality' => 'St. Louis',
562
- 'region' => 'MO',
563
- 'postalCode' => '63119',
564
- 'options' => [
565
- 'updateExisting' => True
566
- ]
567
- ]
568
- ]
569
- ]
570
- );
571
- $result = Braintree\CreditCard::updateFromTransparentRedirect($queryString);
572
- $this->assertTrue($result->success);
573
- $card = $result->creditCard;
574
- $this->assertEquals(1, sizeof(Braintree\Customer::find($customer->id)->addresses));
575
- $this->assertEquals('123 New St', $card->billingAddress->streetAddress);
576
- $this->assertEquals('St. Louis', $card->billingAddress->locality);
577
- $this->assertEquals('MO', $card->billingAddress->region);
578
- $this->assertEquals('63119', $card->billingAddress->postalCode);
579
- }
580
-
581
- public function testSale_createsASaleUsingGivenToken()
582
- {
583
- $customer = Braintree\Customer::createNoValidate([
584
- 'creditCard' => [
585
- 'number' => '5105105105105100',
586
- 'expirationDate' => '05/12'
587
- ]
588
- ]);
589
- $creditCard = $customer->creditCards[0];
590
- $result = Braintree\CreditCard::sale($creditCard->token, [
591
- 'amount' => '100.00'
592
- ]);
593
- $this->assertTrue($result->success);
594
- $this->assertEquals('100.00', $result->transaction->amount);
595
- $this->assertEquals($customer->id, $result->transaction->customerDetails->id);
596
- $this->assertEquals($creditCard->token, $result->transaction->creditCardDetails->token);
597
- }
598
-
599
- public function testSaleNoValidate_createsASaleUsingGivenToken()
600
- {
601
- $customer = Braintree\Customer::createNoValidate([
602
- 'creditCard' => [
603
- 'number' => '5105105105105100',
604
- 'expirationDate' => '05/12'
605
- ]
606
- ]);
607
- $creditCard = $customer->creditCards[0];
608
- $transaction = Braintree\CreditCard::saleNoValidate($creditCard->token, [
609
- 'amount' => '100.00'
610
- ]);
611
- $this->assertEquals('100.00', $transaction->amount);
612
- $this->assertEquals($customer->id, $transaction->customerDetails->id);
613
- $this->assertEquals($creditCard->token, $transaction->creditCardDetails->token);
614
- }
615
-
616
- public function testSaleNoValidate_createsASaleUsingGivenTokenAndCvv()
617
- {
618
- $customer = Braintree\Customer::createNoValidate([
619
- 'creditCard' => [
620
- 'number' => '5105105105105100',
621
- 'expirationDate' => '05/12'
622
- ]
623
- ]);
624
- $creditCard = $customer->creditCards[0];
625
- $transaction = Braintree\CreditCard::saleNoValidate($creditCard->token, [
626
- 'amount' => '100.00',
627
- 'creditCard' => [
628
- 'cvv' => '301'
629
- ]
630
- ]);
631
- $this->assertEquals('100.00', $transaction->amount);
632
- $this->assertEquals($customer->id, $transaction->customerDetails->id);
633
- $this->assertEquals($creditCard->token, $transaction->creditCardDetails->token);
634
- $this->assertEquals('S', $transaction->cvvResponseCode);
635
- }
636
-
637
- public function testSaleNoValidate_throwsIfInvalid()
638
- {
639
- $customer = Braintree\Customer::createNoValidate([
640
- 'creditCard' => [
641
- 'number' => '5105105105105100',
642
- 'expirationDate' => '05/12'
643
- ]
644
- ]);
645
- $creditCard = $customer->creditCards[0];
646
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
647
- Braintree\CreditCard::saleNoValidate($creditCard->token, [
648
- 'amount' => 'invalid'
649
- ]);
650
- }
651
-
652
- public function testCredit_createsACreditUsingGivenToken()
653
- {
654
- $customer = Braintree\Customer::createNoValidate([
655
- 'creditCard' => [
656
- 'number' => '5105105105105100',
657
- 'expirationDate' => '05/12'
658
- ]
659
- ]);
660
- $creditCard = $customer->creditCards[0];
661
- $result = Braintree\CreditCard::credit($creditCard->token, [
662
- 'amount' => '100.00'
663
- ]);
664
- $this->assertTrue($result->success);
665
- $this->assertEquals('100.00', $result->transaction->amount);
666
- $this->assertEquals(Braintree\Transaction::CREDIT, $result->transaction->type);
667
- $this->assertEquals($customer->id, $result->transaction->customerDetails->id);
668
- $this->assertEquals($creditCard->token, $result->transaction->creditCardDetails->token);
669
- }
670
-
671
- public function testCreditNoValidate_createsACreditUsingGivenToken()
672
- {
673
- $customer = Braintree\Customer::createNoValidate([
674
- 'creditCard' => [
675
- 'number' => '5105105105105100',
676
- 'expirationDate' => '05/12'
677
- ]
678
- ]);
679
- $creditCard = $customer->creditCards[0];
680
- $transaction = Braintree\CreditCard::creditNoValidate($creditCard->token, [
681
- 'amount' => '100.00'
682
- ]);
683
- $this->assertEquals('100.00', $transaction->amount);
684
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction->type);
685
- $this->assertEquals($customer->id, $transaction->customerDetails->id);
686
- $this->assertEquals($creditCard->token, $transaction->creditCardDetails->token);
687
- }
688
-
689
- public function testCreditNoValidate_throwsIfInvalid()
690
- {
691
- $customer = Braintree\Customer::createNoValidate([
692
- 'creditCard' => [
693
- 'number' => '5105105105105100',
694
- 'expirationDate' => '05/12'
695
- ]
696
- ]);
697
- $creditCard = $customer->creditCards[0];
698
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
699
- Braintree\CreditCard::creditNoValidate($creditCard->token, [
700
- 'amount' => 'invalid'
701
- ]);
702
- }
703
-
704
- public function testExpired()
705
- {
706
- $collection = Braintree\CreditCard::expired();
707
- $this->assertTrue($collection->maximumCount() > 1);
708
-
709
- $arr = [];
710
- foreach($collection as $creditCard) {
711
- $this->assertTrue($creditCard->isExpired());
712
- array_push($arr, $creditCard->token);
713
- }
714
- $uniqueCreditCardTokens = array_unique(array_values($arr));
715
- $this->assertEquals($collection->maximumCount(), count($uniqueCreditCardTokens));
716
- }
717
-
718
-
719
- public function testExpiringBetween()
720
- {
721
- $collection = Braintree\CreditCard::expiringBetween(
722
- mktime(0, 0, 0, 1, 1, 2010),
723
- mktime(23, 59, 59, 12, 31, 2010)
724
- );
725
- $this->assertTrue($collection->maximumCount() > 1);
726
-
727
- $arr = [];
728
- foreach($collection as $creditCard) {
729
- $this->assertEquals('2010', $creditCard->expirationYear);
730
- array_push($arr, $creditCard->token);
731
- }
732
- $uniqueCreditCardTokens = array_unique(array_values($arr));
733
- $this->assertEquals($collection->maximumCount(), count($uniqueCreditCardTokens));
734
- }
735
-
736
- public function testExpiringBetween_parsesCreditCardDetailsUnderTransactionsCorrectly()
737
- {
738
- $collection = Braintree\CreditCard::expiringBetween(
739
- mktime(0, 0, 0, 1, 1, 2010),
740
- mktime(23, 59, 59, 12, 31, 2010)
741
- );
742
- $this->assertTrue($collection->maximumCount() > 1);
743
-
744
- foreach($collection as $creditCard) {
745
- foreach($creditCard->subscriptions as $subscription) {
746
- foreach($subscription->transactions as $transaction) {
747
- $this->assertNotNull($transaction->creditCardDetails->expirationMonth);
748
- }
749
- }
750
- }
751
- }
752
-
753
- public function testFind()
754
- {
755
- $customer = Braintree\Customer::createNoValidate();
756
- $result = Braintree\CreditCard::create([
757
- 'customerId' => $customer->id,
758
- 'cardholderName' => 'Cardholder',
759
- 'number' => '5105105105105100',
760
- 'expirationDate' => '05/12'
761
- ]);
762
- $this->assertTrue($result->success);
763
- $creditCard = Braintree\CreditCard::find($result->creditCard->token);
764
- $this->assertEquals($customer->id, $creditCard->customerId);
765
- $this->assertEquals('510510', $creditCard->bin);
766
- $this->assertEquals('5100', $creditCard->last4);
767
- $this->assertEquals('Cardholder', $creditCard->cardholderName);
768
- $this->assertEquals('05/2012', $creditCard->expirationDate);
769
- $this->assertEquals([], $creditCard->subscriptions);
770
- }
771
-
772
- public function testFindReturnsAssociatedSubscriptions()
773
- {
774
- $customer = Braintree\Customer::createNoValidate();
775
- $result = Braintree\CreditCard::create([
776
- 'customerId' => $customer->id,
777
- 'cardholderName' => 'Cardholder',
778
- 'number' => '5105105105105100',
779
- 'expirationDate' => '05/12',
780
- 'billingAddress' => [
781
- 'firstName' => 'Drew',
782
- 'lastName' => 'Smith',
783
- 'company' => 'Smith Co.',
784
- 'streetAddress' => '1 E Main St',
785
- 'extendedAddress' => 'Suite 101',
786
- 'locality' => 'Chicago',
787
- 'region' => 'IL',
788
- 'postalCode' => '60622',
789
- 'countryName' => 'United States of America'
790
- ]
791
- ]);
792
- $id = strval(rand());
793
- Braintree\Subscription::create([
794
- 'id' => $id,
795
- 'paymentMethodToken' => $result->creditCard->token,
796
- 'planId' => 'integration_trialless_plan',
797
- 'price' => '1.00'
798
- ]);
799
- $creditCard = Braintree\CreditCard::find($result->creditCard->token);
800
- $this->assertEquals($id, $creditCard->subscriptions[0]->id);
801
- $this->assertEquals('integration_trialless_plan', $creditCard->subscriptions[0]->planId);
802
- $this->assertEquals('1.00', $creditCard->subscriptions[0]->price);
803
- }
804
-
805
- public function testFind_throwsIfCannotBeFound()
806
- {
807
- $this->setExpectedException('Braintree\Exception\NotFound');
808
- Braintree\CreditCard::find('invalid-token');
809
- }
810
-
811
- public function testFind_throwsUsefulErrorMessagesWhenEmpty()
812
- {
813
- $this->setExpectedException('InvalidArgumentException', 'expected credit card id to be set');
814
- Braintree\CreditCard::find('');
815
- }
816
-
817
- public function testFind_throwsUsefulErrorMessagesWhenInvalid()
818
- {
819
- $this->setExpectedException('InvalidArgumentException', '@ is an invalid credit card token');
820
- Braintree\CreditCard::find('@');
821
- }
822
-
823
- public function testFromNonce()
824
- {
825
- $customer = Braintree\Customer::createNoValidate();
826
- $http = new HttpClientApi(Braintree\Configuration::$global);
827
- $nonce = $http->nonce_for_new_card([
828
- "credit_card" => [
829
- "number" => "4009348888881881",
830
- "expirationMonth" => "11",
831
- "expirationYear" => "2099"
832
- ],
833
- "customerId" => $customer->id
834
- ]);
835
-
836
- $creditCard = Braintree\CreditCard::fromNonce($nonce);
837
-
838
- $customer = Braintree\Customer::find($customer->id);
839
- $this->assertEquals($customer->creditCards[0], $creditCard);
840
- }
841
-
842
- public function testFromNonce_ReturnsErrorWhenNoncePointsToSharedCard()
843
- {
844
- $http = new HttpClientApi(Braintree\Configuration::$global);
845
- $nonce = $http->nonce_for_new_card([
846
- "credit_card" => [
847
- "number" => "4009348888881881",
848
- "expirationMonth" => "11",
849
- "expirationYear" => "2099"
850
- ],
851
- "share" => true
852
- ]);
853
-
854
- $this->setExpectedException('Braintree\Exception\NotFound', "not found");
855
- Braintree\CreditCard::fromNonce($nonce);
856
- }
857
-
858
- public function testFromNonce_ReturnsErrorWhenNonceIsConsumed()
859
- {
860
- $customer = Braintree\Customer::createNoValidate();
861
- $http = new HttpClientApi(Braintree\Configuration::$global);
862
- $nonce = $http->nonce_for_new_card([
863
- "credit_card" => [
864
- "number" => "4009348888881881",
865
- "expirationMonth" => "11",
866
- "expirationYear" => "2099"
867
- ],
868
- "customerId" => $customer->id
869
- ]);
870
-
871
- Braintree\CreditCard::fromNonce($nonce);
872
- $this->setExpectedException('Braintree\Exception\NotFound', "consumed");
873
- Braintree\CreditCard::fromNonce($nonce);
874
- }
875
-
876
- public function testUpdate()
877
- {
878
- $customer = Braintree\Customer::createNoValidate();
879
- $createResult = Braintree\CreditCard::create([
880
- 'customerId' => $customer->id,
881
- 'cardholderName' => 'Old Cardholder',
882
- 'number' => '5105105105105100',
883
- 'expirationDate' => '05/12'
884
- ]);
885
- $this->assertTrue($createResult->success);
886
- $updateResult = Braintree\CreditCard::update($createResult->creditCard->token, [
887
- 'cardholderName' => 'New Cardholder',
888
- 'number' => '4111111111111111',
889
- 'expirationDate' => '07/14'
890
- ]);
891
- $this->assertEquals($customer->id, $updateResult->creditCard->customerId);
892
- $this->assertEquals('411111', $updateResult->creditCard->bin);
893
- $this->assertEquals('1111', $updateResult->creditCard->last4);
894
- $this->assertEquals('New Cardholder', $updateResult->creditCard->cardholderName);
895
- $this->assertEquals('07/2014', $updateResult->creditCard->expirationDate);
896
- }
897
-
898
- public function testUpdate_withCardVerification()
899
- {
900
- $customer = Braintree\Customer::createNoValidate();
901
- $initialCreditCard = Braintree\CreditCard::create([
902
- 'customerId' => $customer->id,
903
- 'number' => '5105105105105100',
904
- 'expirationDate' => '05/12'
905
- ])->creditCard;
906
-
907
- $result = Braintree\CreditCard::update($initialCreditCard->token, [
908
- 'billingAddress' => [
909
- 'region' => 'IL'
910
- ],
911
- 'options' => ['verifyCard' => true]
912
- ]);
913
- $this->assertFalse($result->success);
914
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
915
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
916
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
917
- $this->assertEquals('I', $result->creditCardVerification->cvvResponseCode);
918
- $this->assertEquals(null, $result->creditCardVerification->avsErrorResponseCode);
919
- $this->assertEquals('I', $result->creditCardVerification->avsPostalCodeResponseCode);
920
- $this->assertEquals('I', $result->creditCardVerification->avsStreetAddressResponseCode);
921
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $result->creditCardVerification->merchantAccountId);
922
- }
923
-
924
- public function testUpdate_withCardVerificationAndSpecificMerchantAccount()
925
- {
926
- $customer = Braintree\Customer::createNoValidate();
927
- $initialCreditCard = Braintree\CreditCard::create([
928
- 'customerId' => $customer->id,
929
- 'number' => '5105105105105100',
930
- 'expirationDate' => '05/12'
931
- ])->creditCard;
932
-
933
- $result = Braintree\CreditCard::update($initialCreditCard->token, [
934
- 'billingAddress' => [
935
- 'region' => 'IL'
936
- ],
937
- 'options' => [
938
- 'verificationMerchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
939
- 'verifyCard' => true
940
- ]
941
- ]);
942
- $this->assertFalse($result->success);
943
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
944
- $this->assertEquals(Test\Helper::nonDefaultMerchantAccountId(), $result->creditCardVerification->merchantAccountId);
945
- }
946
-
947
- public function testUpdate_createsNewBillingAddressByDefault()
948
- {
949
- $customer = Braintree\Customer::createNoValidate();
950
- $initialCreditCard = Braintree\CreditCard::create([
951
- 'customerId' => $customer->id,
952
- 'number' => '5105105105105100',
953
- 'expirationDate' => '05/12',
954
- 'billingAddress' => [
955
- 'streetAddress' => '123 Nigeria Ave'
956
- ]
957
- ])->creditCard;
958
-
959
- $updatedCreditCard = Braintree\CreditCard::update($initialCreditCard->token, [
960
- 'billingAddress' => [
961
- 'region' => 'IL'
962
- ]
963
- ])->creditCard;
964
- $this->assertEquals('IL', $updatedCreditCard->billingAddress->region);
965
- $this->assertNull($updatedCreditCard->billingAddress->streetAddress);
966
- $this->assertNotEquals($initialCreditCard->billingAddress->id, $updatedCreditCard->billingAddress->id);
967
- }
968
-
969
- public function testUpdate_updatesExistingBillingAddressIfUpdateExistingOptionIsTrue()
970
- {
971
- $customer = Braintree\Customer::createNoValidate();
972
- $initialCreditCard = Braintree\CreditCard::create([
973
- 'customerId' => $customer->id,
974
- 'number' => '5105105105105100',
975
- 'expirationDate' => '05/12',
976
- 'billingAddress' => [
977
- 'countryName' => 'Turkey',
978
- 'countryCodeAlpha2' => 'TR',
979
- 'countryCodeAlpha3' => 'TUR',
980
- 'countryCodeNumeric' => '792',
981
- ]
982
- ])->creditCard;
983
-
984
- $updatedCreditCard = Braintree\CreditCard::update($initialCreditCard->token, [
985
- 'billingAddress' => [
986
- 'countryName' => 'Thailand',
987
- 'countryCodeAlpha2' => 'TH',
988
- 'countryCodeAlpha3' => 'THA',
989
- 'countryCodeNumeric' => '764',
990
- 'options' => [
991
- 'updateExisting' => True
992
- ]
993
- ]
994
- ])->creditCard;
995
- $this->assertEquals('Thailand', $updatedCreditCard->billingAddress->countryName);
996
- $this->assertEquals('TH', $updatedCreditCard->billingAddress->countryCodeAlpha2);
997
- $this->assertEquals('THA', $updatedCreditCard->billingAddress->countryCodeAlpha3);
998
- $this->assertEquals('764', $updatedCreditCard->billingAddress->countryCodeNumeric);
999
- $this->assertEquals($initialCreditCard->billingAddress->id, $updatedCreditCard->billingAddress->id);
1000
- }
1001
-
1002
- public function testUpdate_canChangeToken()
1003
- {
1004
- $oldToken = strval(rand());
1005
- $newToken = strval(rand());
1006
-
1007
- $customer = Braintree\Customer::createNoValidate();
1008
- $createResult = Braintree\CreditCard::create([
1009
- 'customerId' => $customer->id,
1010
- 'token' => $oldToken,
1011
- 'number' => '5105105105105100',
1012
- 'expirationDate' => '05/12'
1013
- ]);
1014
- $this->assertTrue($createResult->success);
1015
- $updateResult = Braintree\CreditCard::update($oldToken, [
1016
- 'token' => $newToken
1017
- ]);
1018
- $this->assertEquals($customer->id, $updateResult->creditCard->customerId);
1019
- $this->assertEquals($newToken, $updateResult->creditCard->token);
1020
- $this->assertEquals($newToken, Braintree\CreditCard::find($newToken)->token);
1021
- }
1022
-
1023
- public function testUpdateNoValidate()
1024
- {
1025
- $customer = Braintree\Customer::createNoValidate();
1026
- $creditCard = Braintree\CreditCard::createNoValidate([
1027
- 'customerId' => $customer->id,
1028
- 'cardholderName' => 'Old Cardholder',
1029
- 'number' => '5105105105105100',
1030
- 'expirationDate' => '05/12'
1031
- ]);
1032
- $updatedCard = Braintree\CreditCard::updateNoValidate($creditCard->token, [
1033
- 'cardholderName' => 'New Cardholder',
1034
- 'number' => '4111111111111111',
1035
- 'expirationDate' => '07/14'
1036
- ]);
1037
- $this->assertEquals($customer->id, $updatedCard->customerId);
1038
- $this->assertEquals('411111', $updatedCard->bin);
1039
- $this->assertEquals('1111', $updatedCard->last4);
1040
- $this->assertEquals('New Cardholder', $updatedCard->cardholderName);
1041
- $this->assertEquals('07/2014', $updatedCard->expirationDate);
1042
- }
1043
-
1044
- public function testUpdateNoValidate_throwsIfInvalid()
1045
- {
1046
- $customer = Braintree\Customer::createNoValidate();
1047
- $creditCard = Braintree\CreditCard::createNoValidate([
1048
- 'customerId' => $customer->id,
1049
- 'cardholderName' => 'Old Cardholder',
1050
- 'number' => '5105105105105100',
1051
- 'expirationDate' => '05/12'
1052
- ]);
1053
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
1054
- Braintree\CreditCard::updateNoValidate($creditCard->token, [
1055
- 'number' => 'invalid',
1056
- ]);
1057
- }
1058
-
1059
- public function testUpdate_withDefault()
1060
- {
1061
- $customer = Braintree\Customer::createNoValidate();
1062
- $card1 = Braintree\CreditCard::create([
1063
- 'customerId' => $customer->id,
1064
- 'cardholderName' => 'Cardholder',
1065
- 'number' => '5105105105105100',
1066
- 'expirationDate' => '05/12'
1067
- ])->creditCard;
1068
- $card2 = Braintree\CreditCard::create([
1069
- 'customerId' => $customer->id,
1070
- 'cardholderName' => 'Cardholder',
1071
- 'number' => '5105105105105100',
1072
- 'expirationDate' => '05/12'
1073
- ])->creditCard;
1074
-
1075
- $this->assertTrue($card1->isDefault());
1076
- $this->assertFalse($card2->isDefault());
1077
-
1078
- Braintree\CreditCard::update($card2->token, [
1079
- 'options' => ['makeDefault' => true]
1080
- ])->creditCard;
1081
-
1082
- $this->assertFalse(Braintree\CreditCard::find($card1->token)->isDefault());
1083
- $this->assertTrue(Braintree\CreditCard::find($card2->token)->isDefault());
1084
- }
1085
-
1086
- public function testDelete_deletesThePaymentMethod()
1087
- {
1088
- $customer = Braintree\Customer::createNoValidate([]);
1089
- $creditCard = Braintree\CreditCard::createNoValidate([
1090
- 'customerId' => $customer->id,
1091
- 'number' => '5105105105105100',
1092
- 'expirationDate' => '05/12'
1093
- ]);
1094
- Braintree\CreditCard::find($creditCard->token);
1095
- Braintree\CreditCard::delete($creditCard->token);
1096
- $this->setExpectedException('Braintree\Exception\NotFound');
1097
- Braintree\CreditCard::find($creditCard->token);
1098
- }
1099
-
1100
- public function testGatewayRejectionOnCVV()
1101
- {
1102
- $old_merchant_id = Braintree\Configuration::merchantId();
1103
- $old_public_key = Braintree\Configuration::publicKey();
1104
- $old_private_key = Braintree\Configuration::privateKey();
1105
-
1106
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
1107
- Braintree\Configuration::publicKey('processing_rules_public_key');
1108
- Braintree\Configuration::privateKey('processing_rules_private_key');
1109
-
1110
- $customer = Braintree\Customer::createNoValidate();
1111
- $result = Braintree\CreditCard::create([
1112
- 'customerId' => $customer->id,
1113
- 'number' => '4111111111111111',
1114
- 'expirationDate' => '05/2011',
1115
- 'cvv' => '200',
1116
- 'options' => ['verifyCard' => true]
1117
- ]);
1118
-
1119
- Braintree\Configuration::merchantId($old_merchant_id);
1120
- Braintree\Configuration::publicKey($old_public_key);
1121
- Braintree\Configuration::privateKey($old_private_key);
1122
-
1123
- $this->assertFalse($result->success);
1124
- $this->assertEquals(Braintree\Transaction::CVV, $result->creditCardVerification->gatewayRejectionReason);
1125
- }
1126
-
1127
- public function testGatewayRejectionIsNullOnProcessorDecline()
1128
- {
1129
- $old_merchant_id = Braintree\Configuration::merchantId();
1130
- $old_public_key = Braintree\Configuration::publicKey();
1131
- $old_private_key = Braintree\Configuration::privateKey();
1132
-
1133
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
1134
- Braintree\Configuration::publicKey('processing_rules_public_key');
1135
- Braintree\Configuration::privateKey('processing_rules_private_key');
1136
-
1137
- $customer = Braintree\Customer::createNoValidate();
1138
- $result = Braintree\CreditCard::create([
1139
- 'customerId' => $customer->id,
1140
- 'number' => '5105105105105100',
1141
- 'expirationDate' => '05/2011',
1142
- 'cvv' => '200',
1143
- 'options' => ['verifyCard' => true]
1144
- ]);
1145
-
1146
- Braintree\Configuration::merchantId($old_merchant_id);
1147
- Braintree\Configuration::publicKey($old_public_key);
1148
- Braintree\Configuration::privateKey($old_private_key);
1149
-
1150
- $this->assertFalse($result->success);
1151
- $this->assertNull($result->creditCardVerification->gatewayRejectionReason);
1152
- }
1153
-
1154
- public function createCreditCardViaTr($regularParams, $trParams)
1155
- {
1156
- $trData = Braintree\TransparentRedirect::createCreditCardData(
1157
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
1158
- );
1159
- return Test\Helper::submitTrRequest(
1160
- Braintree\CreditCard::createCreditCardUrl(),
1161
- $regularParams,
1162
- $trData
1163
- );
1164
- }
1165
-
1166
- public function updateCreditCardViaTr($regularParams, $trParams)
1167
- {
1168
- $trData = Braintree\TransparentRedirect::updateCreditCardData(
1169
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
1170
- );
1171
- return Test\Helper::submitTrRequest(
1172
- Braintree\CreditCard::updateCreditCardUrl(),
1173
- $regularParams,
1174
- $trData
1175
- );
1176
- }
1177
-
1178
- public function testPrepaidCard()
1179
- {
1180
- $customer = Braintree\Customer::createNoValidate();
1181
- $result = Braintree\CreditCard::create([
1182
- 'customerId' => $customer->id,
1183
- 'cardholderName' => 'Cardholder',
1184
- 'number' => CardTypeIndicators::PREPAID,
1185
- 'expirationDate' => '05/12',
1186
- 'options' => ['verifyCard' => true]
1187
- ]);
1188
- $this->assertEquals(Braintree\CreditCard::PREPAID_YES, $result->creditCard->prepaid);
1189
- }
1190
-
1191
- public function testCommercialCard()
1192
- {
1193
- $customer = Braintree\Customer::createNoValidate();
1194
- $result = Braintree\CreditCard::create([
1195
- 'customerId' => $customer->id,
1196
- 'cardholderName' => 'Cardholder',
1197
- 'number' => CardTypeIndicators::COMMERCIAL,
1198
- 'expirationDate' => '05/12',
1199
- 'options' => ['verifyCard' => true]
1200
- ]);
1201
- $this->assertEquals(Braintree\CreditCard::COMMERCIAL_YES, $result->creditCard->commercial);
1202
- }
1203
-
1204
- public function testDebitCard()
1205
- {
1206
- $customer = Braintree\Customer::createNoValidate();
1207
- $result = Braintree\CreditCard::create([
1208
- 'customerId' => $customer->id,
1209
- 'cardholderName' => 'Cardholder',
1210
- 'number' => CardTypeIndicators::DEBIT,
1211
- 'expirationDate' => '05/12',
1212
- 'options' => ['verifyCard' => true]
1213
- ]);
1214
- $this->assertEquals(Braintree\CreditCard::DEBIT_YES, $result->creditCard->debit);
1215
- }
1216
-
1217
- public function testPayrollCard()
1218
- {
1219
- $customer = Braintree\Customer::createNoValidate();
1220
- $result = Braintree\CreditCard::create([
1221
- 'customerId' => $customer->id,
1222
- 'cardholderName' => 'Cardholder',
1223
- 'number' => CardTypeIndicators::PAYROLL,
1224
- 'expirationDate' => '05/12',
1225
- 'options' => ['verifyCard' => true]
1226
- ]);
1227
- $this->assertEquals(Braintree\CreditCard::PAYROLL_YES, $result->creditCard->payroll);
1228
- }
1229
-
1230
- public function testHealthCareCard()
1231
- {
1232
- $customer = Braintree\Customer::createNoValidate();
1233
- $result = Braintree\CreditCard::create([
1234
- 'customerId' => $customer->id,
1235
- 'cardholderName' => 'Cardholder',
1236
- 'number' => CardTypeIndicators::HEALTHCARE,
1237
- 'expirationDate' => '05/12',
1238
- 'options' => ['verifyCard' => true]
1239
- ]);
1240
- $this->assertEquals(Braintree\CreditCard::HEALTHCARE_YES, $result->creditCard->healthcare);
1241
- }
1242
-
1243
- public function testDurbinRegulatedCard()
1244
- {
1245
- $customer = Braintree\Customer::createNoValidate();
1246
- $result = Braintree\CreditCard::create([
1247
- 'customerId' => $customer->id,
1248
- 'cardholderName' => 'Cardholder',
1249
- 'number' => CardTypeIndicators::DURBIN_REGULATED,
1250
- 'expirationDate' => '05/12',
1251
- 'options' => ['verifyCard' => true]
1252
- ]);
1253
- $this->assertEquals(Braintree\CreditCard::DURBIN_REGULATED_YES, $result->creditCard->durbinRegulated);
1254
- }
1255
-
1256
- public function testCountryOfIssuanceCard()
1257
- {
1258
- $customer = Braintree\Customer::createNoValidate();
1259
- $result = Braintree\CreditCard::create([
1260
- 'customerId' => $customer->id,
1261
- 'cardholderName' => 'Cardholder',
1262
- 'number' => CardTypeIndicators::COUNTRY_OF_ISSUANCE,
1263
- 'expirationDate' => '05/12',
1264
- 'options' => ['verifyCard' => true]
1265
- ]);
1266
- $this->assertEquals("USA", $result->creditCard->countryOfIssuance);
1267
- }
1268
-
1269
- public function testIssuingBankCard()
1270
- {
1271
- $customer = Braintree\Customer::createNoValidate();
1272
- $result = Braintree\CreditCard::create([
1273
- 'customerId' => $customer->id,
1274
- 'cardholderName' => 'Cardholder',
1275
- 'number' => CardTypeIndicators::ISSUING_BANK,
1276
- 'expirationDate' => '05/12',
1277
- 'options' => ['verifyCard' => true]
1278
- ]);
1279
- $this->assertEquals("NETWORK ONLY", $result->creditCard->issuingBank);
1280
- }
1281
-
1282
- public function testNegativeCardTypeIndicators()
1283
- {
1284
- $customer = Braintree\Customer::createNoValidate();
1285
- $result = Braintree\CreditCard::create([
1286
- 'customerId' => $customer->id,
1287
- 'cardholderName' => 'Cardholder',
1288
- 'number' => CardTypeIndicators::NO,
1289
- 'expirationDate' => '05/12',
1290
- 'options' => ['verifyCard' => true]
1291
- ]);
1292
- $this->assertEquals(Braintree\CreditCard::PREPAID_NO, $result->creditCard->prepaid);
1293
- $this->assertEquals(Braintree\CreditCard::DURBIN_REGULATED_NO, $result->creditCard->durbinRegulated);
1294
- $this->assertEquals(Braintree\CreditCard::PAYROLL_NO, $result->creditCard->payroll);
1295
- $this->assertEquals(Braintree\CreditCard::DEBIT_NO, $result->creditCard->debit);
1296
- $this->assertEquals(Braintree\CreditCard::HEALTHCARE_NO, $result->creditCard->healthcare);
1297
- $this->assertEquals(Braintree\CreditCard::COMMERCIAL_NO, $result->creditCard->commercial);
1298
- }
1299
-
1300
- public function testUnknownCardTypeIndicators()
1301
- {
1302
- $customer = Braintree\Customer::createNoValidate();
1303
- $result = Braintree\CreditCard::create([
1304
- 'customerId' => $customer->id,
1305
- 'cardholderName' => 'Cardholder',
1306
- 'number' => CardTypeIndicators::UNKNOWN,
1307
- 'expirationDate' => '05/12',
1308
- 'options' => ['verifyCard' => true]
1309
- ]);
1310
- $this->assertEquals(Braintree\CreditCard::PREPAID_UNKNOWN, $result->creditCard->prepaid);
1311
- $this->assertEquals(Braintree\CreditCard::DURBIN_REGULATED_UNKNOWN, $result->creditCard->durbinRegulated);
1312
- $this->assertEquals(Braintree\CreditCard::PAYROLL_UNKNOWN, $result->creditCard->payroll);
1313
- $this->assertEquals(Braintree\CreditCard::DEBIT_UNKNOWN, $result->creditCard->debit);
1314
- $this->assertEquals(Braintree\CreditCard::HEALTHCARE_UNKNOWN, $result->creditCard->healthcare);
1315
- $this->assertEquals(Braintree\CreditCard::COMMERCIAL_UNKNOWN, $result->creditCard->commercial);
1316
- $this->assertEquals(Braintree\CreditCard::COUNTRY_OF_ISSUANCE_UNKNOWN, $result->creditCard->countryOfIssuance);
1317
- $this->assertEquals(Braintree\CreditCard::ISSUING_BANK_UNKNOWN, $result->creditCard->issuingBank);
1318
- }
1319
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/CreditCardVerificationAdvancedSearchTest.php DELETED
@@ -1,259 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class CreditCardVerificationAdvancedSearchTest extends Setup
11
- {
12
- public function test_searchOnTextFields()
13
- {
14
- $searchCriteria = [
15
- 'creditCardCardholderName' => 'Tim Toole',
16
- 'creditCardExpirationDate' => '05/2010',
17
- 'creditCardNumber' => Braintree\Test\CreditCardNumbers::$failsSandboxVerification['Visa'],
18
- 'billingAddressDetailsPostalCode' => '90210',
19
- ];
20
- $result = Braintree\Customer::create([
21
- 'creditCard' => [
22
- 'cardholderName' => $searchCriteria['creditCardCardholderName'],
23
- 'number' => $searchCriteria['creditCardNumber'],
24
- 'expirationDate' => $searchCriteria['creditCardExpirationDate'],
25
- 'billingAddress' => [
26
- 'postalCode' => $searchCriteria['billingAddressDetailsPostalCode']
27
- ],
28
- 'options' => ['verifyCard' => true],
29
- ],
30
- ]);
31
- $verification = $result->creditCardVerification;
32
-
33
- $query = [Braintree\CreditCardVerificationSearch::id()->is($verification->id)];
34
- foreach ($searchCriteria AS $criterion => $value) {
35
- $query[] = Braintree\CreditCardVerificationSearch::$criterion()->is($value);
36
- }
37
-
38
- $collection = Braintree\CreditCardVerification::search($query);
39
- $this->assertEquals(1, $collection->maximumCount());
40
- $this->assertEquals($result->creditCardVerification->id, $collection->firstItem()->id);
41
-
42
- foreach ($searchCriteria AS $criterion => $value) {
43
- $collection = Braintree\CreditCardVerification::search([
44
- Braintree\CreditCardVerificationSearch::$criterion()->is($value),
45
- Braintree\CreditCardVerificationSearch::id()->is($result->creditCardVerification->id)
46
- ]);
47
- $this->assertEquals(1, $collection->maximumCount());
48
- $this->assertEquals($result->creditCardVerification->id, $collection->firstItem()->id);
49
-
50
- $collection = Braintree\CreditCardVerification::search([
51
- Braintree\CreditCardVerificationSearch::$criterion()->is('invalid_attribute'),
52
- Braintree\CreditCardVerificationSearch::id()->is($result->creditCardVerification->id)
53
- ]);
54
- $this->assertEquals(0, $collection->maximumCount());
55
- }
56
- }
57
-
58
- public function test_searchOnSuccessfulCustomerAndPaymentFields()
59
- {
60
- $customerId = uniqid();
61
- $searchCriteria = [
62
- 'customerId' => $customerId,
63
- 'customerEmail' => $customerId . 'sandworm@example.com',
64
- 'paymentMethodToken' => $customerId . 'token',
65
- ];
66
- $result = Braintree\Customer::create([
67
- 'id' => $customerId,
68
- 'email' => $searchCriteria['customerEmail'],
69
- 'creditCard' => [
70
- 'token' => $searchCriteria['paymentMethodToken'],
71
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
72
- 'expirationDate' => '05/2017',
73
- 'options' => ['verifyCard' => true]
74
- ]
75
- ]);
76
- $customer = $result->customer;
77
-
78
- $query = [];
79
- foreach ($searchCriteria AS $criterion => $value) {
80
- $query[] = Braintree\CreditCardVerificationSearch::$criterion()->is($value);
81
- }
82
-
83
- $collection = Braintree\CreditCardVerification::search($query);
84
- $this->assertEquals(1, $collection->maximumCount());
85
-
86
- foreach ($searchCriteria AS $criterion => $value) {
87
- $collection = Braintree\CreditCardVerification::search([
88
- Braintree\CreditCardVerificationSearch::$criterion()->is($value),
89
- ]);
90
- $this->assertEquals(1, $collection->maximumCount());
91
-
92
- $collection = Braintree\CreditCardVerification::search([
93
- Braintree\CreditCardVerificationSearch::$criterion()->is('invalid_attribute'),
94
- ]);
95
- $this->assertEquals(0, $collection->maximumCount());
96
- }
97
- }
98
-
99
- public function testGateway_searchEmpty()
100
- {
101
- $query = [];
102
- $query[] = Braintree\CreditCardVerificationSearch::creditCardCardholderName()->is('Not Found');
103
-
104
- $gateway = new Braintree\Gateway([
105
- 'environment' => 'development',
106
- 'merchantId' => 'integration_merchant_id',
107
- 'publicKey' => 'integration_public_key',
108
- 'privateKey' => 'integration_private_key'
109
- ]);
110
- $collection = $gateway->creditCardVerification()->search($query);
111
-
112
- $this->assertEquals(0, $collection->maximumCount());
113
- }
114
-
115
- public function test_createdAt()
116
- {
117
- $result = Braintree\Customer::create([
118
- 'creditCard' => [
119
- 'cardholderName' => 'Joe Smith',
120
- 'number' => '4000111111111115',
121
- 'expirationDate' => '12/2016',
122
- 'options' => ['verifyCard' => true],
123
- ],
124
- ]);
125
-
126
- $verification = $result->creditCardVerification;
127
-
128
- $past = clone $verification->createdAt;
129
- $past->modify('-1 hour');
130
- $future = clone $verification->createdAt;
131
- $future->modify('+1 hour');
132
-
133
- $collection = Braintree\CreditCardVerification::search([
134
- Braintree\CreditCardVerificationSearch::id()->is($verification->id),
135
- Braintree\CreditCardVerificationSearch::createdAt()->between($past, $future)
136
- ]);
137
- $this->assertEquals(1, $collection->maximumCount());
138
- $this->assertEquals($verification->id, $collection->firstItem()->id);
139
-
140
- $collection = Braintree\CreditCardVerification::search([
141
- Braintree\CreditCardVerificationSearch::id()->is($verification->id),
142
- Braintree\CreditCardVerificationSearch::createdAt()->lessThanOrEqualTo($future)
143
- ]);
144
- $this->assertEquals(1, $collection->maximumCount());
145
- $this->assertEquals($verification->id, $collection->firstItem()->id);
146
-
147
- $collection = Braintree\CreditCardVerification::search([
148
- Braintree\CreditCardVerificationSearch::id()->is($verification->id),
149
- Braintree\CreditCardVerificationSearch::createdAt()->greaterThanOrEqualTo($past)
150
- ]);
151
- $this->assertEquals(1, $collection->maximumCount());
152
- $this->assertEquals($verification->id, $collection->firstItem()->id);
153
- }
154
-
155
- public function test_multipleValueNode_ids()
156
- {
157
- $result = Braintree\Customer::create([
158
- 'creditCard' => [
159
- 'cardholderName' => 'Joe Smith',
160
- 'number' => '4000111111111115',
161
- 'expirationDate' => '12/2016',
162
- 'options' => ['verifyCard' => true],
163
- ],
164
- ]);
165
-
166
- $creditCardVerification = $result->creditCardVerification;
167
-
168
- $collection = Braintree\CreditCardVerification::search([
169
- Braintree\CreditCardVerificationSearch::ids()->is($creditCardVerification->id)
170
- ]);
171
- $this->assertEquals(1, $collection->maximumCount());
172
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
173
-
174
- $collection = Braintree\CreditCardVerification::search([
175
- Braintree\CreditCardVerificationSearch::ids()->in(
176
- [$creditCardVerification->id,'1234']
177
- )
178
- ]);
179
- $this->assertEquals(1, $collection->maximumCount());
180
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
181
-
182
- $collection = Braintree\CreditCardVerification::search([
183
- Braintree\CreditCardVerificationSearch::ids()->is('1234')
184
- ]);
185
- $this->assertEquals(0, $collection->maximumCount());
186
- }
187
-
188
- public function test_multipleValueNode_creditCardType()
189
- {
190
- $result = Braintree\Customer::create([
191
- 'creditCard' => [
192
- 'cardholderName' => 'Joe Smith',
193
- 'number' => '4000111111111115',
194
- 'expirationDate' => '12/2016',
195
- 'options' => ['verifyCard' => true],
196
- ],
197
- ]);
198
-
199
- $creditCardVerification = $result->creditCardVerification;
200
-
201
- $collection = Braintree\CreditCardVerification::search([
202
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
203
- Braintree\CreditCardVerificationSearch::creditCardCardType()->is($creditCardVerification->creditCard['cardType'])
204
- ]);
205
- $this->assertEquals(1, $collection->maximumCount());
206
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
207
-
208
- $collection = Braintree\CreditCardVerification::search([
209
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
210
- Braintree\CreditCardVerificationSearch::creditCardCardType()->in(
211
- [$creditCardVerification->creditCard['cardType'], Braintree\CreditCard::CHINA_UNION_PAY]
212
- )
213
- ]);
214
- $this->assertEquals(1, $collection->maximumCount());
215
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
216
-
217
- $collection = Braintree\CreditCardVerification::search([
218
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
219
- Braintree\CreditCardVerificationSearch::creditCardCardType()->is(Braintree\CreditCard::CHINA_UNION_PAY)
220
- ]);
221
- $this->assertEquals(0, $collection->maximumCount());
222
- }
223
-
224
- public function test_multipleValueNode_status()
225
- {
226
- $result = Braintree\Customer::create([
227
- 'creditCard' => [
228
- 'cardholderName' => 'Joe Smith',
229
- 'number' => '4000111111111115',
230
- 'expirationDate' => '12/2016',
231
- 'options' => ['verifyCard' => true],
232
- ],
233
- ]);
234
-
235
- $creditCardVerification = $result->creditCardVerification;
236
-
237
- $collection = Braintree\CreditCardVerification::search([
238
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
239
- Braintree\CreditCardVerificationSearch::status()->is($creditCardVerification->status)
240
- ]);
241
- $this->assertEquals(1, $collection->maximumCount());
242
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
243
-
244
- $collection = Braintree\CreditCardVerification::search([
245
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
246
- Braintree\CreditCardVerificationSearch::status()->in(
247
- [$creditCardVerification->status, Braintree\Result\CreditCardVerification::VERIFIED]
248
- )
249
- ]);
250
- $this->assertEquals(1, $collection->maximumCount());
251
- $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
252
-
253
- $collection = Braintree\CreditCardVerification::search([
254
- Braintree\CreditCardVerificationSearch::id()->is($creditCardVerification->id),
255
- Braintree\CreditCardVerificationSearch::status()->is(Braintree\Result\CreditCardVerification::VERIFIED)
256
- ]);
257
- $this->assertEquals(0, $collection->maximumCount());
258
- }
259
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/CreditCardVerificationTest.php DELETED
@@ -1,56 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class CreditCardVerificationTest extends Setup
11
- {
12
- public function test_createWithSuccessfulResponse()
13
- {
14
- $result = Braintree\CreditCardVerification::create([
15
- 'creditCard' => [
16
- 'number' => '4111111111111111',
17
- 'expirationDate' => '05/2011',
18
- ],
19
- ]);
20
- $this->assertTrue($result->success);
21
- }
22
-
23
- public function test_createWithUnsuccessfulResponse()
24
- {
25
- $result = Braintree\CreditCardVerification::create([
26
- 'creditCard' => [
27
- 'number' => Braintree\Test\CreditCardNumbers::$failsSandboxVerification['Visa'],
28
- 'expirationDate' => '05/2011',
29
- ],
30
- ]);
31
- $this->assertFalse($result->success);
32
- $this->assertEquals($result->verification->status, Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED);
33
-
34
- $verification = $result->verification;
35
-
36
- $this->assertEquals($verification->processorResponseCode, '2000');
37
- $this->assertEquals($verification->processorResponseText, 'Do Not Honor');
38
- }
39
-
40
- public function test_createWithInvalidRequest()
41
- {
42
- $result = Braintree\CreditCardVerification::create([
43
- 'creditCard' => [
44
- 'number' => Braintree\Test\CreditCardNumbers::$failsSandboxVerification['Visa'],
45
- 'expirationDate' => '05/2011',
46
- ],
47
- 'options' => [
48
- 'amount' => '-5.00'
49
- ],
50
- ]);
51
- $this->assertFalse($result->success);
52
-
53
- $amountErrors = $result->errors->forKey('verification')->forKey('options')->onAttribute('amount');
54
- $this->assertEquals(Braintree\Error\Codes::VERIFICATION_OPTIONS_AMOUNT_CANNOT_BE_NEGATIVE, $amountErrors[0]->code);
55
- }
56
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/CustomerAdvancedSearchTest.php DELETED
@@ -1,199 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class CustomerAdvancedSearchTest extends Setup
10
- {
11
- public function test_noMatches()
12
- {
13
- $collection = Braintree\Customer::search([
14
- Braintree\CustomerSearch::company()->is('badname')
15
- ]);
16
-
17
- $this->assertEquals(0, $collection->maximumCount());
18
- }
19
-
20
- public function test_noRequestsWhenIterating()
21
- {
22
- $resultsReturned = false;
23
- $collection = Braintree\Customer::search([
24
- Braintree\CustomerSearch::firstName()->is('badname')
25
- ]);
26
-
27
- foreach($collection as $customer) {
28
- $resultsReturned = true;
29
- break;
30
- }
31
-
32
- $this->assertSame(0, $collection->maximumCount());
33
- $this->assertEquals(false, $resultsReturned);
34
- }
35
-
36
- public function test_findDuplicateCardsGivenPaymentMethodToken()
37
- {
38
- $creditCardRequest = ['number' => '63049580000009', 'expirationDate' => '05/2012'];
39
-
40
- $jim = Braintree\Customer::create(['firstName' => 'Jim', 'creditCard' => $creditCardRequest])->customer;
41
- $joe = Braintree\Customer::create(['firstName' => 'Joe', 'creditCard' => $creditCardRequest])->customer;
42
-
43
- $query = [Braintree\CustomerSearch::paymentMethodTokenWithDuplicates()->is($jim->creditCards[0]->token)];
44
- $collection = Braintree\Customer::search($query);
45
-
46
- $customerIds = [];
47
- foreach($collection as $customer)
48
- {
49
- $customerIds[] = $customer->id;
50
- }
51
-
52
- $this->assertTrue(in_array($jim->id, $customerIds));
53
- $this->assertTrue(in_array($joe->id, $customerIds));
54
- }
55
-
56
- public function test_searchOnTextFields()
57
- {
58
- $token = 'cctoken' . rand();
59
-
60
- $search_criteria = [
61
- 'firstName' => 'Timmy',
62
- 'lastName' => 'OToole',
63
- 'company' => 'OToole and Son(s)' . rand(),
64
- 'email' => 'timmy@example.com',
65
- 'website' => 'http://example.com',
66
- 'phone' => '3145551234',
67
- 'fax' => '3145551235',
68
- 'cardholderName' => 'Tim Toole',
69
- 'creditCardExpirationDate' => '05/2010',
70
- 'creditCardNumber' => '4111111111111111',
71
- 'paymentMethodToken' => $token,
72
- 'addressFirstName' => 'Thomas',
73
- 'addressLastName' => 'Otool',
74
- 'addressStreetAddress' => '1 E Main St',
75
- 'addressExtendedAddress' => 'Suite 3',
76
- 'addressLocality' => 'Chicago',
77
- 'addressRegion' => 'Illinois',
78
- 'addressPostalCode' => '60622',
79
- 'addressCountryName' => 'United States of America'
80
- ];
81
-
82
- $customer = Braintree\Customer::createNoValidate([
83
- 'firstName' => $search_criteria['firstName'],
84
- 'lastName' => $search_criteria['lastName'],
85
- 'company' => $search_criteria['company'],
86
- 'email' => $search_criteria['email'],
87
- 'fax' => $search_criteria['fax'],
88
- 'phone' => $search_criteria['phone'],
89
- 'website' => $search_criteria['website'],
90
- 'creditCard' => [
91
- 'cardholderName' => 'Tim Toole',
92
- 'number' => '4111111111111111',
93
- 'expirationDate' => $search_criteria['creditCardExpirationDate'],
94
- 'token' => $token,
95
- 'billingAddress' => [
96
- 'firstName' => $search_criteria['addressFirstName'],
97
- 'lastName' => $search_criteria['addressLastName'],
98
- 'streetAddress' => $search_criteria['addressStreetAddress'],
99
- 'extendedAddress' => $search_criteria['addressExtendedAddress'],
100
- 'locality' => $search_criteria['addressLocality'],
101
- 'region' => $search_criteria['addressRegion'],
102
- 'postalCode' => $search_criteria['addressPostalCode'],
103
- 'countryName' => 'United States of America'
104
- ]
105
- ]
106
- ]);
107
-
108
- $query = [Braintree\CustomerSearch::id()->is($customer->id)];
109
- foreach ($search_criteria AS $criterion => $value) {
110
- $query[] = Braintree\CustomerSearch::$criterion()->is($value);
111
- }
112
-
113
- $collection = Braintree\Customer::search($query);
114
-
115
- $this->assertEquals(1, $collection->maximumCount());
116
- $this->assertEquals($customer->id, $collection->firstItem()->id);
117
-
118
- foreach ($search_criteria AS $criterion => $value) {
119
- $collection = Braintree\Customer::search([
120
- Braintree\CustomerSearch::$criterion()->is($value),
121
- Braintree\CustomerSearch::id()->is($customer->id),
122
- ]);
123
- $this->assertEquals(1, $collection->maximumCount());
124
- $this->assertEquals($customer->id, $collection->firstItem()->id);
125
-
126
- $collection = Braintree\Customer::search([
127
- Braintree\CustomerSearch::$criterion()->is('invalid_attribute'),
128
- Braintree\CustomerSearch::id()->is($customer->id),
129
- ]);
130
- $this->assertEquals(0, $collection->maximumCount());
131
- }
132
- }
133
-
134
- public function test_createdAt()
135
- {
136
- $customer = Braintree\Customer::createNoValidate();
137
-
138
- $past = clone $customer->createdAt;
139
- $past->modify("-1 hour");
140
- $future = clone $customer->createdAt;
141
- $future->modify("+1 hour");
142
-
143
- $collection = Braintree\Customer::search([
144
- Braintree\CustomerSearch::id()->is($customer->id),
145
- Braintree\CustomerSearch::createdAt()->between($past, $future),
146
- ]);
147
- $this->assertEquals(1, $collection->maximumCount());
148
- $this->assertEquals($customer->id, $collection->firstItem()->id);
149
-
150
- $collection = Braintree\Customer::search([
151
- Braintree\CustomerSearch::id()->is($customer->id),
152
- Braintree\CustomerSearch::createdAt()->lessThanOrEqualTo($future),
153
- ]);
154
- $this->assertEquals(1, $collection->maximumCount());
155
- $this->assertEquals($customer->id, $collection->firstItem()->id);
156
-
157
- $collection = Braintree\Customer::search([
158
- Braintree\CustomerSearch::id()->is($customer->id),
159
- Braintree\CustomerSearch::createdAt()->greaterThanOrEqualTo($past),
160
- ]);
161
- $this->assertEquals(1, $collection->maximumCount());
162
- $this->assertEquals($customer->id, $collection->firstItem()->id);
163
- }
164
-
165
- public function test_paypalAccountEmail()
166
- {
167
- $http = new HttpClientApi(Braintree\Configuration::$global);
168
- $nonce = $http->nonceForPayPalAccount([
169
- 'paypal_account' => [
170
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
171
- ]
172
- ]);
173
-
174
- $customerId = 'UNIQUE_CUSTOMER_ID-' . strval(rand());
175
- $customerResult = Braintree\Customer::create([
176
- 'paymentMethodNonce' => $nonce,
177
- 'id' => $customerId
178
- ]);
179
-
180
- $this->assertTrue($customerResult->success);
181
-
182
- $customer = $customerResult->customer;
183
-
184
- $collection = Braintree\Customer::search([
185
- Braintree\CustomerSearch::id()->is($customer->id),
186
- Braintree\CustomerSearch::paypalAccountEmail()->is('jane.doe@example.com')
187
- ]);
188
- $this->assertEquals(1, $collection->maximumCount());
189
- $this->assertEquals($customer->id, $collection->firstItem()->id);
190
- }
191
-
192
- public function test_throwsIfNoOperatorNodeGiven()
193
- {
194
- $this->setExpectedException('InvalidArgumentException', 'Operator must be provided');
195
- Braintree\Customer::search([
196
- Braintree\CustomerSearch::creditCardExpirationDate()
197
- ]);
198
- }
199
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/CustomerTest.php DELETED
@@ -1,1259 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class CustomerTest extends Setup
11
- {
12
- public function testAll_smokeTest()
13
- {
14
- $all = Braintree\Customer::all();
15
- $this->assertTrue($all->maximumCount() > 0);
16
- }
17
-
18
- public function testAllWithManyResults()
19
- {
20
- $collection = Braintree\Customer::all();
21
- $this->assertTrue($collection->maximumCount() > 1);
22
- $customer = $collection->firstItem();
23
-
24
- $this->assertTrue(strlen($customer->id) > 0);
25
- $this->assertTrue($customer instanceof Braintree\Customer);
26
- }
27
-
28
- public function testCreate()
29
- {
30
- $result = Braintree\Customer::create([
31
- 'firstName' => 'Mike',
32
- 'lastName' => 'Jones',
33
- 'company' => 'Jones Co.',
34
- 'email' => 'mike.jones@example.com',
35
- 'phone' => '419.555.1234',
36
- 'fax' => '419.555.1235',
37
- 'website' => 'http://example.com'
38
- ]);
39
- $this->assertEquals(true, $result->success);
40
- $customer = $result->customer;
41
- $this->assertEquals('Mike', $customer->firstName);
42
- $this->assertEquals('Jones', $customer->lastName);
43
- $this->assertEquals('Jones Co.', $customer->company);
44
- $this->assertEquals('mike.jones@example.com', $customer->email);
45
- $this->assertEquals('419.555.1234', $customer->phone);
46
- $this->assertEquals('419.555.1235', $customer->fax);
47
- $this->assertEquals('http://example.com', $customer->website);
48
- $this->assertNotNull($customer->merchantId);
49
- }
50
-
51
- public function testCreateWithIdOfZero()
52
- {
53
- $result = Braintree\Customer::create([
54
- 'id' => '0'
55
- ]);
56
-
57
- $this->assertEquals(true, $result->success);
58
- $this->assertEquals($result->customer->id, '0');
59
- $customer = Braintree\Customer::find('0');
60
-
61
- $this->assertEquals('0', $customer->id);
62
-
63
- Braintree\Customer::delete('0');
64
- }
65
-
66
- public function testGatewayCreate()
67
- {
68
- $gateway = new Braintree\Gateway([
69
- 'environment' => 'development',
70
- 'merchantId' => 'integration_merchant_id',
71
- 'publicKey' => 'integration_public_key',
72
- 'privateKey' => 'integration_private_key'
73
- ]);
74
- $result = $gateway->customer()->create([
75
- 'firstName' => 'Mike',
76
- 'lastName' => 'Jones',
77
- ]);
78
- $this->assertEquals(true, $result->success);
79
- $customer = $result->customer;
80
- $this->assertEquals('Mike', $customer->firstName);
81
- $this->assertEquals('Jones', $customer->lastName);
82
- $this->assertNotNull($customer->merchantId);
83
- }
84
-
85
- public function testCreateWithAccessToken()
86
- {
87
- $credentials = Test\Braintree\OAuthTestHelper::createCredentials([
88
- 'clientId' => 'client_id$development$integration_client_id',
89
- 'clientSecret' => 'client_secret$development$integration_client_secret',
90
- 'merchantId' => 'integration_merchant_id',
91
- ]);
92
-
93
- $gateway = new Braintree\Gateway([
94
- 'accessToken' => $credentials->accessToken,
95
- ]);
96
-
97
- $result = $gateway->customer()->create([
98
- 'firstName' => 'Mike',
99
- 'lastName' => 'Jones',
100
- ]);
101
- $this->assertEquals(true, $result->success);
102
- $customer = $result->customer;
103
- $this->assertEquals('Mike', $customer->firstName);
104
- $this->assertEquals('Jones', $customer->lastName);
105
- $this->assertNotNull($customer->merchantId);
106
- }
107
-
108
- public function testCreateCustomerWithCardUsingNonce()
109
- {
110
- $http = new HttpClientApi(Braintree\Configuration::$global);
111
- $nonce = $http->nonce_for_new_card([
112
- "creditCard" => [
113
- "number" => "4111111111111111",
114
- "expirationMonth" => "11",
115
- "expirationYear" => "2099"
116
- ],
117
- "share" => true
118
- ]);
119
-
120
- $result = Braintree\Customer::create([
121
- 'creditCard' => [
122
- 'paymentMethodNonce' => $nonce
123
- ]
124
- ]);
125
-
126
- $this->assertTrue($result->success);
127
- $this->assertSame("411111", $result->customer->creditCards[0]->bin);
128
- $this->assertSame("1111", $result->customer->creditCards[0]->last4);
129
- }
130
-
131
- public function testCreateCustomerWithApplePayCard()
132
- {
133
- $nonce = Braintree\Test\Nonces::$applePayVisa;
134
- $result = Braintree\Customer::create([
135
- 'paymentMethodNonce' => $nonce
136
- ]);
137
- $this->assertTrue($result->success);
138
- $customer = $result->customer;
139
- $this->assertNotNull($customer->applePayCards[0]);
140
- $this->assertNotNull($customer->paymentMethods[0]);
141
- }
142
-
143
- public function testCreateCustomerWithAndroidPayProxyCard()
144
- {
145
- $nonce = Braintree\Test\Nonces::$androidPayDiscover;
146
- $result = Braintree\Customer::create([
147
- 'paymentMethodNonce' => $nonce
148
- ]);
149
- $this->assertTrue($result->success);
150
- $customer = $result->customer;
151
- $this->assertNotNull($customer->androidPayCards[0]);
152
- $this->assertNotNull($customer->paymentMethods[0]);
153
- $androidPayCard = $customer->androidPayCards[0];
154
- $this->assertTrue($androidPayCard instanceof Braintree\AndroidPayCard);
155
- $this->assertNotNull($androidPayCard->token);
156
- $this->assertNotNull($androidPayCard->expirationYear);
157
- }
158
-
159
- public function testCreateCustomerWithAndroidPayNetworkToken()
160
- {
161
- $nonce = Braintree\Test\Nonces::$androidPayMasterCard;
162
- $result = Braintree\Customer::create([
163
- 'paymentMethodNonce' => $nonce
164
- ]);
165
- $this->assertTrue($result->success);
166
- $customer = $result->customer;
167
- $this->assertNotNull($customer->androidPayCards[0]);
168
- $this->assertNotNull($customer->paymentMethods[0]);
169
- $androidPayCard = $customer->androidPayCards[0];
170
- $this->assertTrue($androidPayCard instanceof Braintree\AndroidPayCard);
171
- $this->assertNotNull($androidPayCard->token);
172
- $this->assertNotNull($androidPayCard->expirationYear);
173
- }
174
-
175
- public function testCreateCustomerWithAmexExpressCheckoutCard()
176
- {
177
- $nonce = Braintree\Test\Nonces::$amexExpressCheckout;
178
- $result = Braintree\Customer::create([
179
- 'paymentMethodNonce' => $nonce
180
- ]);
181
- $this->assertTrue($result->success);
182
- $customer = $result->customer;
183
- $this->assertNotNull($customer->amexExpressCheckoutCards[0]);
184
- $this->assertNotNull($customer->paymentMethods[0]);
185
- $amexExpressCheckoutCard = $customer->amexExpressCheckoutCards[0];
186
- $this->assertTrue($amexExpressCheckoutCard instanceof Braintree\AmexExpressCheckoutCard);
187
- $this->assertNotNull($amexExpressCheckoutCard->token);
188
- $this->assertNotNull($amexExpressCheckoutCard->expirationYear);
189
- }
190
-
191
- public function testCreateCustomerWithVenmoAccount()
192
- {
193
- $nonce = Braintree\Test\Nonces::$venmoAccount;
194
- $result = Braintree\Customer::create(array(
195
- 'paymentMethodNonce' => $nonce
196
- ));
197
- $this->assertTrue($result->success);
198
- $customer = $result->customer;
199
- $this->assertNotNull($customer->venmoAccounts[0]);
200
- $this->assertNotNull($customer->paymentMethods[0]);
201
- $venmoAccount = $customer->venmoAccounts[0];
202
- $this->assertTrue($venmoAccount instanceof Braintree\VenmoAccount);
203
- $this->assertNotNull($venmoAccount->token);
204
- $this->assertNotNull($venmoAccount->username);
205
- $this->assertNotNull($venmoAccount->venmoUserId);
206
- }
207
-
208
- public function testCreateCustomerWithCoinbase()
209
- {
210
- $nonce = Braintree\Test\Nonces::$coinbase;
211
- $result = Braintree\Customer::create([
212
- 'paymentMethodNonce' => $nonce
213
- ]);
214
- $this->assertTrue($result->success);
215
- $customer = $result->customer;
216
- $this->assertNotNull($customer->coinbaseAccounts[0]);
217
- $this->assertNotNull($customer->coinbaseAccounts[0]->userId);
218
- $this->assertNotNull($customer->coinbaseAccounts[0]->userName);
219
- $this->assertNotNull($customer->coinbaseAccounts[0]->userEmail);
220
- $this->assertNotNull($customer->paymentMethods[0]);
221
- }
222
-
223
- public function testCreate_withUnicode()
224
- {
225
- $result = Braintree\Customer::create([
226
- 'firstName' => "Здравствуйте",
227
- 'lastName' => 'Jones',
228
- 'company' => 'Jones Co.',
229
- 'email' => 'mike.jones@example.com',
230
- 'phone' => '419.555.1234',
231
- 'fax' => '419.555.1235',
232
- 'website' => 'http://example.com'
233
- ]);
234
- $this->assertEquals(true, $result->success);
235
- $customer = $result->customer;
236
- $this->assertEquals("Здравствуйте", $customer->firstName);
237
- $this->assertEquals('Jones', $customer->lastName);
238
- $this->assertEquals('Jones Co.', $customer->company);
239
- $this->assertEquals('mike.jones@example.com', $customer->email);
240
- $this->assertEquals('419.555.1234', $customer->phone);
241
- $this->assertEquals('419.555.1235', $customer->fax);
242
- $this->assertEquals('http://example.com', $customer->website);
243
- $this->assertNotNull($customer->merchantId);
244
- }
245
-
246
- public function testCreate_withCountry()
247
- {
248
- $result = Braintree\Customer::create([
249
- 'firstName' => 'Bat',
250
- 'lastName' => 'Manderson',
251
- 'creditCard' => [
252
- 'number' => '5105105105105100',
253
- 'expirationDate' => '05/12',
254
- 'billingAddress' => [
255
- 'countryName' => 'Gabon',
256
- 'countryCodeAlpha2' => 'GA',
257
- 'countryCodeAlpha3' => 'GAB',
258
- 'countryCodeNumeric' => '266'
259
- ]
260
- ]
261
- ]);
262
- $this->assertEquals(true, $result->success);
263
- $customer = $result->customer;
264
- $this->assertEquals('Gabon', $customer->creditCards[0]->billingAddress->countryName);
265
- $this->assertEquals('GA', $customer->creditCards[0]->billingAddress->countryCodeAlpha2);
266
- $this->assertEquals('GAB', $customer->creditCards[0]->billingAddress->countryCodeAlpha3);
267
- $this->assertEquals('266', $customer->creditCards[0]->billingAddress->countryCodeNumeric);
268
- $this->assertEquals(1, preg_match('/\A\w{32}\z/', $customer->creditCards[0]->uniqueNumberIdentifier));
269
- }
270
-
271
- public function testCreate_withVenmoSdkSession()
272
- {
273
- $result = Braintree\Customer::create([
274
- 'firstName' => 'Bat',
275
- 'lastName' => 'Manderson',
276
- 'creditCard' => [
277
- 'number' => '5105105105105100',
278
- 'expirationDate' => '05/12',
279
- 'options' => [
280
- 'venmoSdkSession' => Braintree\Test\VenmoSdk::getTestSession()
281
- ]
282
- ]
283
- ]);
284
- $this->assertEquals(true, $result->success);
285
- $customer = $result->customer;
286
- $this->assertEquals(true, $customer->creditCards[0]->venmoSdk);
287
- }
288
-
289
- public function testCreate_withVenmoSdkPaymentMethodCode()
290
- {
291
- $result = Braintree\Customer::create([
292
- 'firstName' => 'Bat',
293
- 'lastName' => 'Manderson',
294
- 'creditCard' => [
295
- 'venmoSdkPaymentMethodCode' => Braintree\Test\VenmoSdk::$visaPaymentMethodCode
296
- ],
297
- ]);
298
- $this->assertEquals(true, $result->success);
299
- $customer = $result->customer;
300
- $this->assertEquals("411111", $customer->creditCards[0]->bin);
301
- }
302
-
303
- public function testCreate_blankCustomer()
304
- {
305
- $result = Braintree\Customer::create();
306
- $this->assertEquals(true, $result->success);
307
- $this->assertNotNull($result->customer->id);
308
-
309
- $result = Braintree\Customer::create([]);
310
- $this->assertEquals(true, $result->success);
311
- $this->assertNotNull($result->customer->id);
312
- }
313
-
314
- public function testCreate_withSpecialChars()
315
- {
316
- $result = Braintree\Customer::create(['firstName' => '<>&"\'']);
317
- $this->assertEquals(true, $result->success);
318
- $this->assertEquals('<>&"\'', $result->customer->firstName);
319
- }
320
-
321
- public function testCreate_withCustomFields()
322
- {
323
- $result = Braintree\Customer::create([
324
- 'firstName' => 'Mike',
325
- 'customFields' => [
326
- 'store_me' => 'some custom value'
327
- ]
328
- ]);
329
- $this->assertEquals(true, $result->success);
330
- $customFields = $result->customer->customFields;
331
- $this->assertEquals('some custom value', $customFields['store_me']);
332
- }
333
-
334
- public function testCreate_withFraudParams()
335
- {
336
- $result = Braintree\Customer::create([
337
- 'firstName' => 'Mike',
338
- 'creditCard' => [
339
- 'number' => '5105105105105100',
340
- 'expirationDate' => '05/12',
341
- 'cvv' => '123',
342
- 'cardholderName' => 'Mike Jones',
343
- 'deviceSessionId' => 'abc123',
344
- 'fraudMerchantId' => '456'
345
- ]
346
- ]);
347
- $this->assertEquals(true, $result->success);
348
- }
349
-
350
- public function testCreate_withCreditCard()
351
- {
352
- $result = Braintree\Customer::create([
353
- 'firstName' => 'Mike',
354
- 'lastName' => 'Jones',
355
- 'company' => 'Jones Co.',
356
- 'email' => 'mike.jones@example.com',
357
- 'phone' => '419.555.1234',
358
- 'fax' => '419.555.1235',
359
- 'website' => 'http://example.com',
360
- 'creditCard' => [
361
- 'number' => '5105105105105100',
362
- 'expirationDate' => '05/12',
363
- 'cvv' => '123',
364
- 'cardholderName' => 'Mike Jones'
365
- ]
366
- ]);
367
- $this->assertEquals(true, $result->success);
368
- $customer = $result->customer;
369
- $this->assertEquals('Mike', $customer->firstName);
370
- $this->assertEquals('Jones', $customer->lastName);
371
- $this->assertEquals('Jones Co.', $customer->company);
372
- $this->assertEquals('mike.jones@example.com', $customer->email);
373
- $this->assertEquals('419.555.1234', $customer->phone);
374
- $this->assertEquals('419.555.1235', $customer->fax);
375
- $this->assertEquals('http://example.com', $customer->website);
376
- $creditCard = $customer->creditCards[0];
377
- $this->assertEquals('510510', $creditCard->bin);
378
- $this->assertEquals('5100', $creditCard->last4);
379
- $this->assertEquals('Mike Jones', $creditCard->cardholderName);
380
- $this->assertEquals('05/2012', $creditCard->expirationDate);
381
- $this->assertEquals('05', $creditCard->expirationMonth);
382
- $this->assertEquals('2012', $creditCard->expirationYear);
383
- }
384
-
385
- public function testCreate_withDuplicateCardCheck()
386
- {
387
- $customer = Braintree\Customer::createNoValidate();
388
-
389
- $attributes = [
390
- 'firstName' => 'Mike',
391
- 'lastName' => 'Jones',
392
- 'company' => 'Jones Co.',
393
- 'email' => 'mike.jones@example.com',
394
- 'phone' => '419.555.1234',
395
- 'fax' => '419.555.1235',
396
- 'website' => 'http://example.com',
397
- 'creditCard' => [
398
- 'number' => '5105105105105100',
399
- 'expirationDate' => '05/12',
400
- 'cvv' => '123',
401
- 'cardholderName' => 'Mike Jones',
402
- 'options' => [
403
- 'failOnDuplicatePaymentMethod' => true
404
- ]
405
- ]
406
- ];
407
- Braintree\Customer::create($attributes);
408
- $result = Braintree\Customer::create($attributes);
409
-
410
- $this->assertFalse($result->success);
411
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->onAttribute('number');
412
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_DUPLICATE_CARD_EXISTS, $errors[0]->code);
413
- $this->assertEquals(1, preg_match('/Duplicate card exists in the vault\./', $result->message));
414
- }
415
-
416
- public function testCreate_withCreditCardAndSpecificVerificationMerchantAccount()
417
- {
418
- $result = Braintree\Customer::create([
419
- 'firstName' => 'Mike',
420
- 'lastName' => 'Jones',
421
- 'company' => 'Jones Co.',
422
- 'email' => 'mike.jones@example.com',
423
- 'phone' => '419.555.1234',
424
- 'fax' => '419.555.1235',
425
- 'website' => 'http://example.com',
426
- 'creditCard' => [
427
- 'number' => '5105105105105100',
428
- 'expirationDate' => '05/12',
429
- 'cvv' => '123',
430
- 'cardholderName' => 'Mike Jones',
431
- 'options' => [
432
- 'verificationMerchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
433
- 'verifyCard' => true
434
- ]
435
- ]
436
- ]);
437
- Test\Helper::assertPrintable($result);
438
- $this->assertFalse($result->success);
439
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
440
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
441
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
442
- $this->assertEquals('M', $result->creditCardVerification->cvvResponseCode);
443
- $this->assertEquals(null, $result->creditCardVerification->avsErrorResponseCode);
444
- $this->assertEquals('I', $result->creditCardVerification->avsPostalCodeResponseCode);
445
- $this->assertEquals('I', $result->creditCardVerification->avsStreetAddressResponseCode);
446
- }
447
-
448
- public function testCreate_withCreditCardAndBillingAddress()
449
- {
450
- $result = Braintree\Customer::create([
451
- 'firstName' => 'Mike',
452
- 'lastName' => 'Jones',
453
- 'company' => 'Jones Co.',
454
- 'email' => 'mike.jones@example.com',
455
- 'phone' => '419.555.1234',
456
- 'fax' => '419.555.1235',
457
- 'website' => 'http://example.com',
458
- 'creditCard' => [
459
- 'number' => '5105105105105100',
460
- 'expirationDate' => '05/12',
461
- 'cvv' => '123',
462
- 'cardholderName' => 'Mike Jones',
463
- 'billingAddress' => [
464
- 'firstName' => 'Drew',
465
- 'lastName' => 'Smith',
466
- 'company' => 'Smith Co.',
467
- 'streetAddress' => '1 E Main St',
468
- 'extendedAddress' => 'Suite 101',
469
- 'locality' => 'Chicago',
470
- 'region' => 'IL',
471
- 'postalCode' => '60622',
472
- 'countryName' => 'United States of America'
473
- ]
474
- ]
475
- ]);
476
- Test\Helper::assertPrintable($result);
477
- $this->assertEquals(true, $result->success);
478
- $customer = $result->customer;
479
- $this->assertEquals('Mike', $customer->firstName);
480
- $this->assertEquals('Jones', $customer->lastName);
481
- $this->assertEquals('Jones Co.', $customer->company);
482
- $this->assertEquals('mike.jones@example.com', $customer->email);
483
- $this->assertEquals('419.555.1234', $customer->phone);
484
- $this->assertEquals('419.555.1235', $customer->fax);
485
- $this->assertEquals('http://example.com', $customer->website);
486
- $creditCard = $customer->creditCards[0];
487
- $this->assertEquals('510510', $creditCard->bin);
488
- $this->assertEquals('5100', $creditCard->last4);
489
- $this->assertEquals('Mike Jones', $creditCard->cardholderName);
490
- $this->assertEquals('05/2012', $creditCard->expirationDate);
491
- $this->assertEquals('05', $creditCard->expirationMonth);
492
- $this->assertEquals('2012', $creditCard->expirationYear);
493
- $address = $customer->addresses[0];
494
- $this->assertEquals($address, $creditCard->billingAddress);
495
- $this->assertEquals('Drew', $address->firstName);
496
- $this->assertEquals('Smith', $address->lastName);
497
- $this->assertEquals('Smith Co.', $address->company);
498
- $this->assertEquals('1 E Main St', $address->streetAddress);
499
- $this->assertEquals('Suite 101', $address->extendedAddress);
500
- $this->assertEquals('Chicago', $address->locality);
501
- $this->assertEquals('IL', $address->region);
502
- $this->assertEquals('60622', $address->postalCode);
503
- $this->assertEquals('United States of America', $address->countryName);
504
- }
505
-
506
- public function testCreate_withValidationErrors()
507
- {
508
- $result = Braintree\Customer::create([
509
- 'email' => 'invalid',
510
- 'creditCard' => [
511
- 'number' => 'invalid',
512
- 'billingAddress' => [
513
- 'streetAddress' => str_repeat('x', 256)
514
- ]
515
- ]
516
- ]);
517
- Test\Helper::assertPrintable($result);
518
- $this->assertEquals(false, $result->success);
519
- $errors = $result->errors->forKey('customer')->onAttribute('email');
520
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_EMAIL_IS_INVALID, $errors[0]->code);
521
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->onAttribute('number');
522
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_NUMBER_INVALID_LENGTH, $errors[0]->code);
523
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->forKey('billingAddress')->onAttribute('streetAddress');
524
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_STREET_ADDRESS_IS_TOO_LONG, $errors[0]->code);
525
- }
526
-
527
- public function testCreate_countryValidations_inconsistency()
528
- {
529
- $result = Braintree\Customer::create([
530
- 'creditCard' => [
531
- 'billingAddress' => [
532
- 'countryName' => 'Georgia',
533
- 'countryCodeAlpha2' => 'TF'
534
- ]
535
- ]
536
- ]);
537
- $this->assertEquals(false, $result->success);
538
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->forKey('billingAddress')->onAttribute('base');
539
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_INCONSISTENT_COUNTRY, $errors[0]->code);
540
- }
541
-
542
- public function testCreateNoValidate_returnsCustomer()
543
- {
544
- $customer = Braintree\Customer::createNoValidate([
545
- 'firstName' => 'Paul',
546
- 'lastName' => 'Martin'
547
- ]);
548
- $this->assertEquals('Paul', $customer->firstName);
549
- $this->assertEquals('Martin', $customer->lastName);
550
- }
551
-
552
- public function testCreateNoValidate_throwsIfInvalid()
553
- {
554
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
555
- $customer = Braintree\Customer::createNoValidate(['email' => 'invalid']);
556
- }
557
-
558
- public function testCreate_worksWithFuturePayPalNonce()
559
- {
560
- $nonce = Braintree\Test\Nonces::$paypalFuturePayment;
561
-
562
- $result = Braintree\Customer::create([
563
- 'paymentMethodNonce' => $nonce
564
- ]);
565
-
566
- $this->assertTrue($result->success);
567
- }
568
-
569
- public function testCreate_doesNotWorkWithOnetimePayPalNonce()
570
- {
571
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
572
-
573
- $result = Braintree\Customer::create([
574
- 'paymentMethodNonce' => $nonce
575
- ]);
576
-
577
- $this->assertFalse($result->success);
578
- $errors = $result->errors->forKey('customer')->forKey('paypalAccount')->errors;
579
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT, $errors[0]->code);
580
- }
581
-
582
- public function testDelete_deletesTheCustomer()
583
- {
584
- $result = Braintree\Customer::create([]);
585
- $this->assertEquals(true, $result->success);
586
- Braintree\Customer::find($result->customer->id);
587
- Braintree\Customer::delete($result->customer->id);
588
- $this->setExpectedException('Braintree\Exception\NotFound');
589
- Braintree\Customer::find($result->customer->id);
590
- }
591
-
592
- public function testFind()
593
- {
594
- $result = Braintree\Customer::create([
595
- 'firstName' => 'Mike',
596
- 'lastName' => 'Jones',
597
- 'company' => 'Jones Co.',
598
- 'email' => 'mike.jones@example.com',
599
- 'phone' => '419.555.1234',
600
- 'fax' => '419.555.1235',
601
- 'website' => 'http://example.com'
602
- ]);
603
- $this->assertEquals(true, $result->success);
604
- $customer = Braintree\Customer::find($result->customer->id);
605
- $this->assertEquals('Mike', $customer->firstName);
606
- $this->assertEquals('Jones', $customer->lastName);
607
- $this->assertEquals('Jones Co.', $customer->company);
608
- $this->assertEquals('mike.jones@example.com', $customer->email);
609
- $this->assertEquals('419.555.1234', $customer->phone);
610
- $this->assertEquals('419.555.1235', $customer->fax);
611
- $this->assertEquals('http://example.com', $customer->website);
612
- }
613
-
614
- public function testFind_throwsExceptionIfNotFound()
615
- {
616
- $this->setExpectedException('Braintree\Exception\NotFound');
617
- Braintree\Customer::find("does-not-exist");
618
- }
619
-
620
- public function testUpdate()
621
- {
622
- $result = Braintree\Customer::create([
623
- 'firstName' => 'Old First',
624
- 'lastName' => 'Old Last',
625
- 'company' => 'Old Company',
626
- 'email' => 'old.email@example.com',
627
- 'phone' => 'old phone',
628
- 'fax' => 'old fax',
629
- 'website' => 'http://old.example.com'
630
- ]);
631
- $this->assertEquals(true, $result->success);
632
- $customer = $result->customer;
633
- $updateResult = Braintree\Customer::update($customer->id, [
634
- 'firstName' => 'New First',
635
- 'lastName' => 'New Last',
636
- 'company' => 'New Company',
637
- 'email' => 'new.email@example.com',
638
- 'phone' => 'new phone',
639
- 'fax' => 'new fax',
640
- 'website' => 'http://new.example.com'
641
- ]);
642
- $this->assertEquals(true, $updateResult->success);
643
- $this->assertEquals('New First', $updateResult->customer->firstName);
644
- $this->assertEquals('New Last', $updateResult->customer->lastName);
645
- $this->assertEquals('New Company', $updateResult->customer->company);
646
- $this->assertEquals('new.email@example.com', $updateResult->customer->email);
647
- $this->assertEquals('new phone', $updateResult->customer->phone);
648
- $this->assertEquals('new fax', $updateResult->customer->fax);
649
- $this->assertEquals('http://new.example.com', $updateResult->customer->website);
650
- }
651
-
652
- public function testUpdate_withCountry()
653
- {
654
- $customer = Braintree\Customer::create([
655
- 'firstName' => 'Bat',
656
- 'lastName' => 'Manderson',
657
- 'creditCard' => [
658
- 'number' => '5105105105105100',
659
- 'expirationDate' => '05/12',
660
- 'billingAddress' => [
661
- 'countryName' => 'United States of America',
662
- 'countryCodeAlpha2' => 'US',
663
- 'countryCodeAlpha3' => 'USA',
664
- 'countryCodeNumeric' => '840'
665
- ]
666
- ]
667
- ])->customer;
668
-
669
- $result = Braintree\Customer::update($customer->id, [
670
- 'firstName' => 'Bat',
671
- 'lastName' => 'Manderson',
672
- 'creditCard' => [
673
- 'options' => [
674
- 'updateExistingToken' => $customer->creditCards[0]->token
675
- ],
676
- 'billingAddress' => [
677
- 'countryName' => 'Gabon',
678
- 'countryCodeAlpha2' => 'GA',
679
- 'countryCodeAlpha3' => 'GAB',
680
- 'countryCodeNumeric' => '266',
681
- 'options' => [
682
- 'updateExisting' => true
683
- ]
684
- ]
685
- ]
686
- ]);
687
-
688
- $this->assertEquals(true, $result->success);
689
- $updatedCustomer = $result->customer;
690
- $this->assertEquals('Gabon', $updatedCustomer->creditCards[0]->billingAddress->countryName);
691
- $this->assertEquals('GA', $updatedCustomer->creditCards[0]->billingAddress->countryCodeAlpha2);
692
- $this->assertEquals('GAB', $updatedCustomer->creditCards[0]->billingAddress->countryCodeAlpha3);
693
- $this->assertEquals('266', $updatedCustomer->creditCards[0]->billingAddress->countryCodeNumeric);
694
- }
695
-
696
- public function testUpdate_withUpdatingExistingCreditCard()
697
- {
698
- $create_result = Braintree\Customer::create([
699
- 'firstName' => 'Old First',
700
- 'lastName' => 'Old Last',
701
- 'website' => 'http://old.example.com',
702
- 'creditCard' => [
703
- 'number' => '5105105105105100',
704
- 'expirationDate' => '05/12',
705
- 'cardholderName' => 'Old Cardholder'
706
- ]
707
- ]);
708
- $this->assertEquals(true, $create_result->success);
709
- $customer = $create_result->customer;
710
- $creditCard = $customer->creditCards[0];
711
- $result = Braintree\Customer::update($customer->id, [
712
- 'firstName' => 'New First',
713
- 'lastName' => 'New Last',
714
- 'creditCard' => [
715
- 'number' => '4111111111111111',
716
- 'expirationDate' => '11/14',
717
- 'cardholderName' => 'New Cardholder',
718
- 'options' => [
719
- 'updateExistingToken' => $creditCard->token
720
- ]
721
- ]
722
- ]);
723
- $this->assertEquals(true, $result->success);
724
- $this->assertEquals('New First', $result->customer->firstName);
725
- $this->assertEquals('New Last', $result->customer->lastName);
726
- $this->assertEquals(1, sizeof($result->customer->creditCards));
727
- $creditCard = $result->customer->creditCards[0];
728
- $this->assertEquals('411111', $creditCard->bin);
729
- $this->assertEquals('11/2014', $creditCard->expirationDate);
730
- $this->assertEquals('New Cardholder', $creditCard->cardholderName);
731
- }
732
-
733
- public function testUpdate_forBillingAddressAndExistingCreditCardAndCustomerDetailsTogether()
734
- {
735
- $create_result = Braintree\Customer::create([
736
- 'firstName' => 'Old First',
737
- 'lastName' => 'Old Last',
738
- 'creditCard' => [
739
- 'number' => '5105105105105100',
740
- 'expirationDate' => '05/12',
741
- 'cvv' => '123',
742
- 'cardholderName' => 'Old Cardholder',
743
- 'billingAddress' => [
744
- 'firstName' => 'Drew',
745
- 'lastName' => 'Smith'
746
- ]
747
- ]
748
- ]);
749
- $this->assertEquals(true, $create_result->success);
750
- $customer = $create_result->customer;
751
- $creditCard = $customer->creditCards[0];
752
- $result = Braintree\Customer::update($customer->id, [
753
- 'firstName' => 'New Customer First',
754
- 'lastName' => 'New Customer Last',
755
- 'creditCard' => [
756
- 'number' => '4111111111111111',
757
- 'expirationDate' => '11/14',
758
- 'options' => [
759
- 'updateExistingToken' => $creditCard->token
760
- ],
761
- 'billingAddress' => [
762
- 'firstName' => 'New Billing First',
763
- 'lastName' => 'New Billing Last',
764
- 'options' => [
765
- 'updateExisting' => true
766
- ]
767
- ]
768
- ]
769
- ]);
770
- $this->assertEquals(true, $result->success);
771
- $this->assertEquals('New Customer First', $result->customer->firstName);
772
- $this->assertEquals('New Customer Last', $result->customer->lastName);
773
- $this->assertEquals(1, sizeof($result->customer->creditCards));
774
- $this->assertEquals(1, sizeof($result->customer->addresses));
775
-
776
- $creditCard = $result->customer->creditCards[0];
777
- $this->assertEquals('411111', $creditCard->bin);
778
- $this->assertEquals('11/2014', $creditCard->expirationDate);
779
-
780
- $billingAddress = $creditCard->billingAddress;
781
- $this->assertEquals('New Billing First', $billingAddress->firstName);
782
- $this->assertEquals('New Billing Last', $billingAddress->lastName);
783
- }
784
-
785
- public function testUpdate_withNewCreditCardAndExistingBillingAddress()
786
- {
787
- $customer = Braintree\Customer::create()->customer;
788
- $address = Braintree\Address::create([
789
- 'customerId' => $customer->id,
790
- 'firstName' => 'Dan'
791
- ])->address;
792
-
793
- $result = Braintree\Customer::update($customer->id, [
794
- 'creditCard' => [
795
- 'number' => '4111111111111111',
796
- 'expirationDate' => '11/14',
797
- 'billingAddressId' => $address->id
798
- ]
799
- ]);
800
-
801
- $billingAddress = $result->customer->creditCards[0]->billingAddress;
802
- $this->assertEquals($address->id, $billingAddress->id);
803
- $this->assertEquals('Dan', $billingAddress->firstName);
804
- }
805
-
806
- public function testUpdate_worksWithFuturePayPalNonce()
807
- {
808
- $customerResult = Braintree\Customer::create([
809
- 'creditCard' => [
810
- 'number' => '5105105105105100',
811
- 'expirationDate' => '05/12',
812
- 'options' => [
813
- 'makeDefault' => true
814
- ]
815
- ]
816
- ]);
817
- $paypalAccountToken = 'PAYPALToken-' . strval(rand());
818
- $http = new HttpClientApi(Braintree\Configuration::$global);
819
- $nonce = $http->nonceForPayPalAccount([
820
- 'paypal_account' => [
821
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
822
- 'token' => $paypalAccountToken,
823
- 'options' => [
824
- 'makeDefault' => true
825
- ]
826
- ]
827
- ]);
828
-
829
- $result = Braintree\Customer::update($customerResult->customer->id, [
830
- 'paymentMethodNonce' => $nonce
831
- ]);
832
-
833
- $this->assertTrue($result->success);
834
- $this->assertEquals($result->customer->defaultPaymentMethod()->token, $paypalAccountToken);
835
-
836
- }
837
-
838
- public function testUpdate_doesNotWorkWithOnetimePayPalNonce()
839
- {
840
- $customerResult = Braintree\Customer::create([
841
- 'creditCard' => [
842
- 'number' => '5105105105105100',
843
- 'expirationDate' => '05/12',
844
- 'options' => [
845
- 'makeDefault' => true
846
- ]
847
- ]
848
- ]);
849
- $paypalAccountToken = 'PAYPALToken-' . strval(rand());
850
- $http = new HttpClientApi(Braintree\Configuration::$global);
851
- $nonce = $http->nonceForPayPalAccount([
852
- 'paypal_account' => [
853
- 'access_token' => 'PAYPAL_ACCESS_TOKEN',
854
- 'token' => $paypalAccountToken,
855
- 'options' => [
856
- 'makeDefault' => true
857
- ]
858
- ]
859
- ]);
860
-
861
- $result = Braintree\Customer::update($customerResult->customer->id, [
862
- 'paymentMethodNonce' => $nonce
863
- ]);
864
-
865
- $this->assertFalse($result->success);
866
- $errors = $result->errors->forKey('customer')->forKey('paypalAccount')->errors;
867
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT, $errors[0]->code);
868
-
869
- }
870
-
871
- public function testUpdateNoValidate()
872
- {
873
- $result = Braintree\Customer::create([
874
- 'firstName' => 'Old First',
875
- 'lastName' => 'Old Last',
876
- 'company' => 'Old Company',
877
- 'email' => 'old.email@example.com',
878
- 'phone' => 'old phone',
879
- 'fax' => 'old fax',
880
- 'website' => 'http://old.example.com'
881
- ]);
882
- $this->assertEquals(true, $result->success);
883
- $customer = $result->customer;
884
- $updated = Braintree\Customer::updateNoValidate($customer->id, [
885
- 'firstName' => 'New First',
886
- 'lastName' => 'New Last',
887
- 'company' => 'New Company',
888
- 'email' => 'new.email@example.com',
889
- 'phone' => 'new phone',
890
- 'fax' => 'new fax',
891
- 'website' => 'http://new.example.com'
892
- ]);
893
- $this->assertEquals('New First', $updated->firstName);
894
- $this->assertEquals('New Last', $updated->lastName);
895
- $this->assertEquals('New Company', $updated->company);
896
- $this->assertEquals('new.email@example.com', $updated->email);
897
- $this->assertEquals('new phone', $updated->phone);
898
- $this->assertEquals('new fax', $updated->fax);
899
- $this->assertEquals('http://new.example.com', $updated->website);
900
- }
901
-
902
- public function testCreateFromTransparentRedirect()
903
- {
904
- Test\Helper::suppressDeprecationWarnings();
905
- $queryString = $this->createCustomerViaTr(
906
- [
907
- 'customer' => [
908
- 'first_name' => 'Joe',
909
- 'last_name' => 'Martin',
910
- 'credit_card' => [
911
- 'number' => '5105105105105100',
912
- 'expiration_date' => '05/12'
913
- ]
914
- ]
915
- ],
916
- [
917
- ]
918
- );
919
- $result = Braintree\Customer::createFromTransparentRedirect($queryString);
920
- $this->assertTrue($result->success);
921
- $this->assertEquals('Joe', $result->customer->firstName);
922
- $this->assertEquals('Martin', $result->customer->lastName);
923
- $creditCard = $result->customer->creditCards[0];
924
- $this->assertEquals('510510', $creditCard->bin);
925
- $this->assertEquals('5100', $creditCard->last4);
926
- $this->assertEquals('05/2012', $creditCard->expirationDate);
927
- }
928
-
929
- public function testCreateFromTransparentRedirect_withParamsInTrData()
930
- {
931
- Test\Helper::suppressDeprecationWarnings();
932
- $queryString = $this->createCustomerViaTr(
933
- [
934
- ],
935
- [
936
- 'customer' => [
937
- 'firstName' => 'Joe',
938
- 'lastName' => 'Martin',
939
- 'creditCard' => [
940
- 'number' => '5105105105105100',
941
- 'expirationDate' => '05/12'
942
- ]
943
- ]
944
- ]
945
- );
946
- $result = Braintree\Customer::createFromTransparentRedirect($queryString);
947
- $this->assertTrue($result->success);
948
- $this->assertEquals('Joe', $result->customer->firstName);
949
- $this->assertEquals('Martin', $result->customer->lastName);
950
- $creditCard = $result->customer->creditCards[0];
951
- $this->assertEquals('510510', $creditCard->bin);
952
- $this->assertEquals('5100', $creditCard->last4);
953
- $this->assertEquals('05/2012', $creditCard->expirationDate);
954
- }
955
-
956
- public function testCreateFromTransparentRedirect_withValidationErrors()
957
- {
958
- Test\Helper::suppressDeprecationWarnings();
959
- $queryString = $this->createCustomerViaTr(
960
- [
961
- 'customer' => [
962
- 'first_name' => str_repeat('x', 256),
963
- 'credit_card' => [
964
- 'number' => 'invalid',
965
- 'expiration_date' => ''
966
- ]
967
- ]
968
- ],
969
- [
970
- ]
971
- );
972
- $result = Braintree\Customer::createFromTransparentRedirect($queryString);
973
- $this->assertFalse($result->success);
974
- $errors = $result->errors->forKey('customer')->onAttribute('firstName');
975
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_FIRST_NAME_IS_TOO_LONG, $errors[0]->code);
976
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->onAttribute('number');
977
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_NUMBER_INVALID_LENGTH, $errors[0]->code);
978
- $errors = $result->errors->forKey('customer')->forKey('creditCard')->onAttribute('expirationDate');
979
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED, $errors[0]->code);
980
- }
981
-
982
- public function testCreateWithInvalidUTF8Bytes()
983
- {
984
- $result = Braintree\Customer::create([
985
- 'firstName' => "Jos\xe8 Maria"
986
- ]);
987
- $this->assertEquals(true, $result->success);
988
- $customer = $result->customer;
989
- $this->assertEquals("Jos\xc3\xa8 Maria", $customer->firstName);
990
- }
991
-
992
- public function testCreateWithValidUTF8Bytes()
993
- {
994
- $result = Braintree\Customer::create([
995
- 'firstName' => "Jos\303\251"
996
- ]);
997
- $this->assertEquals(true, $result->success);
998
- $customer = $result->customer;
999
- $this->assertEquals("Jos\303\251", $customer->firstName);
1000
- }
1001
-
1002
- public function testUpdateFromTransparentRedirect()
1003
- {
1004
- Test\Helper::suppressDeprecationWarnings();
1005
- $customer = Braintree\Customer::createNoValidate();
1006
- $queryString = $this->updateCustomerViaTr(
1007
- [
1008
- 'customer' => [
1009
- 'first_name' => 'Joe',
1010
- 'last_name' => 'Martin',
1011
- 'email' => 'joe.martin@example.com'
1012
- ]
1013
- ],
1014
- [
1015
- 'customerId' => $customer->id
1016
- ]
1017
- );
1018
- $result = Braintree\Customer::updateFromTransparentRedirect($queryString);
1019
- $this->assertTrue($result->success);
1020
- $this->assertEquals('Joe', $result->customer->firstName);
1021
- $this->assertEquals('Martin', $result->customer->lastName);
1022
- $this->assertEquals('joe.martin@example.com', $result->customer->email);
1023
- }
1024
-
1025
- public function testUpdateFromTransparentRedirect_withParamsInTrData()
1026
- {
1027
- Test\Helper::suppressDeprecationWarnings();
1028
- $customer = Braintree\Customer::createNoValidate();
1029
- $queryString = $this->updateCustomerViaTr(
1030
- [
1031
- ],
1032
- [
1033
- 'customerId' => $customer->id,
1034
- 'customer' => [
1035
- 'firstName' => 'Joe',
1036
- 'lastName' => 'Martin',
1037
- 'email' => 'joe.martin@example.com'
1038
- ]
1039
- ]
1040
- );
1041
- $result = Braintree\Customer::updateFromTransparentRedirect($queryString);
1042
- $this->assertTrue($result->success);
1043
- $this->assertEquals('Joe', $result->customer->firstName);
1044
- $this->assertEquals('Martin', $result->customer->lastName);
1045
- $this->assertEquals('joe.martin@example.com', $result->customer->email);
1046
- }
1047
-
1048
- public function testUpdateFromTransparentRedirect_withValidationErrors()
1049
- {
1050
- Test\Helper::suppressDeprecationWarnings();
1051
- $customer = Braintree\Customer::createNoValidate();
1052
- $queryString = $this->updateCustomerViaTr(
1053
- [
1054
- 'customer' => [
1055
- 'first_name' => str_repeat('x', 256),
1056
- ]
1057
- ],
1058
- [
1059
- 'customerId' => $customer->id
1060
- ]
1061
- );
1062
- $result = Braintree\Customer::updateFromTransparentRedirect($queryString);
1063
- $this->assertFalse($result->success);
1064
- $errors = $result->errors->forKey('customer')->onAttribute('firstName');
1065
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_FIRST_NAME_IS_TOO_LONG, $errors[0]->code);
1066
- }
1067
-
1068
- public function testUpdateFromTransparentRedirect_withUpdateExisting()
1069
- {
1070
- Test\Helper::suppressDeprecationWarnings();
1071
- $customer = Braintree\Customer::create([
1072
- 'firstName' => 'Mike',
1073
- 'lastName' => 'Jones',
1074
- 'creditCard' => [
1075
- 'number' => '5105105105105100',
1076
- 'expirationDate' => '05/12',
1077
- 'cardholderName' => 'Mike Jones',
1078
- 'billingAddress' => [
1079
- 'firstName' => 'Drew',
1080
- 'lastName' => 'Smith'
1081
- ]
1082
- ]
1083
- ])->customer;
1084
-
1085
- $queryString = $this->updateCustomerViaTr(
1086
- [],
1087
- [
1088
- 'customerId' => $customer->id,
1089
- 'customer' => [
1090
- 'firstName' => 'New First',
1091
- 'lastName' => 'New Last',
1092
- 'creditCard' => [
1093
- 'number' => '4111111111111111',
1094
- 'expirationDate' => '05/13',
1095
- 'cardholderName' => 'New Cardholder',
1096
- 'options' => [
1097
- 'updateExistingToken' => $customer->creditCards[0]->token
1098
- ],
1099
- 'billingAddress' => [
1100
- 'firstName' => 'New First Billing',
1101
- 'lastName' => 'New Last Billing',
1102
- 'options' => [
1103
- 'updateExisting' => true
1104
- ]
1105
- ]
1106
- ]
1107
- ]
1108
- ]
1109
- );
1110
- $result = Braintree\Customer::updateFromTransparentRedirect($queryString);
1111
- $this->assertTrue($result->success);
1112
-
1113
- $this->assertEquals(true, $result->success);
1114
- $customer = $result->customer;
1115
- $this->assertEquals('New First', $customer->firstName);
1116
- $this->assertEquals('New Last', $customer->lastName);
1117
-
1118
- $this->assertEquals(1, sizeof($result->customer->creditCards));
1119
- $creditCard = $customer->creditCards[0];
1120
- $this->assertEquals('411111', $creditCard->bin);
1121
- $this->assertEquals('1111', $creditCard->last4);
1122
- $this->assertEquals('New Cardholder', $creditCard->cardholderName);
1123
- $this->assertEquals('05/2013', $creditCard->expirationDate);
1124
-
1125
- $this->assertEquals(1, sizeof($result->customer->addresses));
1126
- $address = $customer->addresses[0];
1127
- $this->assertEquals($address, $creditCard->billingAddress);
1128
- $this->assertEquals('New First Billing', $address->firstName);
1129
- $this->assertEquals('New Last Billing', $address->lastName);
1130
- }
1131
-
1132
- public function testSale_createsASaleUsingGivenToken()
1133
- {
1134
- $customer = Braintree\Customer::createNoValidate([
1135
- 'creditCard' => [
1136
- 'number' => '5105105105105100',
1137
- 'expirationDate' => '05/12'
1138
- ]
1139
- ]);
1140
- $creditCard = $customer->creditCards[0];
1141
- $result = Braintree\Customer::sale($customer->id, [
1142
- 'amount' => '100.00'
1143
- ]);
1144
- $this->assertTrue($result->success);
1145
- $this->assertEquals('100.00', $result->transaction->amount);
1146
- $this->assertEquals($customer->id, $result->transaction->customerDetails->id);
1147
- $this->assertEquals($creditCard->token, $result->transaction->creditCardDetails->token);
1148
- }
1149
-
1150
- public function testSaleNoValidate_createsASaleUsingGivenToken()
1151
- {
1152
- $customer = Braintree\Customer::createNoValidate([
1153
- 'creditCard' => [
1154
- 'number' => '5105105105105100',
1155
- 'expirationDate' => '05/12'
1156
- ]
1157
- ]);
1158
- $creditCard = $customer->creditCards[0];
1159
- $transaction = Braintree\Customer::saleNoValidate($customer->id, [
1160
- 'amount' => '100.00'
1161
- ]);
1162
- $this->assertEquals('100.00', $transaction->amount);
1163
- $this->assertEquals($customer->id, $transaction->customerDetails->id);
1164
- $this->assertEquals($creditCard->token, $transaction->creditCardDetails->token);
1165
- }
1166
-
1167
- public function testSaleNoValidate_throwsIfInvalid()
1168
- {
1169
- $customer = Braintree\Customer::createNoValidate([
1170
- 'creditCard' => [
1171
- 'number' => '5105105105105100',
1172
- 'expirationDate' => '05/12'
1173
- ]
1174
- ]);
1175
- $creditCard = $customer->creditCards[0];
1176
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
1177
- Braintree\Customer::saleNoValidate($customer->id, [
1178
- 'amount' => 'invalid'
1179
- ]);
1180
- }
1181
-
1182
- public function testCredit_createsACreditUsingGivenCustomerId()
1183
- {
1184
- $customer = Braintree\Customer::createNoValidate([
1185
- 'creditCard' => [
1186
- 'number' => '5105105105105100',
1187
- 'expirationDate' => '05/12'
1188
- ]
1189
- ]);
1190
- $creditCard = $customer->creditCards[0];
1191
- $result = Braintree\Customer::credit($customer->id, [
1192
- 'amount' => '100.00'
1193
- ]);
1194
- $this->assertTrue($result->success);
1195
- $this->assertEquals('100.00', $result->transaction->amount);
1196
- $this->assertEquals(Braintree\Transaction::CREDIT, $result->transaction->type);
1197
- $this->assertEquals($customer->id, $result->transaction->customerDetails->id);
1198
- $this->assertEquals($creditCard->token, $result->transaction->creditCardDetails->token);
1199
- }
1200
-
1201
- public function testCreditNoValidate_createsACreditUsingGivenId()
1202
- {
1203
- $customer = Braintree\Customer::createNoValidate([
1204
- 'creditCard' => [
1205
- 'number' => '5105105105105100',
1206
- 'expirationDate' => '05/12'
1207
- ]
1208
- ]);
1209
- $creditCard = $customer->creditCards[0];
1210
- $transaction = Braintree\Customer::creditNoValidate($customer->id, [
1211
- 'amount' => '100.00'
1212
- ]);
1213
- $this->assertEquals('100.00', $transaction->amount);
1214
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction->type);
1215
- $this->assertEquals($customer->id, $transaction->customerDetails->id);
1216
- $this->assertEquals($creditCard->token, $transaction->creditCardDetails->token);
1217
- }
1218
-
1219
- public function testCreditNoValidate_throwsIfInvalid()
1220
- {
1221
- $customer = Braintree\Customer::createNoValidate([
1222
- 'creditCard' => [
1223
- 'number' => '5105105105105100',
1224
- 'expirationDate' => '05/12'
1225
- ]
1226
- ]);
1227
- $creditCard = $customer->creditCards[0];
1228
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
1229
- Braintree\Customer::creditNoValidate($customer->id, [
1230
- 'amount' => 'invalid'
1231
- ]);
1232
- }
1233
-
1234
- public function createCustomerViaTr($regularParams, $trParams)
1235
- {
1236
- Test\Helper::suppressDeprecationWarnings();
1237
- $trData = Braintree\TransparentRedirect::createCustomerData(
1238
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
1239
- );
1240
- return Test\Helper::submitTrRequest(
1241
- Braintree\Customer::createCustomerUrl(),
1242
- $regularParams,
1243
- $trData
1244
- );
1245
- }
1246
-
1247
- public function updateCustomerViaTr($regularParams, $trParams)
1248
- {
1249
- Test\Helper::suppressDeprecationWarnings();
1250
- $trData = Braintree\TransparentRedirect::updateCustomerData(
1251
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
1252
- );
1253
- return Test\Helper::submitTrRequest(
1254
- Braintree\Customer::updateCustomerUrl(),
1255
- $regularParams,
1256
- $trData
1257
- );
1258
- }
1259
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/DisbursementTest.php DELETED
@@ -1,39 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class DisbursementTest extends Setup
11
- {
12
- public function testTransactions()
13
- {
14
- $disbursement = Braintree\Disbursement::factory([
15
- "id" => "123456",
16
- "merchantAccount" => [
17
- "id" => "sandbox_sub_merchant_account",
18
- "masterMerchantAccount" => [
19
- "id" => "sandbox_master_merchant_account",
20
- "status" => "active"
21
- ],
22
- "status" => "active"
23
- ],
24
- "transactionIds" => ["sub_merchant_transaction"],
25
- "exceptionMessage" => "invalid_account_number",
26
- "amount" => "100.00",
27
- "disbursementDate" => new DateTime("2013-04-10"),
28
- "followUpAction" => "update",
29
- "retry" => false,
30
- "success" => false
31
- ]);
32
-
33
- $transactions = $disbursement->transactions();
34
-
35
- $this->assertNotNull($transactions);
36
- $this->assertEquals(sizeOf($transactions), 1);
37
- $this->assertEquals($transactions->firstItem()->id, 'sub_merchant_transaction');
38
- }
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/DiscountTest.php DELETED
@@ -1,88 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class DiscountTest extends Setup
10
- {
11
- public function testAll_returnsAllDiscounts()
12
- {
13
- $newId = strval(rand());
14
-
15
- $discountParams = [
16
- "amount" => "100.00",
17
- "description" => "some description",
18
- "id" => $newId,
19
- "kind" => "discount",
20
- "name" => "php_discount",
21
- "neverExpires" => "false",
22
- "numberOfBillingCycles" => "1"
23
- ];
24
-
25
- $http = new Braintree\Http(Braintree\Configuration::$global);
26
- $path = Braintree\Configuration::$global->merchantPath() . "/modifications/create_modification_for_tests";
27
- $http->post($path, ["modification" => $discountParams]);
28
-
29
- $discounts = Braintree\Discount::all();
30
-
31
- foreach ($discounts as $discount)
32
- {
33
- if ($discount->id == $newId)
34
- {
35
- $actualDiscount = $discount;
36
- }
37
- }
38
-
39
- $this->assertNotNull($actualDiscount);
40
- $this->assertEquals($discountParams["amount"], $actualDiscount->amount);
41
- $this->assertEquals($discountParams["description"], $actualDiscount->description);
42
- $this->assertEquals($discountParams["id"], $actualDiscount->id);
43
- $this->assertEquals($discountParams["kind"], $actualDiscount->kind);
44
- $this->assertEquals($discountParams["name"], $actualDiscount->name);
45
- $this->assertFalse($actualDiscount->neverExpires);
46
- $this->assertEquals($discountParams["numberOfBillingCycles"], $actualDiscount->numberOfBillingCycles);
47
- }
48
-
49
- public function testGatewayAll_returnsAllDiscounts()
50
- {
51
- $newId = strval(rand());
52
-
53
- $discountParams = [
54
- "amount" => "100.00",
55
- "description" => "some description",
56
- "id" => $newId,
57
- "kind" => "discount",
58
- "name" => "php_discount",
59
- "neverExpires" => "false",
60
- "numberOfBillingCycles" => "1"
61
- ];
62
-
63
- $http = new Braintree\Http(Braintree\Configuration::$global);
64
- $path = Braintree\Configuration::$global->merchantPath() . "/modifications/create_modification_for_tests";
65
- $http->post($path, ["modification" => $discountParams]);
66
-
67
- $gateway = new Braintree\Gateway([
68
- 'environment' => 'development',
69
- 'merchantId' => 'integration_merchant_id',
70
- 'publicKey' => 'integration_public_key',
71
- 'privateKey' => 'integration_private_key'
72
- ]);
73
- $discounts = $gateway->discount()->all();
74
-
75
- foreach ($discounts as $discount)
76
- {
77
- if ($discount->id == $newId)
78
- {
79
- $actualDiscount = $discount;
80
- }
81
- }
82
-
83
- $this->assertNotNull($actualDiscount);
84
- $this->assertEquals($discountParams["amount"], $actualDiscount->amount);
85
- $this->assertEquals($discountParams["id"], $actualDiscount->id);
86
- $this->assertEquals($discountParams["kind"], $actualDiscount->kind);
87
- }
88
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/Error/ErrorCollectionTest.php DELETED
@@ -1,80 +0,0 @@
1
- <?php
2
- namespace Test\Integration\Error;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ErrorCollectionTest extends Setup
10
- {
11
- public function testDeepSize_withNestedErrors()
12
- {
13
- $result = Braintree\Customer::create([
14
- 'email' => 'invalid',
15
- 'creditCard' => [
16
- 'number' => 'invalid',
17
- 'expirationDate' => 'invalid',
18
- 'billingAddress' => [
19
- 'countryName' => 'invaild'
20
- ]
21
- ]
22
- ]);
23
- $this->assertEquals(false, $result->success);
24
- $this->assertEquals(4, $result->errors->deepSize());
25
- }
26
-
27
- public function testOnHtmlField()
28
- {
29
- $result = Braintree\Customer::create([
30
- 'email' => 'invalid',
31
- 'creditCard' => [
32
- 'number' => 'invalid',
33
- 'expirationDate' => 'invalid',
34
- 'billingAddress' => [
35
- 'countryName' => 'invaild'
36
- ]
37
- ]
38
- ]);
39
- $this->assertEquals(false, $result->success);
40
- $errors = $result->errors->onHtmlField('customer[email]');
41
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_EMAIL_IS_INVALID, $errors[0]->code);
42
- $errors = $result->errors->onHtmlField('customer[credit_card][number]');
43
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_NUMBER_INVALID_LENGTH, $errors[0]->code);
44
- $errors = $result->errors->onHtmlField('customer[credit_card][billing_address][country_name]');
45
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, $errors[0]->code);
46
- }
47
-
48
- public function testOnHtmlField_returnsEmptyArrayIfNone()
49
- {
50
- $result = Braintree\Customer::create([
51
- 'email' => 'invalid',
52
- 'creditCard' => [
53
- 'number' => '5105105105105100',
54
- 'expirationDate' => '05/12',
55
- 'billingAddress' => [
56
- 'streetAddress' => '1 E Main St'
57
- ]
58
- ]
59
- ]);
60
- $this->assertEquals(false, $result->success);
61
- $errors = $result->errors->onHtmlField('customer[email]');
62
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_EMAIL_IS_INVALID, $errors[0]->code);
63
- $this->assertEquals([], $result->errors->onHtmlField('customer[credit_card][number]'));
64
- $this->assertEquals([], $result->errors->onHtmlField('customer[credit_card][billing_address][country_name]'));
65
- }
66
-
67
- public function testOnHtmlField_returnsEmptyForCustomFieldsIfNoErrors()
68
- {
69
- $result = Braintree\Customer::create([
70
- 'email' => 'invalid',
71
- 'creditCard' => [
72
- 'number' => '5105105105105100',
73
- 'expirationDate' => '05/12',
74
- ],
75
- 'customFields' => ['storeMe' => 'value']
76
- ]);
77
- $this->assertEquals(false, $result->success);
78
- $this->assertEquals([], $result->errors->onHtmlField('customer[custom_fields][store_me]'));
79
- }
80
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/Error/ValidationErrorCollectionTest.php DELETED
@@ -1,75 +0,0 @@
1
- <?php
2
- namespace Test\Integration\Error;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ValidationErrorCollectionTest extends Setup
10
- {
11
- public function mapValidationErrorsToCodes($validationErrors)
12
- {
13
- $codes = array_map(create_function('$validationError', 'return $validationError->code;'), $validationErrors);
14
- sort($codes);
15
- return $codes;
16
- }
17
-
18
- public function test_shallowAll_givesAllErrorsShallowly()
19
- {
20
- $result = Braintree\Customer::create([
21
- 'email' => 'invalid',
22
- 'creditCard' => [
23
- 'number' => '1234123412341234',
24
- 'expirationDate' => 'invalid',
25
- 'billingAddress' => [
26
- 'countryName' => 'invalid'
27
- ]
28
- ]
29
- ]);
30
-
31
- $this->assertEquals([], $result->errors->shallowAll());
32
-
33
- $expectedCustomerErrors = [Braintree\Error\Codes::CUSTOMER_EMAIL_IS_INVALID];
34
- $actualCustomerErrors = $result->errors->forKey('customer')->shallowAll();
35
- $this->assertEquals($expectedCustomerErrors, self::mapValidationErrorsToCodes($actualCustomerErrors));
36
-
37
- $expectedCreditCardErrors = [
38
- Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID,
39
- Braintree\Error\Codes::CREDIT_CARD_NUMBER_IS_INVALID,
40
- ];
41
- $actualCreditCardErrors = $result->errors->forKey('customer')->forKey('creditCard')->shallowAll();
42
- $this->assertEquals($expectedCreditCardErrors, self::mapValidationErrorsToCodes($actualCreditCardErrors));
43
- }
44
-
45
- public function test_deepAll_givesAllErrorsDeeply()
46
- {
47
- $result = Braintree\Customer::create([
48
- 'email' => 'invalid',
49
- 'creditCard' => [
50
- 'number' => '1234123412341234',
51
- 'expirationDate' => 'invalid',
52
- 'billingAddress' => [
53
- 'countryName' => 'invalid'
54
- ]
55
- ]
56
- ]);
57
-
58
- $expectedErrors = [
59
- Braintree\Error\Codes::CUSTOMER_EMAIL_IS_INVALID,
60
- Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID,
61
- Braintree\Error\Codes::CREDIT_CARD_NUMBER_IS_INVALID,
62
- Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
63
- ];
64
- $actualErrors = $result->errors->deepAll();
65
- $this->assertEquals($expectedErrors, self::mapValidationErrorsToCodes($actualErrors));
66
-
67
- $expectedErrors = [
68
- Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID,
69
- Braintree\Error\Codes::CREDIT_CARD_NUMBER_IS_INVALID,
70
- Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
71
- ];
72
- $actualErrors = $result->errors->forKey('customer')->forKey('creditCard')->deepAll();
73
- $this->assertEquals($expectedErrors, self::mapValidationErrorsToCodes($actualErrors));
74
- }
75
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/EuropeBankAccountTest.php DELETED
@@ -1,54 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class EuropeBankAccountTest extends Setup
10
- {
11
- public function testCanExchangeNonceForEuropeBankAccount()
12
- {
13
- $gateway = new Braintree\Gateway([
14
- 'environment' => 'development',
15
- 'merchantId' => 'altpay_merchant',
16
- 'publicKey' => 'altpay_merchant_public_key',
17
- 'privateKey' => 'altpay_merchant_private_key'
18
- ]);
19
-
20
- $result = $gateway->customer()->create();
21
- $this->assertTrue($result->success);
22
- $customer = $result->customer;
23
- $clientApi = new HttpClientApi($gateway->config);
24
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
25
- "customerId" => $customer->id,
26
- "sepa_mandate" => [
27
- "locale" => "de-DE",
28
- "bic" => "DEUTDEFF",
29
- "iban" => "DE89370400440532013000",
30
- "accountHolderName" => "Bob Holder",
31
- "billingAddress" => [
32
- "streetAddress" => "123 Currywurst Way",
33
- "extendedAddress" => "Lager Suite",
34
- "firstName" => "Wilhelm",
35
- "lastName" => "Dix",
36
- "locality" => "Frankfurt",
37
- "postalCode" => "60001",
38
- "countryCodeAlpha2" => "DE",
39
- "region" => "Hesse"
40
- ]
41
- ]
42
- ]);
43
- $result = $gateway->paymentMethod()->create([
44
- "customerId" => $customer->id,
45
- "paymentMethodNonce" => $nonce
46
- ]);
47
-
48
- $this->assertTrue($result->success);
49
- $paymentMethod = $result->paymentMethod;
50
- $account = $gateway->paymentMethod()->find($paymentMethod->token);
51
- $this->assertEquals($paymentMethod->token, $account->token);
52
- $this->assertEquals($account->bic, "DEUTDEFF");
53
- }
54
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/HttpClientApi.php DELETED
@@ -1,116 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Braintree;
7
- use Test;
8
-
9
- class HttpClientApi extends Braintree\Http
10
- {
11
- protected function _doRequest($httpVerb, $path, $requestBody = null)
12
- {
13
- return $this->_doUrlRequest($httpVerb, $this->_config->baseUrl() . "/merchants/" . $this->_config->getMerchantId() . $path, $requestBody);
14
- }
15
-
16
- public function get($path)
17
- {
18
- return $this->_doRequest('GET', $path);
19
- }
20
-
21
- public function post($path, $body = null)
22
- {
23
- return $this->_doRequest('POST', $path, $body);
24
- }
25
-
26
- public function _doUrlRequest($httpVerb, $url, $requestBody = null)
27
- {
28
- $curl = curl_init();
29
- curl_setopt($curl, CURLOPT_TIMEOUT, 60);
30
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $httpVerb);
31
- curl_setopt($curl, CURLOPT_URL, $url);
32
- curl_setopt($curl, CURLOPT_HTTPHEADER, [
33
- 'Content-Type: application/json',
34
- 'X-ApiVersion: ' . Braintree\Configuration::API_VERSION,
35
- ]);
36
- curl_setopt($curl, CURLOPT_USERPWD, $this->_config->publicKey() . ':' . $this->_config->privateKey());
37
-
38
- if(!empty($requestBody)) {
39
- curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);
40
- }
41
-
42
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
43
- $response = curl_exec($curl);
44
- $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
45
- curl_close($curl);
46
- return ['status' => $httpStatus, 'body' => $response];
47
- }
48
-
49
- public function get_cards($options) {
50
- $encoded_fingerprint = urlencode($options["authorization_fingerprint"]);
51
- $url = "/client_api/v1/payment_methods.json?";
52
- $url .= "authorizationFingerprint=" . $encoded_fingerprint;
53
- $url .= "&sharedCustomerIdentifier=" . $options["shared_customer_identifier"];
54
- $url .= "&sharedCustomerIdentifierType=" . $options["shared_customer_identifier_type"];
55
-
56
- return $this->get($url);
57
- }
58
-
59
- public function nonce_for_new_card($options) {
60
- $clientTokenOptions = [];
61
- if (array_key_exists("customerId", $options)) {
62
- $clientTokenOptions["customerId"] = $options["customerId"];
63
- unset($options["customerId"]);
64
- }
65
-
66
- $clientToken = json_decode(Test\Helper::decodedClientToken($clientTokenOptions));
67
-
68
- $options["authorization_fingerprint"] = $clientToken->authorizationFingerprint;
69
- $options["shared_customer_identifier"] = "fake_identifier_" . rand();
70
- $options["shared_customer_identifier_type"] = "testing";
71
- $response = $this->post('/client_api/v1/payment_methods/credit_cards.json', json_encode($options));
72
- if ($response["status"] == 201 || $response["status"] == 202) {
73
- $body = json_decode($response["body"]);
74
- return $body->creditCards[0]->nonce;
75
- } else {
76
- throw new Exception(var_dump($response));
77
- }
78
- }
79
-
80
- public function nonceForNewEuropeanBankAccount($options) {
81
- $clientTokenOptions = [
82
- 'sepaMandateType' => 'business',
83
- 'sepaMandateAcceptanceLocation' => 'Rostock, Germany'
84
- ];
85
-
86
- if (array_key_exists("customerId", $options)) {
87
- $clientTokenOptions["customerId"] = $options["customerId"];
88
- unset($options["customerId"]);
89
- }
90
-
91
- $gateway = new Braintree\Gateway($this->_config);
92
-
93
- $clientToken = json_decode(base64_decode($gateway->clientToken()->generate($clientTokenOptions)));
94
- $options["authorization_fingerprint"] = $clientToken->authorizationFingerprint;
95
-
96
- $response = $this->post('/client_api/v1/sepa_mandates/', json_encode($options));
97
- if ($response["status"] == 201 || $response["status"] == 202) {
98
- $body = json_decode($response["body"]);
99
- return $body->europeBankAccounts[0]->nonce;
100
- } else {
101
- throw new Exception(var_dump($response));
102
- }
103
- }
104
-
105
- public function nonceForPayPalAccount($options) {
106
- $clientToken = json_decode(Test\Helper::decodedClientToken());
107
- $options["authorization_fingerprint"] = $clientToken->authorizationFingerprint;
108
- $response = $this->post('/client_api/v1/payment_methods/paypal_accounts.json', json_encode($options));
109
- if ($response["status"] == 201 || $response["status"] == 202) {
110
- $body = json_decode($response["body"], true);
111
- return $body["paypalAccounts"][0]["nonce"];
112
- } else {
113
- throw new Exception(var_dump($response));
114
- }
115
- }
116
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/HttpTest.php DELETED
@@ -1,67 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class HttpTest extends Setup
10
- {
11
- public function testProductionSSL()
12
- {
13
- try {
14
- Braintree\Configuration::environment('production');
15
- $this->setExpectedException('Braintree\Exception\Authentication');
16
- $http = new Braintree\Http(Braintree\Configuration::$global);
17
- $http->get('/');
18
- } catch (Braintree\Exception $e) {
19
- Braintree\Configuration::environment('development');
20
- throw $e;
21
- }
22
- Braintree\Configuration::environment('development');
23
- }
24
-
25
- public function testSandboxSSL()
26
- {
27
- try {
28
- Braintree\Configuration::environment('sandbox');
29
- $this->setExpectedException('Braintree\Exception\Authentication');
30
- $http = new Braintree\Http(Braintree\Configuration::$global);
31
- $http->get('/');
32
- } catch (Braintree\Exception $e) {
33
- Braintree\Configuration::environment('development');
34
- throw $e;
35
- }
36
- Braintree\Configuration::environment('development');
37
- }
38
-
39
- public function testSslError()
40
- {
41
- try {
42
- Braintree\Configuration::environment('sandbox');
43
- $this->setExpectedException('Braintree\Exception\SSLCertificate');
44
- $http = new Braintree\Http(Braintree\Configuration::$global);
45
- //ip address of api.braintreegateway.com
46
- $http->_doUrlRequest('get', '204.109.13.121');
47
- } catch (Braintree\Exception $e) {
48
- Braintree\Configuration::environment('development');
49
- throw $e;
50
- }
51
- Braintree\Configuration::environment('development');
52
- }
53
-
54
- public function testAuthorizationWithConfig()
55
- {
56
- $config = new Braintree\Configuration([
57
- 'environment' => 'development',
58
- 'merchant_id' => 'integration_merchant_id',
59
- 'publicKey' => 'badPublicKey',
60
- 'privateKey' => 'badPrivateKey'
61
- ]);
62
-
63
- $http = new Braintree\Http($config);
64
- $result = $http->_doUrlRequest('GET', $config->baseUrl() . '/merchants/integration_merchant_id/customers');
65
- $this->assertEquals(401, $result['status']);
66
- }
67
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/MerchantAccountTest.php DELETED
@@ -1,431 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class MerchantAccountTest extends Setup
11
- {
12
- private static $deprecatedValidParams = [
13
- 'applicantDetails' => [
14
- 'companyName' => "Robot City",
15
- 'firstName' => "Joe",
16
- 'lastName' => "Bloggs",
17
- 'email' => "joe@bloggs.com",
18
- 'phone' => "555-555-5555",
19
- 'address' => [
20
- 'streetAddress' => "123 Credibility St.",
21
- 'postalCode' => "60606",
22
- 'locality' => "Chicago",
23
- 'region' => "IL",
24
- ],
25
- 'dateOfBirth' => "10/9/1980",
26
- 'ssn' => "123-00-1234",
27
- 'taxId' => "123456789",
28
- 'routingNumber' => "122100024",
29
- 'accountNumber' => "43759348798"
30
- ],
31
- 'tosAccepted' => true,
32
- 'masterMerchantAccountId' => "sandbox_master_merchant_account"
33
- ];
34
-
35
- private static $validParams = [
36
- 'individual' => [
37
- 'firstName' => "Joe",
38
- 'lastName' => "Bloggs",
39
- 'email' => "joe@bloggs.com",
40
- 'phone' => "555-555-5555",
41
- 'address' => [
42
- 'streetAddress' => "123 Credibility St.",
43
- 'postalCode' => "60606",
44
- 'locality' => "Chicago",
45
- 'region' => "IL",
46
- ],
47
- 'dateOfBirth' => "10/9/1980",
48
- 'ssn' => "123-00-1234",
49
- ],
50
- 'business' => [
51
- 'dbaName' => "Robot City",
52
- 'legalName' => "Robot City INC",
53
- 'taxId' => "123456789",
54
- ],
55
- 'funding' => [
56
- 'routingNumber' => "122100024",
57
- 'accountNumber' => "43759348798",
58
- 'destination' => Braintree\MerchantAccount::FUNDING_DESTINATION_BANK,
59
- 'descriptor' => 'Joes Bloggs MI',
60
- ],
61
- 'tosAccepted' => true,
62
- 'masterMerchantAccountId' => "sandbox_master_merchant_account"
63
- ];
64
-
65
- public function testCreate()
66
- {
67
- $result = Braintree\MerchantAccount::create(self::$validParams);
68
- $this->assertEquals(true, $result->success);
69
- $merchantAccount = $result->merchantAccount;
70
- $this->assertEquals(Braintree\MerchantAccount::STATUS_PENDING, $merchantAccount->status);
71
- $this->assertEquals("sandbox_master_merchant_account", $merchantAccount->masterMerchantAccount->id);
72
- }
73
-
74
- public function testGatewayCreate()
75
- {
76
- $gateway = new Braintree\Gateway([
77
- 'environment' => 'development',
78
- 'merchantId' => 'integration_merchant_id',
79
- 'publicKey' => 'integration_public_key',
80
- 'privateKey' => 'integration_private_key'
81
- ]);
82
- $result = $gateway->merchantAccount()->create(self::$validParams);
83
- $this->assertEquals(true, $result->success);
84
- $merchantAccount = $result->merchantAccount;
85
- $this->assertEquals(Braintree\MerchantAccount::STATUS_PENDING, $merchantAccount->status);
86
- $this->assertEquals("sandbox_master_merchant_account", $merchantAccount->masterMerchantAccount->id);
87
- }
88
-
89
- public function testCreateWithDeprecatedParameters()
90
- {
91
- Test\Helper::suppressDeprecationWarnings();
92
- $result = Braintree\MerchantAccount::create(self::$deprecatedValidParams);
93
- $this->assertEquals(true, $result->success);
94
- $merchantAccount = $result->merchantAccount;
95
- $this->assertEquals(Braintree\MerchantAccount::STATUS_PENDING, $merchantAccount->status);
96
- $this->assertEquals("sandbox_master_merchant_account", $merchantAccount->masterMerchantAccount->id);
97
- }
98
-
99
- public function testCreateWithId()
100
- {
101
- $rand = rand(1, 1000);
102
- $subMerchantAccountId = "sub_merchant_account_id" + $rand;
103
- $validParamsWithId = array_merge([], self::$validParams);
104
- $validParamsWithId['id'] = $subMerchantAccountId;
105
- $result = Braintree\MerchantAccount::create($validParamsWithId);
106
- $this->assertEquals(true, $result->success);
107
- $merchantAccount = $result->merchantAccount;
108
- $this->assertEquals(Braintree\MerchantAccount::STATUS_PENDING, $merchantAccount->status);
109
- $this->assertEquals("sandbox_master_merchant_account", $merchantAccount->masterMerchantAccount->id);
110
- $this->assertEquals("sub_merchant_account_id" + $rand, $merchantAccount->id);
111
- }
112
-
113
- public function testFailedCreate()
114
- {
115
- $result = Braintree\MerchantAccount::create([]);
116
- $this->assertEquals(false, $result->success);
117
- $errors = $result->errors->forKey('merchantAccount')->onAttribute('masterMerchantAccountId');
118
- $this->assertEquals(Braintree\Error\Codes::MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED, $errors[0]->code);
119
- }
120
-
121
- public function testCreateWithFundingDestination()
122
- {
123
- $params = array_merge([], self::$validParams);
124
- $params['funding']['destination'] = Braintree\MerchantAccount::FUNDING_DESTINATION_BANK;
125
- $result = Braintree\MerchantAccount::create($params);
126
- $this->assertEquals(true, $result->success);
127
-
128
- $params = array_merge([], self::$validParams);
129
- $params['funding']['destination'] = Braintree\MerchantAccount::FUNDING_DESTINATION_EMAIL;
130
- $params['funding']['email'] = "billgates@outlook.com";
131
- $result = Braintree\MerchantAccount::create($params);
132
- $this->assertEquals(true, $result->success);
133
-
134
- $params = array_merge([], self::$validParams);
135
- $params['funding']['destination'] = Braintree\MerchantAccount::FUNDING_DESTINATION_MOBILE_PHONE;
136
- $params['funding']['mobilePhone'] = "1112224444";
137
- $result = Braintree\MerchantAccount::create($params);
138
- $this->assertEquals(true, $result->success);
139
- }
140
-
141
- public function testFind()
142
- {
143
- $params = array_merge([], self::$validParams);
144
- $result = Braintree\MerchantAccount::create(self::$validParams);
145
- $this->assertEquals(true, $result->success);
146
- $this->assertEquals(Braintree\MerchantAccount::STATUS_PENDING, $result->merchantAccount->status);
147
-
148
- $id = $result->merchantAccount->id;
149
- $merchantAccount = Braintree\MerchantAccount::find($id);
150
-
151
- $this->assertEquals(Braintree\MerchantAccount::STATUS_ACTIVE, $merchantAccount->status);
152
- $this->assertEquals($params['individual']['firstName'], $merchantAccount->individualDetails->firstName);
153
- $this->assertEquals($params['individual']['lastName'], $merchantAccount->individualDetails->lastName);
154
- }
155
-
156
- public function testRetrievesMasterMerchantAccountCurrencyIsoCode()
157
- {
158
- $merchantAccount = Braintree\MerchantAccount::find("sandbox_master_merchant_account");
159
-
160
- $this->assertEquals("USD", $merchantAccount->currencyIsoCode);
161
- }
162
-
163
- public function testFind_throwsIfNotFound()
164
- {
165
- $this->setExpectedException('Braintree\Exception\NotFound', 'merchant account with id does-not-exist not found');
166
- Braintree\MerchantAccount::find('does-not-exist');
167
- }
168
-
169
- public function testUpdate()
170
- {
171
- $params = array_merge([], self::$validParams);
172
- unset($params["tosAccepted"]);
173
- unset($params["masterMerchantAccountId"]);
174
- $params["individual"]["firstName"] = "John";
175
- $params["individual"]["lastName"] = "Doe";
176
- $params["individual"]["email"] = "john.doe@example.com";
177
- $params["individual"]["dateOfBirth"] = "1970-01-01";
178
- $params["individual"]["phone"] = "3125551234";
179
- $params["individual"]["address"]["streetAddress"] = "123 Fake St";
180
- $params["individual"]["address"]["locality"] = "Chicago";
181
- $params["individual"]["address"]["region"] = "IL";
182
- $params["individual"]["address"]["postalCode"] = "60622";
183
- $params["business"]["dbaName"] = "James's Bloggs";
184
- $params["business"]["legalName"] = "James's Bloggs Inc";
185
- $params["business"]["taxId"] = "123456789";
186
- $params["business"]["address"]["streetAddress"] = "999 Fake St";
187
- $params["business"]["address"]["locality"] = "Miami";
188
- $params["business"]["address"]["region"] = "FL";
189
- $params["business"]["address"]["postalCode"] = "99999";
190
- $params["funding"]["accountNumber"] = "43759348798";
191
- $params["funding"]["routingNumber"] = "071000013";
192
- $params["funding"]["email"] = "check@this.com";
193
- $params["funding"]["mobilePhone"] = "1234567890";
194
- $params["funding"]["destination"] = Braintree\MerchantAccount::FUNDING_DESTINATION_BANK;
195
- $params["funding"]["descriptor"] = "Joes Bloggs FL";
196
-
197
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
198
- $this->assertEquals(true, $result->success);
199
-
200
- $updatedMerchantAccount = $result->merchantAccount;
201
- $this->assertEquals("active", $updatedMerchantAccount->status);
202
- $this->assertEquals("sandbox_sub_merchant_account", $updatedMerchantAccount->id);
203
- $this->assertEquals("sandbox_master_merchant_account", $updatedMerchantAccount->masterMerchantAccount->id);
204
- $this->assertEquals("John", $updatedMerchantAccount->individualDetails->firstName);
205
- $this->assertEquals("Doe", $updatedMerchantAccount->individualDetails->lastName);
206
- $this->assertEquals("john.doe@example.com", $updatedMerchantAccount->individualDetails->email);
207
- $this->assertEquals("1970-01-01", $updatedMerchantAccount->individualDetails->dateOfBirth);
208
- $this->assertEquals("3125551234", $updatedMerchantAccount->individualDetails->phone);
209
- $this->assertEquals("123 Fake St", $updatedMerchantAccount->individualDetails->addressDetails->streetAddress);
210
- $this->assertEquals("Chicago", $updatedMerchantAccount->individualDetails->addressDetails->locality);
211
- $this->assertEquals("IL", $updatedMerchantAccount->individualDetails->addressDetails->region);
212
- $this->assertEquals("60622", $updatedMerchantAccount->individualDetails->addressDetails->postalCode);
213
- $this->assertEquals("James's Bloggs", $updatedMerchantAccount->businessDetails->dbaName);
214
- $this->assertEquals("James's Bloggs Inc", $updatedMerchantAccount->businessDetails->legalName);
215
- $this->assertEquals("123456789", $updatedMerchantAccount->businessDetails->taxId);
216
- $this->assertEquals("999 Fake St", $updatedMerchantAccount->businessDetails->addressDetails->streetAddress);
217
- $this->assertEquals("Miami", $updatedMerchantAccount->businessDetails->addressDetails->locality);
218
- $this->assertEquals("FL", $updatedMerchantAccount->businessDetails->addressDetails->region);
219
- $this->assertEquals("99999", $updatedMerchantAccount->businessDetails->addressDetails->postalCode);
220
- $this->assertEquals("8798", $updatedMerchantAccount->fundingDetails->accountNumberLast4);
221
- $this->assertEquals("071000013", $updatedMerchantAccount->fundingDetails->routingNumber);
222
- $this->assertEquals("check@this.com", $updatedMerchantAccount->fundingDetails->email);
223
- $this->assertEquals("1234567890", $updatedMerchantAccount->fundingDetails->mobilePhone);
224
- $this->assertEquals(Braintree\MerchantAccount::FUNDING_DESTINATION_BANK, $updatedMerchantAccount->fundingDetails->destination);
225
- $this->assertEquals("Joes Bloggs FL", $updatedMerchantAccount->fundingDetails->descriptor);
226
- }
227
-
228
- public function testUpdateDoesNotRequireAllFields()
229
- {
230
- $params = [
231
- 'individual' => [
232
- 'firstName' => "Joe"
233
- ]
234
- ];
235
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
236
- $this->assertEquals(true, $result->success);
237
- }
238
-
239
- public function testUpdateWithBlankFields()
240
- {
241
- $params = [
242
- 'individual' => [
243
- 'firstName' => "",
244
- 'lastName' => "",
245
- 'email' => "",
246
- 'phone' => "",
247
- 'address' => [
248
- 'streetAddress' => "",
249
- 'postalCode' => "",
250
- 'locality' => "",
251
- 'region' => "",
252
- ],
253
- 'dateOfBirth' => "",
254
- 'ssn' => "",
255
- ],
256
- 'business' => [
257
- 'dbaName' => "",
258
- 'legalName' => "",
259
- 'taxId' => "",
260
- ],
261
- 'funding' => [
262
- 'routingNumber' => "",
263
- 'accountNumber' => "",
264
- 'destination' => "",
265
- ],
266
- ];
267
-
268
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
269
- $this->assertEquals(false, $result->success);
270
-
271
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("firstName");
272
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED);
273
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("lastName");
274
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED);
275
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("dateOfBirth");
276
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED);
277
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("email");
278
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED);
279
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("streetAddress");
280
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED);
281
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("postalCode");
282
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED);
283
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("locality");
284
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED);
285
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("region");
286
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED);
287
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("destination");
288
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED);
289
- }
290
-
291
- public function testUpdateWithInvalidFields()
292
- {
293
- $params = [
294
- "individual" => [
295
- "firstName" => "<>",
296
- "lastName" => "<>",
297
- "email" => "bad",
298
- "phone" => "999",
299
- "address" => [
300
- "streetAddress" => "nope",
301
- "postalCode" => "1",
302
- "region" => "QQ",
303
- ],
304
- "dateOfBirth" => "hah",
305
- "ssn" => "12345",
306
- ],
307
- "business" => [
308
- "legalName" => "``{}",
309
- "dbaName" => "{}``",
310
- "taxId" => "bad",
311
- "address" => [
312
- "streetAddress" => "nope",
313
- "postalCode" => "1",
314
- "region" => "QQ",
315
- ],
316
- ],
317
- "funding" => [
318
- "destination" => "MY WALLET",
319
- "routingNumber" => "LEATHER",
320
- "accountNumber" => "BACK POCKET",
321
- "email" => "BILLFOLD",
322
- "mobilePhone" => "TRIFOLD"
323
- ],
324
- ];
325
-
326
-
327
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
328
- $this->assertEquals(false, $result->success);
329
-
330
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("firstName");
331
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID);
332
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("lastName");
333
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID);
334
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("email");
335
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID);
336
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("phone");
337
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID);
338
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("streetAddress");
339
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID);
340
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("postalCode");
341
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID);
342
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->forKey("address")->onAttribute("region");
343
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID);
344
- $error = $result->errors->forKey("merchantAccount")->forKey("individual")->onAttribute("ssn");
345
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID);
346
- ;
347
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("legalName");
348
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID);
349
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("dbaName");
350
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID);
351
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("taxId");
352
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID);
353
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->forKey("address")->onAttribute("streetAddress");
354
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID);
355
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->forKey("address")->onAttribute("postalCode");
356
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID);
357
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->forKey("address")->onAttribute("region");
358
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID);
359
-
360
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("destination");
361
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID);
362
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("routingNumber");
363
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID);
364
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("accountNumber");
365
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID);
366
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("email");
367
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID);
368
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("mobilePhone");
369
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID);
370
- }
371
-
372
- public function testUpdateWithInvalidBusinessFields()
373
- {
374
- $params = [
375
- "business" => [
376
- "legalName" => "",
377
- "taxId" => "111223333",
378
- ]
379
- ];
380
-
381
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
382
- $this->assertEquals(false, $result->success);
383
-
384
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("legalName");
385
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_REQUIRED_WITH_TAX_ID);
386
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("taxId");
387
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_TAX_ID_MUST_BE_BLANK);
388
-
389
- $params = [
390
- "business" => [
391
- "legalName" => "legal name",
392
- "taxId" => "",
393
- ]
394
- ];
395
-
396
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
397
- $this->assertEquals(false, $result->success);
398
-
399
- $error = $result->errors->forKey("merchantAccount")->forKey("business")->onAttribute("taxId");
400
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_REQUIRED_WITH_LEGAL_NAME);
401
- }
402
-
403
- public function testUpdateWithInvalidFundingFields()
404
- {
405
- $params = [
406
- "funding" => [
407
- "destination" => Braintree\MerchantAccount::FUNDING_DESTINATION_EMAIL,
408
- "email" => "",
409
- ]
410
- ];
411
-
412
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
413
- $this->assertEquals(false, $result->success);
414
-
415
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("email");
416
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_REQUIRED);
417
-
418
- $params = [
419
- "funding" => [
420
- "destination" => Braintree\MerchantAccount::FUNDING_DESTINATION_MOBILE_PHONE,
421
- "mobilePhone" => "",
422
- ]
423
- ];
424
-
425
- $result = Braintree\MerchantAccount::update("sandbox_sub_merchant_account", $params);
426
- $this->assertEquals(false, $result->success);
427
-
428
- $error = $result->errors->forKey("merchantAccount")->forKey("funding")->onAttribute("mobilePhone");
429
- $this->assertEquals($error[0]->code, Braintree\Error\Codes::MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_REQUIRED);
430
- }
431
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/MerchantTest.php DELETED
@@ -1,62 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class MerchantTest extends Setup
11
- {
12
- public function testCreateMerchant()
13
- {
14
- $gateway = new Braintree\Gateway([
15
- 'clientId' => 'client_id$development$integration_client_id',
16
- 'clientSecret' => 'client_secret$development$integration_client_secret',
17
- ]);
18
- $result = $gateway->merchant()->create([
19
- 'email' => 'name@email.com',
20
- 'countryCodeAlpha3' => 'USA',
21
- 'paymentMethods' => ['credit_card', 'paypal'],
22
- ]);
23
-
24
- $this->assertEquals(true, $result->success);
25
- $merchant = $result->merchant;
26
- $this->assertNotNull($merchant->id);
27
- $credentials = $result->credentials;
28
- $this->assertNotNull($credentials->accessToken);
29
- }
30
-
31
- /**
32
- * @expectedException Braintree\Exception\Configuration
33
- * @expectedExceptionMessage clientId needs to be passed to Braintree\Gateway
34
- */
35
- public function testAssertsHasCredentials()
36
- {
37
- $gateway = new Braintree\Gateway([
38
- 'clientSecret' => 'client_secret$development$integration_client_secret',
39
- ]);
40
- $gateway->merchant()->create([
41
- 'email' => 'name@email.com',
42
- 'countryCodeAlpha3' => 'USA',
43
- ]);
44
- }
45
-
46
- public function testBadPaymentMethods()
47
- {
48
- $gateway = new Braintree\Gateway([
49
- 'clientId' => 'client_id$development$integration_client_id',
50
- 'clientSecret' => 'client_secret$development$integration_client_secret',
51
- ]);
52
- $result = $gateway->merchant()->create([
53
- 'email' => 'name@email.com',
54
- 'countryCodeAlpha3' => 'USA',
55
- 'paymentMethods' => ['fake_money'],
56
- ]);
57
-
58
- $this->assertEquals(false, $result->success);
59
- $errors = $result->errors->forKey('merchant')->onAttribute('paymentMethods');
60
- $this->assertEquals(Braintree\Error\Codes::MERCHANT_ACCOUNT_PAYMENT_METHODS_ARE_INVALID, $errors[0]->code);
61
- }
62
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/MultipleValueNodeTest.php DELETED
@@ -1,94 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class MultipleValueNodeTest extends Setup
11
- {
12
- public function testIn_singleValue()
13
- {
14
- $creditCard = SubscriptionHelper::createCreditCard();
15
- $triallessPlan = SubscriptionHelper::triallessPlan();
16
-
17
- $activeSubscription = Braintree\Subscription::create([
18
- 'paymentMethodToken' => $creditCard->token,
19
- 'planId' => $triallessPlan['id'],
20
- 'price' => '3'
21
- ])->subscription;
22
-
23
- $canceledSubscription = Braintree\Subscription::create([
24
- 'paymentMethodToken' => $creditCard->token,
25
- 'planId' => $triallessPlan['id'],
26
- 'price' => '3'
27
- ])->subscription;
28
- Braintree\Subscription::cancel($canceledSubscription->id);
29
-
30
- $collection = Braintree\Subscription::search([
31
- Braintree\SubscriptionSearch::status()->in([Braintree\Subscription::ACTIVE]),
32
- Braintree\SubscriptionSearch::price()->is('3'),
33
- ]);
34
- foreach ($collection AS $item) {
35
- $this->assertEquals(Braintree\Subscription::ACTIVE, $item->status);
36
- }
37
-
38
- $this->assertTrue(Test\Helper::includes($collection, $activeSubscription));
39
- $this->assertFalse(Test\Helper::includes($collection, $canceledSubscription));
40
- }
41
-
42
- public function testIs()
43
- {
44
- $found = false;
45
- $collection = Braintree\Subscription::search([
46
- Braintree\SubscriptionSearch::status()->is(Braintree\Subscription::PAST_DUE)
47
- ]);
48
- foreach ($collection AS $item) {
49
- $found = true;
50
- $this->assertEquals(Braintree\Subscription::PAST_DUE, $item->status);
51
- }
52
- $this->assertTrue($found);
53
- }
54
-
55
- public function testSearch_statusIsExpired()
56
- {
57
- $found = false;
58
- $collection = Braintree\Subscription::search([
59
- Braintree\SubscriptionSearch::status()->in([Braintree\Subscription::EXPIRED])
60
- ]);
61
- foreach ($collection AS $item) {
62
- $found = true;
63
- $this->assertEquals(Braintree\Subscription::EXPIRED, $item->status);
64
- }
65
- $this->assertTrue($found);
66
- }
67
-
68
- public function testIn_multipleValues()
69
- {
70
- $creditCard = SubscriptionHelper::createCreditCard();
71
- $triallessPlan = SubscriptionHelper::triallessPlan();
72
-
73
- $activeSubscription = Braintree\Subscription::create([
74
- 'paymentMethodToken' => $creditCard->token,
75
- 'planId' => $triallessPlan['id'],
76
- 'price' => '4'
77
- ])->subscription;
78
-
79
- $canceledSubscription = Braintree\Subscription::create([
80
- 'paymentMethodToken' => $creditCard->token,
81
- 'planId' => $triallessPlan['id'],
82
- 'price' => '4'
83
- ])->subscription;
84
- Braintree\Subscription::cancel($canceledSubscription->id);
85
-
86
- $collection = Braintree\Subscription::search([
87
- Braintree\SubscriptionSearch::status()->in([Braintree\Subscription::ACTIVE, Braintree\Subscription::CANCELED]),
88
- Braintree\SubscriptionSearch::price()->is('4')
89
- ]);
90
-
91
- $this->assertTrue(Test\Helper::includes($collection, $activeSubscription));
92
- $this->assertTrue(Test\Helper::includes($collection, $canceledSubscription));
93
- }
94
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/OAuthTest.php DELETED
@@ -1,298 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class OAuthTest extends Setup
11
- {
12
- public function testCreateTokenFromCode()
13
- {
14
- $gateway = new Braintree\Gateway([
15
- 'clientId' => 'client_id$development$integration_client_id',
16
- 'clientSecret' => 'client_secret$development$integration_client_secret'
17
- ]);
18
- $code = Test\Braintree\OAuthTestHelper::createGrant($gateway, [
19
- 'merchant_public_id' => 'integration_merchant_id',
20
- 'scope' => 'read_write'
21
- ]);
22
- $result = $gateway->oauth()->createTokenFromCode([
23
- 'code' => $code,
24
- 'scope' => 'read_write',
25
- ]);
26
-
27
- $this->assertEquals(true, $result->success);
28
- $credentials = $result->credentials;
29
- $this->assertNotNull($credentials->accessToken);
30
- $this->assertNotNull($credentials->refreshToken);
31
- $this->assertEquals('bearer', $credentials->tokenType);
32
- $this->assertNotNull($credentials->expiresAt);
33
- }
34
-
35
- /**
36
- * @expectedException Braintree\Exception\Configuration
37
- * @expectedExceptionMessage clientSecret needs to be passed to Braintree\Gateway.
38
- */
39
- public function testAssertsHasCredentials()
40
- {
41
- $gateway = new Braintree\Gateway([
42
- 'clientId' => 'client_id$development$integration_client_id'
43
- ]);
44
- $gateway->oauth()->createTokenFromCode([
45
- 'code' => 'integration_oauth_auth_code_' . rand(0,299)
46
- ]);
47
- }
48
-
49
-
50
- public function testCreateTokenFromCodeWithMixedCredentials()
51
- {
52
- $gateway = new Braintree\Gateway([
53
- 'clientId' => 'client_id$development$integration_client_id',
54
- 'clientSecret' => 'client_secret$development$integration_client_secret',
55
- 'accessToken' => 'access_token$development$integration_merchant_id$f9ac33b3dd',
56
- ]);
57
- $code = Test\Braintree\OAuthTestHelper::createGrant($gateway, [
58
- 'merchant_public_id' => 'integration_merchant_id',
59
- 'scope' => 'read_write'
60
- ]);
61
- $result = $gateway->oauth()->createTokenFromCode([
62
- 'code' => $code,
63
- 'scope' => 'read_write',
64
- ]);
65
-
66
- $this->assertEquals(true, $result->success);
67
- $credentials = $result->credentials;
68
- $this->assertNotNull($credentials->accessToken);
69
- $this->assertNotNull($credentials->refreshToken);
70
- $this->assertEquals('bearer', $credentials->tokenType);
71
- $this->assertNotNull($credentials->expiresAt);
72
- }
73
-
74
- public function testCreateTokenFromCode_JsonAPI()
75
- {
76
- $gateway = new Braintree\Gateway([
77
- 'clientId' => 'client_id$development$integration_client_id',
78
- 'clientSecret' => 'client_secret$development$integration_client_secret'
79
- ]);
80
- $code = Test\Braintree\OAuthTestHelper::createGrant($gateway, [
81
- 'merchant_public_id' => 'integration_merchant_id',
82
- 'scope' => 'read_write'
83
- ]);
84
- $result = $gateway->oauth()->createTokenFromCode([
85
- 'code' => $code,
86
- 'scope' => 'read_write',
87
- ]);
88
-
89
- $this->assertEquals(true, $result->success);
90
- $this->assertNotNull($result->accessToken);
91
- $this->assertNotNull($result->refreshToken);
92
- $this->assertEquals('bearer', $result->tokenType);
93
- $this->assertNotNull($result->expiresAt);
94
- }
95
-
96
- public function testCreateTokenFromCode_ValidationErrorTest()
97
- {
98
- $gateway = new Braintree\Gateway([
99
- 'clientId' => 'client_id$development$integration_client_id',
100
- 'clientSecret' => 'client_secret$development$integration_client_secret'
101
- ]);
102
- $result = $gateway->oauth()->createTokenFromCode([
103
- 'code' => 'bad_code',
104
- 'scope' => 'read_write',
105
- ]);
106
-
107
- $this->assertEquals(false, $result->success);
108
- $errors = $result->errors->forKey('credentials')->onAttribute('code');
109
- $this->assertEquals(Braintree\Error\Codes::OAUTH_INVALID_GRANT, $errors[0]->code);
110
- $this->assertEquals(1, preg_match('/Invalid grant: code not found/', $result->message));
111
- }
112
-
113
- public function testCreateTokenFromCode_OldError()
114
- {
115
- $gateway = new Braintree\Gateway([
116
- 'clientId' => 'client_id$development$integration_client_id',
117
- 'clientSecret' => 'client_secret$development$integration_client_secret'
118
- ]);
119
- $result = $gateway->oauth()->createTokenFromCode([
120
- 'code' => 'bad_code',
121
- 'scope' => 'read_write',
122
- ]);
123
-
124
- $this->assertEquals(false, $result->success);
125
- $this->assertEquals('invalid_grant', $result->error);
126
- $this->assertEquals('code not found', $result->errorDescription);
127
- }
128
-
129
- public function testCreateTokenFromRefreshToken()
130
- {
131
- $gateway = new Braintree\Gateway([
132
- 'clientId' => 'client_id$development$integration_client_id',
133
- 'clientSecret' => 'client_secret$development$integration_client_secret'
134
- ]);
135
- $code = Test\Braintree\OAuthTestHelper::createGrant($gateway, [
136
- 'merchant_public_id' => 'integration_merchant_id',
137
- 'scope' => 'read_write'
138
- ]);
139
- $refreshToken = $gateway->oauth()->createTokenFromCode([
140
- 'code' => $code,
141
- 'scope' => 'read_write',
142
- ])->credentials->refreshToken;
143
-
144
- $result = $gateway->oauth()->createTokenFromRefreshToken([
145
- 'refreshToken' => $refreshToken,
146
- 'scope' => 'read_write',
147
- ]);
148
-
149
- $this->assertEquals(true, $result->success);
150
- $credentials = $result->credentials;
151
- $this->assertNotNull($credentials->accessToken);
152
- $this->assertNotNull($credentials->refreshToken);
153
- $this->assertEquals('bearer', $credentials->tokenType);
154
- $this->assertNotNull($credentials->expiresAt);
155
- }
156
-
157
-
158
- public function testBuildConnectUrl()
159
- {
160
- $gateway = new Braintree\Gateway([
161
- 'clientId' => 'client_id$development$integration_client_id',
162
- 'clientSecret' => 'client_secret$development$integration_client_secret'
163
- ]);
164
- $url = $gateway->oauth()->connectUrl([
165
- 'merchantId' => 'integration_merchant_id',
166
- 'redirectUri' => 'http://bar.example.com',
167
- 'scope' => 'read_write',
168
- 'state' => 'baz_state',
169
- 'user' => [
170
- 'country' => 'USA',
171
- 'email' => 'foo@example.com',
172
- 'firstName' => 'Bob',
173
- 'lastName' => 'Jones',
174
- 'phone' => '555-555-5555',
175
- 'dobYear' => '1970',
176
- 'dobMonth' => '01',
177
- 'dobDay' => '01',
178
- 'streetAddress' => '222 W Merchandise Mart',
179
- 'locality' => 'Chicago',
180
- 'region' => 'IL',
181
- 'postalCode' => '60606',
182
- ],
183
- 'business' => [
184
- 'name' => '14 Ladders',
185
- 'registeredAs' => '14.0 Ladders',
186
- 'industry' => 'Ladders',
187
- 'description' => 'We sell the best ladders',
188
- 'streetAddress' => '111 N Canal',
189
- 'locality' => 'Chicago',
190
- 'region' => 'IL',
191
- 'postalCode' => '60606',
192
- 'country' => 'USA',
193
- 'annualVolumeAmount' => '1000000',
194
- 'averageTransactionAmount' => '100',
195
- 'maximumTransactionAmount' => '10000',
196
- 'shipPhysicalGoods' => true,
197
- 'fulfillmentCompletedIn' => 7,
198
- 'currency' => 'USD',
199
- 'website' => 'http://example.com',
200
- ],
201
- 'paymentMethods' => ['credit_card'],
202
- ]);
203
-
204
- $components = parse_url($url);
205
- $queryString = $components['query'];
206
- parse_str($queryString, $query);
207
-
208
- $this->assertEquals('localhost', $components['host']);
209
- $this->assertEquals('/oauth/connect', $components['path']);
210
- $this->assertEquals('integration_merchant_id', $query['merchant_id']);
211
- $this->assertEquals('client_id$development$integration_client_id', $query['client_id']);
212
- $this->assertEquals('http://bar.example.com', $query['redirect_uri']);
213
- $this->assertEquals('read_write', $query['scope']);
214
- $this->assertEquals('baz_state', $query['state']);
215
-
216
- $this->assertEquals('USA', $query['user']['country']);
217
- $this->assertEquals('foo@example.com', $query['user']['email']);
218
- $this->assertEquals('Bob', $query['user']['first_name']);
219
- $this->assertEquals('Jones', $query['user']['last_name']);
220
- $this->assertEquals('555-555-5555', $query['user']['phone']);
221
- $this->assertEquals('1970', $query['user']['dob_year']);
222
- $this->assertEquals('01', $query['user']['dob_month']);
223
- $this->assertEquals('01', $query['user']['dob_day']);
224
- $this->assertEquals('222 W Merchandise Mart', $query['user']['street_address']);
225
- $this->assertEquals('Chicago', $query['user']['locality']);
226
- $this->assertEquals('IL', $query['user']['region']);
227
- $this->assertEquals('60606', $query['user']['postal_code']);
228
-
229
- $this->assertEquals('14 Ladders', $query['business']['name']);
230
- $this->assertEquals('14.0 Ladders', $query['business']['registered_as']);
231
- $this->assertEquals('Ladders', $query['business']['industry']);
232
- $this->assertEquals('We sell the best ladders', $query['business']['description']);
233
- $this->assertEquals('111 N Canal', $query['business']['street_address']);
234
- $this->assertEquals('Chicago', $query['business']['locality']);
235
- $this->assertEquals('IL', $query['business']['region']);
236
- $this->assertEquals('60606', $query['business']['postal_code']);
237
- $this->assertEquals('USA', $query['business']['country']);
238
- $this->assertEquals('1000000', $query['business']['annual_volume_amount']);
239
- $this->assertEquals('100', $query['business']['average_transaction_amount']);
240
- $this->assertEquals('10000', $query['business']['maximum_transaction_amount']);
241
- $this->assertEquals(true, $query['business']['ship_physical_goods']);
242
- $this->assertEquals(7, $query['business']['fulfillment_completed_in']);
243
- $this->assertEquals('USD', $query['business']['currency']);
244
- $this->assertEquals('http://example.com', $query['business']['website']);
245
-
246
- $this->assertCount(1, $query['payment_methods']);
247
- $this->assertEquals('credit_card', $query['payment_methods'][0]);
248
-
249
- $this->assertEquals(64, strlen($query['signature']));
250
- $this->assertEquals('SHA256', $query['algorithm']);
251
- }
252
-
253
- public function testBuildConnectUrlWithoutOptionalParams()
254
- {
255
- $gateway = new Braintree\Gateway([
256
- 'clientId' => 'client_id$development$integration_client_id',
257
- 'clientSecret' => 'client_secret$development$integration_client_secret'
258
- ]);
259
- $url = $gateway->oauth()->connectUrl();
260
-
261
- $queryString = parse_url($url)['query'];
262
- parse_str($queryString, $query);
263
-
264
- $this->assertEquals('client_id$development$integration_client_id', $query['client_id']);
265
- $this->assertArrayNotHasKey('merchant_id', $query);
266
- $this->assertArrayNotHasKey('redirect_uri', $query);
267
- $this->assertArrayNotHasKey('scope', $query);
268
- }
269
-
270
- public function testBuildConnectUrlWithPaymentMethods()
271
- {
272
- $gateway = new Braintree\Gateway([
273
- 'clientId' => 'client_id$development$integration_client_id',
274
- 'clientSecret' => 'client_secret$development$integration_client_secret'
275
- ]);
276
- $url = $gateway->oauth()->connectUrl([
277
- 'paymentMethods' => ['credit_card', 'paypal']
278
- ]);
279
-
280
- $queryString = parse_url($url)['query'];
281
- parse_str($queryString, $query);
282
-
283
- $this->assertEquals(['credit_card', 'paypal'], $query['payment_methods']);
284
- }
285
-
286
- public function testComputeSignature()
287
- {
288
- $gateway = new Braintree\Gateway([
289
- 'clientId' => 'client_id$development$integration_client_id',
290
- 'clientSecret' => 'client_secret$development$integration_client_secret'
291
- ]);
292
- $urlToSign = 'http://localhost:3000/oauth/connect?business%5Bname%5D=We+Like+Spaces&client_id=client_id%24development%24integration_client_id';
293
-
294
- $signature = $gateway->oauth()->computeSignature($urlToSign);
295
-
296
- $this->assertEquals("a36bcf10dd982e2e47e0d6a2cb930aea47ade73f954b7d59c58dae6167894d41", $signature);
297
- }
298
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/PayPalAccountTest.php DELETED
@@ -1,309 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class PayPalAccountTest extends Setup
10
- {
11
- public function testFind()
12
- {
13
- $paymentMethodToken = 'PAYPALToken-' . strval(rand());
14
- $customer = Braintree\Customer::createNoValidate();
15
- $http = new HttpClientApi(Braintree\Configuration::$global);
16
- $nonce = $http->nonceForPayPalAccount([
17
- 'paypal_account' => [
18
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
19
- 'token' => $paymentMethodToken
20
- ]
21
- ]);
22
-
23
- Braintree\PaymentMethod::create([
24
- 'customerId' => $customer->id,
25
- 'paymentMethodNonce' => $nonce
26
- ]);
27
-
28
- $foundPayPalAccount = Braintree\PayPalAccount::find($paymentMethodToken);
29
-
30
- $this->assertSame('jane.doe@example.com', $foundPayPalAccount->email);
31
- $this->assertSame($paymentMethodToken, $foundPayPalAccount->token);
32
- $this->assertNotNull($foundPayPalAccount->imageUrl);
33
- }
34
-
35
- public function testGatewayFind()
36
- {
37
- $paymentMethodToken = 'PAYPALToken-' . strval(rand());
38
- $customer = Braintree\Customer::createNoValidate();
39
- $http = new HttpClientApi(Braintree\Configuration::$global);
40
- $nonce = $http->nonceForPayPalAccount([
41
- 'paypal_account' => [
42
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
43
- 'token' => $paymentMethodToken
44
- ]
45
- ]);
46
-
47
- Braintree\PaymentMethod::create([
48
- 'customerId' => $customer->id,
49
- 'paymentMethodNonce' => $nonce
50
- ]);
51
-
52
- $gateway = new Braintree\Gateway([
53
- 'environment' => 'development',
54
- 'merchantId' => 'integration_merchant_id',
55
- 'publicKey' => 'integration_public_key',
56
- 'privateKey' => 'integration_private_key'
57
- ]);
58
- $foundPayPalAccount = $gateway->paypalAccount()->find($paymentMethodToken);
59
-
60
- $this->assertSame('jane.doe@example.com', $foundPayPalAccount->email);
61
- $this->assertSame($paymentMethodToken, $foundPayPalAccount->token);
62
- $this->assertNotNull($foundPayPalAccount->imageUrl);
63
- }
64
-
65
- public function testFind_doesNotReturnIncorrectPaymentMethodType()
66
- {
67
- $creditCardToken = 'creditCardToken-' . strval(rand());
68
- $customer = Braintree\Customer::createNoValidate();
69
- $result = Braintree\CreditCard::create([
70
- 'customerId' => $customer->id,
71
- 'cardholderName' => 'Cardholder',
72
- 'number' => '5105105105105100',
73
- 'expirationDate' => '05/12',
74
- 'token' => $creditCardToken
75
- ]);
76
- $this->assertTrue($result->success);
77
-
78
- $this->setExpectedException('Braintree\Exception\NotFound');
79
- Braintree\PayPalAccount::find($creditCardToken);
80
- }
81
-
82
- public function test_PayPalAccountExposesTimestamps()
83
- {
84
- $customer = Braintree\Customer::createNoValidate();
85
- $result = Braintree\PaymentMethod::create([
86
- 'customerId' => $customer->id,
87
- 'paymentMethodNonce' => Braintree\Test\Nonces::$paypalFuturePayment,
88
- ]);
89
- $this->assertTrue($result->success);
90
-
91
- $this->assertNotNull($result->paymentMethod->createdAt);
92
- $this->assertNotNull($result->paymentMethod->updatedAt);
93
- }
94
-
95
- public function test_PayPalAccountExposesBillingAgreementId()
96
- {
97
- $customer = Braintree\Customer::createNoValidate();
98
- $result = Braintree\PaymentMethod::create([
99
- 'customerId' => $customer->id,
100
- 'paymentMethodNonce' => Braintree\Test\Nonces::$paypalBillingAgreement
101
- ]);
102
- $this->assertTrue($result->success);
103
-
104
- $foundPayPalAccount = Braintree\PayPalAccount::find($result->paymentMethod->token);
105
-
106
- $this->assertNotNull($foundPayPalAccount->billingAgreementId);
107
- }
108
-
109
- public function testFind_throwsIfCannotBeFound()
110
- {
111
- $this->setExpectedException('Braintree\Exception\NotFound');
112
- Braintree\PayPalAccount::find('invalid-token');
113
- }
114
-
115
- public function testFind_throwsUsefulErrorMessagesWhenEmpty()
116
- {
117
- $this->setExpectedException('InvalidArgumentException', 'expected paypal account id to be set');
118
- Braintree\PayPalAccount::find('');
119
- }
120
-
121
- public function testFind_throwsUsefulErrorMessagesWhenInvalid()
122
- {
123
- $this->setExpectedException('InvalidArgumentException', '@ is an invalid paypal account token');
124
- Braintree\PayPalAccount::find('@');
125
- }
126
-
127
- public function testFind_returnsSubscriptionsAssociatedWithAPaypalAccount()
128
- {
129
- $customer = Braintree\Customer::createNoValidate();
130
- $paymentMethodToken = 'paypal-account-' . strval(rand());
131
-
132
- $http = new HttpClientApi(Braintree\Configuration::$global);
133
- $nonce = $http->nonceForPayPalAccount([
134
- 'paypal_account' => [
135
- 'consent_code' => 'consent-code',
136
- 'token' => $paymentMethodToken
137
- ]
138
- ]);
139
-
140
- $result = Braintree\PaymentMethod::create([
141
- 'paymentMethodNonce' => $nonce,
142
- 'customerId' => $customer->id
143
- ]);
144
- $this->assertTrue($result->success);
145
-
146
- $token = $result->paymentMethod->token;
147
- $triallessPlan = SubscriptionHelper::triallessPlan();
148
-
149
- $subscription1 = Braintree\Subscription::create([
150
- 'paymentMethodToken' => $token,
151
- 'planId' => $triallessPlan['id']
152
- ])->subscription;
153
-
154
- $subscription2 = Braintree\Subscription::create([
155
- 'paymentMethodToken' => $token,
156
- 'planId' => $triallessPlan['id']
157
- ])->subscription;
158
-
159
- $paypalAccount = Braintree\PayPalAccount::find($token);
160
- $getIds = function($sub) { return $sub->id; };
161
- $subIds = array_map($getIds, $paypalAccount->subscriptions);
162
- $this->assertTrue(in_array($subscription1->id, $subIds));
163
- $this->assertTrue(in_array($subscription2->id, $subIds));
164
- }
165
-
166
- public function testUpdate()
167
- {
168
- $originalToken = 'ORIGINAL_PAYPALToken-' . strval(rand());
169
- $customer = Braintree\Customer::createNoValidate();
170
- $http = new HttpClientApi(Braintree\Configuration::$global);
171
- $nonce = $http->nonceForPayPalAccount([
172
- 'paypal_account' => [
173
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
174
- 'token' => $originalToken
175
- ]
176
- ]);
177
-
178
- $createResult = Braintree\PaymentMethod::create([
179
- 'customerId' => $customer->id,
180
- 'paymentMethodNonce' => $nonce
181
- ]);
182
- $this->assertTrue($createResult->success);
183
-
184
- $newToken = 'NEW_PAYPALToken-' . strval(rand());
185
- $updateResult = Braintree\PayPalAccount::update($originalToken, [
186
- 'token' => $newToken
187
- ]);
188
-
189
- $this->assertTrue($updateResult->success);
190
- $this->assertEquals($newToken, $updateResult->paypalAccount->token);
191
-
192
- $this->setExpectedException('Braintree\Exception\NotFound');
193
- Braintree\PayPalAccount::find($originalToken);
194
-
195
- }
196
-
197
- public function testUpdateAndMakeDefault()
198
- {
199
- $customer = Braintree\Customer::createNoValidate();
200
-
201
- $creditCardResult = Braintree\CreditCard::create([
202
- 'customerId' => $customer->id,
203
- 'number' => '5105105105105100',
204
- 'expirationDate' => '05/12'
205
- ]);
206
- $this->assertTrue($creditCardResult->success);
207
-
208
- $http = new HttpClientApi(Braintree\Configuration::$global);
209
- $nonce = $http->nonceForPayPalAccount([
210
- 'paypal_account' => [
211
- 'consent_code' => 'PAYPAL_CONSENT_CODE'
212
- ]
213
- ]);
214
-
215
- $createResult = Braintree\PaymentMethod::create([
216
- 'customerId' => $customer->id,
217
- 'paymentMethodNonce' => $nonce
218
- ]);
219
- $this->assertTrue($createResult->success);
220
-
221
- $updateResult = Braintree\PayPalAccount::update($createResult->paymentMethod->token, [
222
- 'options' => ['makeDefault' => true]
223
- ]);
224
-
225
- $this->assertTrue($updateResult->success);
226
- $this->assertTrue($updateResult->paypalAccount->isDefault());
227
- }
228
-
229
- public function testUpdate_handleErrors()
230
- {
231
- $customer = Braintree\Customer::createNoValidate();
232
-
233
- $firstToken = 'FIRST_PAYPALToken-' . strval(rand());
234
- $http = new HttpClientApi(Braintree\Configuration::$global);
235
- $firstNonce = $http->nonceForPayPalAccount([
236
- 'paypal_account' => [
237
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
238
- 'token' => $firstToken
239
- ]
240
- ]);
241
- $firstPaypalAccount = Braintree\PaymentMethod::create([
242
- 'customerId' => $customer->id,
243
- 'paymentMethodNonce' => $firstNonce
244
- ]);
245
- $this->assertTrue($firstPaypalAccount->success);
246
-
247
- $secondToken = 'SECOND_PAYPALToken-' . strval(rand());
248
- $http = new HttpClientApi(Braintree\Configuration::$global);
249
- $secondNonce = $http->nonceForPayPalAccount([
250
- 'paypal_account' => [
251
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
252
- 'token' => $secondToken
253
- ]
254
- ]);
255
- $secondPaypalAccount = Braintree\PaymentMethod::create([
256
- 'customerId' => $customer->id,
257
- 'paymentMethodNonce' => $secondNonce
258
- ]);
259
- $this->assertTrue($secondPaypalAccount->success);
260
-
261
- $updateResult = Braintree\PayPalAccount::update($firstToken, [
262
- 'token' => $secondToken
263
- ]);
264
-
265
- $this->assertFalse($updateResult->success);
266
- $errors = $updateResult->errors->forKey('paypalAccount')->errors;
267
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_TOKEN_IS_IN_USE, $errors[0]->code);
268
- }
269
-
270
- public function testDelete()
271
- {
272
- $paymentMethodToken = 'PAYPALToken-' . strval(rand());
273
- $customer = Braintree\Customer::createNoValidate();
274
- $http = new HttpClientApi(Braintree\Configuration::$global);
275
- $nonce = $http->nonceForPayPalAccount([
276
- 'paypal_account' => [
277
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
278
- 'token' => $paymentMethodToken
279
- ]
280
- ]);
281
-
282
- Braintree\PaymentMethod::create([
283
- 'customerId' => $customer->id,
284
- 'paymentMethodNonce' => $nonce
285
- ]);
286
-
287
- Braintree\PayPalAccount::delete($paymentMethodToken);
288
-
289
- $this->setExpectedException('Braintree\Exception\NotFound');
290
- Braintree\PayPalAccount::find($paymentMethodToken);
291
- }
292
-
293
- public function testSale_createsASaleUsingGivenToken()
294
- {
295
- $nonce = Braintree\Test\Nonces::$paypalFuturePayment;
296
- $customer = Braintree\Customer::createNoValidate([
297
- 'paymentMethodNonce' => $nonce
298
- ]);
299
- $paypalAccount = $customer->paypalAccounts[0];
300
-
301
- $result = Braintree\PayPalAccount::sale($paypalAccount->token, [
302
- 'amount' => '100.00'
303
- ]);
304
- $this->assertTrue($result->success);
305
- $this->assertEquals('100.00', $result->transaction->amount);
306
- $this->assertEquals($customer->id, $result->transaction->customerDetails->id);
307
- $this->assertEquals($paypalAccount->token, $result->transaction->paypalDetails->token);
308
- }
309
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/PaymentMethodNonceTest.php DELETED
@@ -1,70 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class PaymentMethodNonceTest extends Setup
10
- {
11
- public function testCreate_fromPaymentMethodToken()
12
- {
13
- $customer = Braintree\Customer::createNoValidate();
14
- $card = Braintree\CreditCard::create([
15
- 'customerId' => $customer->id,
16
- 'cardholderName' => 'Cardholder',
17
- 'number' => '5105105105105100',
18
- 'expirationDate' => '05/12',
19
- ])->creditCard;
20
-
21
- $result = Braintree\PaymentMethodNonce::create($card->token);
22
-
23
- $this->assertTrue($result->success);
24
- $this->assertNotNull($result->paymentMethodNonce);
25
- $this->assertNotNull($result->paymentMethodNonce->nonce);
26
- }
27
-
28
- public function testCreate_fromNonExistentPaymentMethodToken()
29
- {
30
- $this->setExpectedException('Braintree\Exception\NotFound');
31
- Braintree\PaymentMethodNonce::create('not_a_token');
32
- }
33
-
34
- public function testFind_exposesThreeDSecureInfo()
35
- {
36
- $nonce = Braintree\PaymentMethodNonce::find('threedsecurednonce');
37
- $info = $nonce->threeDSecureInfo;
38
-
39
- $this->assertEquals('threedsecurednonce', $nonce->nonce);
40
- $this->assertEquals('CreditCard', $nonce->type);
41
- $this->assertEquals('Y', $info->enrolled);
42
- $this->assertEquals('authenticate_successful', $info->status);
43
- $this->assertTrue($info->liabilityShifted);
44
- $this->assertTrue($info->liabilityShiftPossible);
45
- }
46
-
47
- public function testFind_exposesNullThreeDSecureInfoIfNoneExists()
48
- {
49
- $http = new HttpClientApi(Braintree\Configuration::$global);
50
- $nonce = $http->nonce_for_new_card([
51
- "creditCard" => [
52
- "number" => "4111111111111111",
53
- "expirationMonth" => "11",
54
- "expirationYear" => "2099"
55
- ]
56
- ]);
57
-
58
- $foundNonce = Braintree\PaymentMethodNonce::find($nonce);
59
- $info = $foundNonce->threeDSecureInfo;
60
-
61
- $this->assertEquals($nonce, $foundNonce->nonce);
62
- $this->assertNull($info);
63
- }
64
-
65
- public function testFind_nonExistantNonce()
66
- {
67
- $this->setExpectedException('Braintree\Exception\NotFound');
68
- Braintree\PaymentMethodNonce::find('not_a_nonce');
69
- }
70
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/PaymentMethodTest.php DELETED
@@ -1,1496 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class PaymentMethodTest extends Setup
11
- {
12
- public function testCreate_fromVaultedCreditCardNonce()
13
- {
14
- $customer = Braintree\Customer::createNoValidate();
15
- $http = new HttpClientApi(Braintree\Configuration::$global);
16
- $nonce = $http->nonce_for_new_card([
17
- 'credit_card' => [
18
- 'number' => '4111111111111111',
19
- 'expirationMonth' => '11',
20
- 'expirationYear' => '2099'
21
- ],
22
- 'share' => true
23
- ]);
24
-
25
- $result = Braintree\PaymentMethod::create([
26
- 'customerId' => $customer->id,
27
- 'paymentMethodNonce' => $nonce
28
- ]);
29
-
30
- $this->assertSame('411111', $result->paymentMethod->bin);
31
- $this->assertSame('1111', $result->paymentMethod->last4);
32
- $this->assertNotNull($result->paymentMethod->token);
33
- $this->assertNotNull($result->paymentMethod->imageUrl);
34
- $this->assertSame($customer->id, $result->paymentMethod->customerId);
35
- }
36
-
37
- public function testGatewayCreate_fromVaultedCreditCardNonce()
38
- {
39
- $customer = Braintree\Customer::createNoValidate();
40
- $http = new HttpClientApi(Braintree\Configuration::$global);
41
- $nonce = $http->nonce_for_new_card([
42
- 'credit_card' => [
43
- 'number' => '4111111111111111',
44
- 'expirationMonth' => '11',
45
- 'expirationYear' => '2099'
46
- ],
47
- 'share' => true
48
- ]);
49
-
50
- $gateway = new Braintree\Gateway([
51
- 'environment' => 'development',
52
- 'merchantId' => 'integration_merchant_id',
53
- 'publicKey' => 'integration_public_key',
54
- 'privateKey' => 'integration_private_key'
55
- ]);
56
- $result = $gateway->paymentMethod()->create([
57
- 'customerId' => $customer->id,
58
- 'paymentMethodNonce' => $nonce
59
- ]);
60
-
61
- $this->assertSame('411111', $result->paymentMethod->bin);
62
- $this->assertSame('1111', $result->paymentMethod->last4);
63
- $this->assertNotNull($result->paymentMethod->token);
64
- $this->assertNotNull($result->paymentMethod->imageUrl);
65
- $this->assertSame($customer->id, $result->paymentMethod->customerId);
66
- }
67
-
68
- public function testCreate_fromFakeApplePayNonce()
69
- {
70
- $customer = Braintree\Customer::createNoValidate();
71
- $result = Braintree\PaymentMethod::create([
72
- 'customerId' => $customer->id,
73
- 'paymentMethodNonce' => Braintree\Test\Nonces::$applePayVisa,
74
- ]);
75
-
76
- $this->assertTrue($result->success);
77
- $applePayCard = $result->paymentMethod;
78
- $this->assertNotNull($applePayCard->token);
79
- $this->assertSame(Braintree\ApplePayCard::VISA, $applePayCard->cardType);
80
- $this->assertContains("Visa ", $applePayCard->paymentInstrumentName);
81
- $this->assertContains("Visa ", $applePayCard->sourceDescription);
82
- $this->assertTrue($applePayCard->default);
83
- $this->assertContains('apple_pay', $applePayCard->imageUrl);
84
- $this->assertTrue(intval($applePayCard->expirationMonth) > 0);
85
- $this->assertTrue(intval($applePayCard->expirationYear) > 0);
86
- $this->assertSame($customer->id, $applePayCard->customerId);
87
- }
88
-
89
- public function testCreate_fromFakeAndroidPayProxyCardNonce()
90
- {
91
- $customer = Braintree\Customer::createNoValidate();
92
- $result = Braintree\PaymentMethod::create([
93
- 'customerId' => $customer->id,
94
- 'paymentMethodNonce' => Braintree\Test\Nonces::$androidPayDiscover
95
- ]);
96
-
97
- $this->assertTrue($result->success);
98
- $androidPayCard = $result->paymentMethod;
99
- $this->assertNotNull($androidPayCard->token);
100
- $this->assertSame(Braintree\CreditCard::DISCOVER, $androidPayCard->virtualCardType);
101
- $this->assertSame(Braintree\CreditCard::DISCOVER, $androidPayCard->cardType);
102
- $this->assertSame("1117", $androidPayCard->virtualCardLast4);
103
- $this->assertSame("1117", $androidPayCard->last4);
104
- $this->assertSame(Braintree\CreditCard::VISA, $androidPayCard->sourceCardType);
105
- $this->assertSame("1111", $androidPayCard->sourceCardLast4);
106
- $this->assertSame("Visa 1111", $androidPayCard->sourceDescription);
107
- $this->assertTrue($androidPayCard->default);
108
- $this->assertContains('android_pay', $androidPayCard->imageUrl);
109
- $this->assertTrue(intval($androidPayCard->expirationMonth) > 0);
110
- $this->assertTrue(intval($androidPayCard->expirationYear) > 0);
111
- $this->assertSame($customer->id, $androidPayCard->customerId);
112
- }
113
-
114
- public function testCreate_fromFakeAndroidPayNetworkTokenNonce()
115
- {
116
- $customer = Braintree\Customer::createNoValidate();
117
- $result = Braintree\PaymentMethod::create([
118
- 'customerId' => $customer->id,
119
- 'paymentMethodNonce' => Braintree\Test\Nonces::$androidPayMasterCard
120
- ]);
121
-
122
- $this->assertTrue($result->success);
123
- $androidPayCard = $result->paymentMethod;
124
- $this->assertNotNull($androidPayCard->token);
125
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCard->virtualCardType);
126
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCard->cardType);
127
- $this->assertSame("4444", $androidPayCard->virtualCardLast4);
128
- $this->assertSame("4444", $androidPayCard->last4);
129
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCard->sourceCardType);
130
- $this->assertSame("4444", $androidPayCard->sourceCardLast4);
131
- $this->assertSame("MasterCard 4444", $androidPayCard->sourceDescription);
132
- $this->assertTrue($androidPayCard->default);
133
- $this->assertContains('android_pay', $androidPayCard->imageUrl);
134
- $this->assertTrue(intval($androidPayCard->expirationMonth) > 0);
135
- $this->assertTrue(intval($androidPayCard->expirationYear) > 0);
136
- $this->assertSame($customer->id, $androidPayCard->customerId);
137
- }
138
-
139
- public function testCreate_fromFakeAmexExpressCheckoutCardNonce()
140
- {
141
- $customer = Braintree\Customer::createNoValidate();
142
- $result = Braintree\PaymentMethod::create([
143
- 'customerId' => $customer->id,
144
- 'paymentMethodNonce' => Braintree\Test\Nonces::$amexExpressCheckout
145
- ]);
146
-
147
- $this->assertTrue($result->success);
148
- $amexExpressCheckoutCard = $result->paymentMethod;
149
- $this->assertInstanceOf('Braintree\AmexExpressCheckoutCard', $amexExpressCheckoutCard);
150
-
151
- $this->assertNotNull($amexExpressCheckoutCard->token);
152
- $this->assertSame(Braintree\CreditCard::AMEX, $amexExpressCheckoutCard->cardType);
153
- $this->assertSame("341111", $amexExpressCheckoutCard->bin);
154
- $this->assertSame("12/21", $amexExpressCheckoutCard->cardMemberExpiryDate);
155
- $this->assertSame("0005", $amexExpressCheckoutCard->cardMemberNumber);
156
- $this->assertSame("American Express", $amexExpressCheckoutCard->cardType);
157
- $this->assertNotNull($amexExpressCheckoutCard->sourceDescription);
158
- $this->assertContains(".png", $amexExpressCheckoutCard->imageUrl);
159
- $this->assertTrue(intval($amexExpressCheckoutCard->expirationMonth) > 0);
160
- $this->assertTrue(intval($amexExpressCheckoutCard->expirationYear) > 0);
161
- $this->assertTrue($amexExpressCheckoutCard->default);
162
- $this->assertSame($customer->id, $amexExpressCheckoutCard->customerId);
163
- $this->assertEquals([], $amexExpressCheckoutCard->subscriptions);
164
- }
165
-
166
- public function testCreate_fromFakeVenmoAccountNonce()
167
- {
168
- $customer = Braintree\Customer::createNoValidate();
169
- $result = Braintree\PaymentMethod::create(array(
170
- 'customerId' => $customer->id,
171
- 'paymentMethodNonce' => Braintree\Test\Nonces::$venmoAccount
172
- ));
173
-
174
- $this->assertTrue($result->success);
175
- $venmoAccount = $result->paymentMethod;
176
- $this->assertInstanceOf('Braintree\VenmoAccount', $venmoAccount);
177
-
178
- $this->assertNotNull($venmoAccount->token);
179
- $this->assertNotNull($venmoAccount->sourceDescription);
180
- $this->assertContains(".png", $venmoAccount->imageUrl);
181
- $this->assertTrue($venmoAccount->default);
182
- $this->assertSame($customer->id, $venmoAccount->customerId);
183
- $this->assertEquals(array(), $venmoAccount->subscriptions);
184
- $this->assertSame("venmojoe", $venmoAccount->username);
185
- $this->assertSame("Venmo-Joe-1", $venmoAccount->venmoUserId);
186
- }
187
-
188
- public function testCreate_fromUnvalidatedCreditCardNonce()
189
- {
190
- $customer = Braintree\Customer::createNoValidate();
191
- $http = new HttpClientApi(Braintree\Configuration::$global);
192
- $nonce = $http->nonce_for_new_card([
193
- 'credit_card' => [
194
- 'number' => '4111111111111111',
195
- 'expirationMonth' => '11',
196
- 'expirationYear' => '2099',
197
- 'options' => [
198
- 'validate' => false
199
- ]
200
- ]
201
- ]);
202
-
203
- $result = Braintree\PaymentMethod::create([
204
- 'customerId' => $customer->id,
205
- 'paymentMethodNonce' => $nonce
206
- ]);
207
-
208
- $this->assertSame('411111', $result->paymentMethod->bin);
209
- $this->assertSame('1111', $result->paymentMethod->last4);
210
- $this->assertSame($customer->id, $result->paymentMethod->customerId);
211
- $this->assertNotNull($result->paymentMethod->token);
212
- }
213
-
214
- public function testCreate_fromUnvalidatedFuturePaypalAccountNonce()
215
- {
216
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
217
- $customer = Braintree\Customer::createNoValidate();
218
- $http = new HttpClientApi(Braintree\Configuration::$global);
219
- $nonce = $http->nonceForPayPalAccount([
220
- 'paypal_account' => [
221
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
222
- 'token' => $paymentMethodToken
223
- ]
224
- ]);
225
-
226
- $result = Braintree\PaymentMethod::create([
227
- 'customerId' => $customer->id,
228
- 'paymentMethodNonce' => $nonce
229
- ]);
230
-
231
- $this->assertSame('jane.doe@example.com', $result->paymentMethod->email);
232
- $this->assertSame($paymentMethodToken, $result->paymentMethod->token);
233
- $this->assertSame($customer->id, $result->paymentMethod->customerId);
234
- }
235
-
236
- public function testCreate_fromAbstractPaymentMethodNonce()
237
- {
238
- $customer = Braintree\Customer::createNoValidate();
239
-
240
- $result = Braintree\PaymentMethod::create([
241
- 'customerId' => $customer->id,
242
- 'paymentMethodNonce' => Braintree\Test\Nonces::$abstractTransactable,
243
- ]);
244
-
245
- $this->assertTrue($result->success);
246
- $this->assertNotNull($result->paymentMethod->token);
247
- $this->assertSame($customer->id, $result->paymentMethod->customerId);
248
- }
249
-
250
- public function testCreate_doesNotWorkForUnvalidatedOnetimePaypalAccountNonce()
251
- {
252
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
253
- $customer = Braintree\Customer::createNoValidate();
254
- $http = new HttpClientApi(Braintree\Configuration::$global);
255
- $nonce = $http->nonceForPayPalAccount([
256
- 'paypal_account' => [
257
- 'access_token' => 'PAYPAL_ACCESS_TOKEN',
258
- 'token' => $paymentMethodToken
259
- ]
260
- ]);
261
-
262
- $result = Braintree\PaymentMethod::create([
263
- 'customerId' => $customer->id,
264
- 'paymentMethodNonce' => $nonce
265
- ]);
266
-
267
- $this->assertFalse($result->success);
268
- $errors = $result->errors->forKey('paypalAccount')->errors;
269
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT, $errors[0]->code);
270
- }
271
-
272
- public function testCreate_handlesValidationErrorsForPayPalAccounts()
273
- {
274
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
275
- $customer = Braintree\Customer::createNoValidate();
276
- $http = new HttpClientApi(Braintree\Configuration::$global);
277
- $nonce = $http->nonceForPayPalAccount([
278
- 'paypal_account' => [
279
- 'token' => $paymentMethodToken
280
- ]
281
- ]);
282
-
283
- $result = Braintree\PaymentMethod::create([
284
- 'customerId' => $customer->id,
285
- 'paymentMethodNonce' => $nonce
286
- ]);
287
-
288
- $this->assertFalse($result->success);
289
- $errors = $result->errors->forKey('paypalAccount')->errors;
290
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT, $errors[0]->code);
291
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CONSENT_CODE_OR_ACCESS_TOKEN_IS_REQUIRED, $errors[1]->code);
292
- }
293
-
294
- public function testCreate_allowsPassingDefaultOptionWithNonce()
295
- {
296
- $customer = Braintree\Customer::createNoValidate();
297
- $card1 = Braintree\CreditCard::create([
298
- 'customerId' => $customer->id,
299
- 'cardholderName' => 'Cardholder',
300
- 'number' => '5105105105105100',
301
- 'expirationDate' => '05/12'
302
- ])->creditCard;
303
-
304
- $this->assertTrue($card1->isDefault());
305
-
306
- $http = new HttpClientApi(Braintree\Configuration::$global);
307
- $nonce = $http->nonce_for_new_card([
308
- 'credit_card' => [
309
- 'number' => '4111111111111111',
310
- 'expirationMonth' => '11',
311
- 'expirationYear' => '2099',
312
- 'options' => [
313
- 'validate' => false
314
- ]
315
- ]
316
- ]);
317
-
318
- $result = Braintree\PaymentMethod::create([
319
- 'customerId' => $customer->id,
320
- 'paymentMethodNonce' => $nonce,
321
- 'options' => [
322
- 'makeDefault' => true
323
- ]
324
- ]);
325
-
326
- $card2 = $result->paymentMethod;
327
- $card1 = Braintree\CreditCard::find($card1->token);
328
- $this->assertFalse($card1->isDefault());
329
- $this->assertTrue($card2->isDefault());
330
- }
331
-
332
- public function testCreate_overridesNonceToken()
333
- {
334
- $customer = Braintree\Customer::createNoValidate();
335
- $firstToken = 'FIRST_TOKEN-' . strval(rand());
336
- $secondToken = 'SECOND_TOKEN-' . strval(rand());
337
- $http = new HttpClientApi(Braintree\Configuration::$global);
338
- $nonce = $http->nonce_for_new_card([
339
- 'credit_card' => [
340
- 'token' => $firstToken,
341
- 'number' => '4111111111111111',
342
- 'expirationMonth' => '11',
343
- 'expirationYear' => '2099',
344
- 'options' => [
345
- 'validate' => false
346
- ]
347
- ]
348
- ]);
349
-
350
- $result = Braintree\PaymentMethod::create([
351
- 'customerId' => $customer->id,
352
- 'paymentMethodNonce' => $nonce,
353
- 'token' => $secondToken
354
- ]);
355
-
356
- $card = $result->paymentMethod;
357
- $this->assertEquals($secondToken, $card->token);
358
- }
359
-
360
- public function testCreate_respectsVerifyCardAndVerificationMerchantAccountIdWhenIncludedOutsideOfTheNonce()
361
- {
362
- $http = new HttpClientApi(Braintree\Configuration::$global);
363
- $nonce = $http->nonce_for_new_card([
364
- 'credit_card' => [
365
- 'number' => '4000111111111115',
366
- 'expirationMonth' => '11',
367
- 'expirationYear' => '2099',
368
- ]
369
- ]);
370
- $customer = Braintree\Customer::createNoValidate();
371
- $result = Braintree\PaymentMethod::create([
372
- 'paymentMethodNonce' => $nonce,
373
- 'customerId' => $customer->id,
374
- 'options' => [
375
- 'verifyCard' => 'true',
376
- 'verificationMerchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
377
- ]
378
- ]);
379
-
380
- $this->assertFalse($result->success);
381
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $result->creditCardVerification->status);
382
- $this->assertEquals('2000', $result->creditCardVerification->processorResponseCode);
383
- $this->assertEquals('Do Not Honor', $result->creditCardVerification->processorResponseText);
384
- $this->assertEquals(Test\Helper::nonDefaultMerchantAccountId(), $result->creditCardVerification->merchantAccountId);
385
- }
386
-
387
- public function testCreate_respectsFailOnDuplicatePaymentMethodWhenIncludedOutsideTheNonce()
388
- {
389
- $customer = Braintree\Customer::createNoValidate();
390
- $result = Braintree\CreditCard::create([
391
- 'customerId' => $customer->id,
392
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
393
- 'expirationDate' => "05/2012"
394
- ]);
395
- $this->assertTrue($result->success);
396
-
397
- $http = new HttpClientApi(Braintree\Configuration::$global);
398
- $nonce = $http->nonce_for_new_card([
399
- 'credit_card' => [
400
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
401
- 'expirationDate' => "05/2012"
402
- ]
403
- ]);
404
- $updateResult = Braintree\PaymentMethod::create([
405
- 'paymentMethodNonce' => $nonce,
406
- 'customerId' => $customer->id,
407
- 'options' => [
408
- 'failOnDuplicatePaymentMethod' => 'true',
409
- ]
410
- ]);
411
-
412
- $this->assertFalse($updateResult->success);
413
- $resultErrors = $updateResult->errors->deepAll();
414
- $this->assertEquals("81724", $resultErrors[0]->code);
415
- }
416
-
417
- public function testCreate_allowsPassingABillingAddressOutsideOfTheNonce()
418
- {
419
- $customer = Braintree\Customer::createNoValidate();
420
- $http = new HttpClientApi(Braintree\Configuration::$global);
421
- $nonce = $http->nonce_for_new_card([
422
- 'credit_card' => [
423
- 'number' => '4111111111111111',
424
- 'expirationMonth' => '12',
425
- 'expirationYear' => '2020',
426
- 'options' => [
427
- 'validate' => false
428
- ]
429
- ]
430
- ]);
431
-
432
- $result = Braintree\PaymentMethod::create([
433
- 'paymentMethodNonce' => $nonce,
434
- 'customerId' => $customer->id,
435
- 'billingAddress' => [
436
- 'streetAddress' => '123 Abc Way'
437
- ]
438
- ]);
439
-
440
- $this->assertTrue($result->success);
441
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\CreditCard'));
442
- $token = $result->paymentMethod->token;
443
-
444
- $foundCreditCard = Braintree\CreditCard::find($token);
445
- $this->assertTrue(NULL != $foundCreditCard);
446
- $this->assertEquals('123 Abc Way', $foundCreditCard->billingAddress->streetAddress);
447
- }
448
-
449
- public function testCreate_overridesTheBillingAddressInTheNonce()
450
- {
451
- $customer = Braintree\Customer::createNoValidate();
452
- $http = new HttpClientApi(Braintree\Configuration::$global);
453
- $nonce = $http->nonce_for_new_card([
454
- 'credit_card' => [
455
- 'number' => '4111111111111111',
456
- 'expirationMonth' => '12',
457
- 'expirationYear' => '2020',
458
- 'options' => [
459
- 'validate' => false
460
- ],
461
- 'billingAddress' => [
462
- 'streetAddress' => '456 Xyz Way'
463
- ]
464
- ]
465
- ]);
466
-
467
- $result = Braintree\PaymentMethod::create([
468
- 'paymentMethodNonce' => $nonce,
469
- 'customerId' => $customer->id,
470
- 'billingAddress' => [
471
- 'streetAddress' => '123 Abc Way'
472
- ]
473
- ]);
474
-
475
- $this->assertTrue($result->success);
476
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\CreditCard'));
477
- $token = $result->paymentMethod->token;
478
-
479
- $foundCreditCard = Braintree\CreditCard::find($token);
480
- $this->assertTrue(NULL != $foundCreditCard);
481
- $this->assertEquals('123 Abc Way', $foundCreditCard->billingAddress->streetAddress);
482
- }
483
-
484
- public function testCreate_doesNotOverrideTheBillingAddressForAVaultedCreditCard()
485
- {
486
- $customer = Braintree\Customer::createNoValidate();
487
- $http = new HttpClientApi(Braintree\Configuration::$global);
488
- $nonce = $http->nonce_for_new_card([
489
- 'customerId' => $customer->id,
490
- 'credit_card' => [
491
- 'number' => '4111111111111111',
492
- 'expirationMonth' => '12',
493
- 'expirationYear' => '2020',
494
- 'billingAddress' => [
495
- 'streetAddress' => '456 Xyz Way'
496
- ]
497
- ]
498
- ]);
499
-
500
- $result = Braintree\PaymentMethod::create([
501
- 'paymentMethodNonce' => $nonce,
502
- 'customerId' => $customer->id,
503
- 'billingAddress' => [
504
- 'streetAddress' => '123 Abc Way'
505
- ]
506
- ]);
507
-
508
- $this->assertTrue($result->success);
509
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\CreditCard'));
510
- $token = $result->paymentMethod->token;
511
-
512
- $foundCreditCard = Braintree\CreditCard::find($token);
513
- $this->assertTrue(NULL != $foundCreditCard);
514
- $this->assertEquals('456 Xyz Way', $foundCreditCard->billingAddress->streetAddress);
515
- }
516
-
517
- public function testCreate_allowsPassingABillingAddressIdOutsideOfTheNonce()
518
- {
519
- $customer = Braintree\Customer::createNoValidate();
520
- $http = new HttpClientApi(Braintree\Configuration::$global);
521
- $nonce = $http->nonce_for_new_card([
522
- 'credit_card' => [
523
- 'number' => '4111111111111111',
524
- 'expirationMonth' => '12',
525
- 'expirationYear' => '2020',
526
- 'options' => [
527
- 'validate' => false
528
- ]
529
- ]
530
- ]);
531
-
532
- $address = Braintree\Address::create([
533
- 'customerId' => $customer->id,
534
- 'firstName' => 'Bobby',
535
- 'lastName' => 'Tables'
536
- ])->address;
537
- $result = Braintree\PaymentMethod::create([
538
- 'paymentMethodNonce' => $nonce,
539
- 'customerId' => $customer->id,
540
- 'billingAddressId' => $address->id
541
- ]);
542
-
543
- $this->assertTrue($result->success);
544
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\CreditCard'));
545
- $token = $result->paymentMethod->token;
546
-
547
- $foundCreditCard = Braintree\CreditCard::find($token);
548
- $this->assertTrue(NULL != $foundCreditCard);
549
- $this->assertEquals('Bobby', $foundCreditCard->billingAddress->firstName);
550
- $this->assertEquals('Tables', $foundCreditCard->billingAddress->lastName);
551
- }
552
-
553
- public function testCreate_doesNotReturnAnErrorIfCreditCardOptionsArePresentForAPaypalNonce()
554
- {
555
- $customer = Braintree\Customer::createNoValidate();
556
- $originalToken = 'paypal-account-' . strval(rand());
557
- $http = new HttpClientApi(Braintree\Configuration::$global);
558
- $nonce = $http->nonceForPaypalAccount([
559
- 'paypalAccount' => [
560
- 'consentCode' => 'consent-code',
561
- 'token' => $originalToken
562
- ]
563
- ]);
564
-
565
- $result = Braintree\PaymentMethod::create([
566
- 'paymentMethodNonce' => $nonce,
567
- 'customerId' => $customer->id,
568
- 'options' => [
569
- 'verifyCard' => 'true',
570
- 'failOnDuplicatePaymentMethod' => 'true',
571
- 'verificationMerchantAccountId' => 'Not a Real Merchant Account Id'
572
- ]
573
- ]);
574
-
575
- $this->assertTrue($result->success);
576
- }
577
-
578
- public function testCreate_ignoresPassedBillingAddressParamsForPaypalAccount()
579
- {
580
- $http = new HttpClientApi(Braintree\Configuration::$global);
581
- $nonce = $http->nonceForPaypalAccount([
582
- 'paypalAccount' => [
583
- 'consentCode' => 'PAYPAL_CONSENT_CODE',
584
- ]
585
- ]);
586
- $customer = Braintree\Customer::createNoValidate();
587
- $result = Braintree\PaymentMethod::create([
588
- 'paymentMethodNonce' => $nonce,
589
- 'customerId' => $customer->id,
590
- 'billingAddress' => [
591
- 'streetAddress' => '123 Abc Way'
592
- ]
593
- ]);
594
-
595
- $this->assertTrue($result->success);
596
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\PaypalAccount'));
597
- $token = $result->paymentMethod->token;
598
-
599
- $foundPaypalAccount = Braintree\PaypalAccount::find($token);
600
- $this->assertTrue(NULL != $foundPaypalAccount);
601
- }
602
-
603
- public function testCreate_ignoresPassedBillingAddressIdForPaypalAccount()
604
- {
605
- $http = new HttpClientApi(Braintree\Configuration::$global);
606
- $nonce = $http->nonceForPaypalAccount([
607
- 'paypalAccount' => [
608
- 'consentCode' => 'PAYPAL_CONSENT_CODE',
609
- ]
610
- ]);
611
- $customer = Braintree\Customer::createNoValidate();
612
- $result = Braintree\PaymentMethod::create([
613
- 'paymentMethodNonce' => $nonce,
614
- 'customerId' => $customer->id,
615
- 'billingAddressId' => 'address_id'
616
- ]);
617
-
618
- $this->assertTrue($result->success);
619
- $this->assertTrue(is_a($result->paymentMethod, 'Braintree\PaypalAccount'));
620
- $token = $result->paymentMethod->token;
621
-
622
- $foundPaypalAccount = Braintree\PaypalAccount::find($token);
623
- $this->assertTrue(NULL != $foundPaypalAccount);
624
- }
625
-
626
- public function testCreate_acceptsNumberAndOtherCreditCardParameters()
627
- {
628
- $customer = Braintree\Customer::createNoValidate();
629
- $result = Braintree\PaymentMethod::create([
630
- 'customerId' => $customer->id,
631
- 'paymentMethodNonce' => Braintree\Test\Nonces::$transactable,
632
- 'cardholderName' => 'Jane Doe',
633
- 'cvv' => '123',
634
- 'expirationMonth' => '10',
635
- 'expirationYear' => '24',
636
- 'number' => '4242424242424242'
637
- ]);
638
-
639
- $this->assertTrue($result->success);
640
- $this->assertTrue('Jane Doe' == $result->paymentMethod->cardholderName);
641
- $this->assertTrue('10' == $result->paymentMethod->expirationMonth);
642
- $this->assertTrue('2024' == $result->paymentMethod->expirationYear);
643
- $this->assertTrue('424242' == $result->paymentMethod->bin);
644
- $this->assertTrue('4242' == $result->paymentMethod->last4);
645
- }
646
-
647
- public function testFind_returnsCreditCards()
648
- {
649
- $paymentMethodToken = 'CREDIT_CARD_TOKEN-' . strval(rand());
650
- $customer = Braintree\Customer::createNoValidate();
651
- $creditCardResult = Braintree\CreditCard::create([
652
- 'customerId' => $customer->id,
653
- 'number' => '5105105105105100',
654
- 'expirationDate' => '05/2011',
655
- 'token' => $paymentMethodToken
656
- ]);
657
- $this->assertTrue($creditCardResult->success);
658
-
659
- $foundCreditCard = Braintree\PaymentMethod::find($creditCardResult->creditCard->token);
660
-
661
- $this->assertEquals($paymentMethodToken, $foundCreditCard->token);
662
- $this->assertEquals('510510', $foundCreditCard->bin);
663
- $this->assertEquals('5100', $foundCreditCard->last4);
664
- $this->assertEquals('05/2011', $foundCreditCard->expirationDate);
665
- }
666
-
667
- public function testFind_returnsCreditCardsWithSubscriptions()
668
- {
669
- $customer = Braintree\Customer::createNoValidate();
670
- $creditCardResult = Braintree\CreditCard::create([
671
- 'customerId' => $customer->id,
672
- 'number' => '5105105105105100',
673
- 'expirationDate' => '05/2011',
674
- ]);
675
- $this->assertTrue($creditCardResult->success);
676
-
677
- $subscriptionId = strval(rand());
678
- Braintree\Subscription::create([
679
- 'id' => $subscriptionId,
680
- 'paymentMethodToken' => $creditCardResult->creditCard->token,
681
- 'planId' => 'integration_trialless_plan',
682
- 'price' => '1.00'
683
- ]);
684
-
685
- $foundCreditCard = Braintree\PaymentMethod::find($creditCardResult->creditCard->token);
686
- $this->assertEquals($subscriptionId, $foundCreditCard->subscriptions[0]->id);
687
- $this->assertEquals('integration_trialless_plan', $foundCreditCard->subscriptions[0]->planId);
688
- $this->assertEquals('1.00', $foundCreditCard->subscriptions[0]->price);
689
- }
690
-
691
- public function testFind_returnsPayPalAccounts()
692
- {
693
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
694
- $customer = Braintree\Customer::createNoValidate();
695
- $http = new HttpClientApi(Braintree\Configuration::$global);
696
- $nonce = $http->nonceForPayPalAccount([
697
- 'paypal_account' => [
698
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
699
- 'token' => $paymentMethodToken
700
- ]
701
- ]);
702
-
703
- Braintree\PaymentMethod::create([
704
- 'customerId' => $customer->id,
705
- 'paymentMethodNonce' => $nonce
706
- ]);
707
-
708
- $foundPayPalAccount = Braintree\PaymentMethod::find($paymentMethodToken);
709
-
710
- $this->assertSame('jane.doe@example.com', $foundPayPalAccount->email);
711
- $this->assertSame($paymentMethodToken, $foundPayPalAccount->token);
712
- }
713
-
714
- public function testFind_returnsApplePayCards()
715
- {
716
- $paymentMethodToken = 'APPLE_PAY-' . strval(rand());
717
- $customer = Braintree\Customer::createNoValidate();
718
- $nonce = Braintree\Test\Nonces::$applePayVisa;
719
- Braintree\PaymentMethod::create([
720
- 'customerId' => $customer->id,
721
- 'paymentMethodNonce' => $nonce,
722
- 'token' => $paymentMethodToken
723
- ]);
724
-
725
- $foundApplePayCard = Braintree\PaymentMethod::find($paymentMethodToken);
726
-
727
- $this->assertSame($paymentMethodToken, $foundApplePayCard->token);
728
- $this->assertInstanceOf('Braintree\ApplePayCard', $foundApplePayCard);
729
- $this->assertTrue(intval($foundApplePayCard->expirationMonth) > 0);
730
- $this->assertTrue(intval($foundApplePayCard->expirationYear) > 0);
731
- }
732
-
733
- public function testFind_returnsAndroidPayCards()
734
- {
735
- $paymentMethodToken = 'ANDROID-PAY-' . strval(rand());
736
- $customer = Braintree\Customer::createNoValidate();
737
- $nonce = Braintree\Test\Nonces::$androidPay;
738
- Braintree\PaymentMethod::create([
739
- 'customerId' => $customer->id,
740
- 'paymentMethodNonce' => $nonce,
741
- 'token' => $paymentMethodToken
742
- ]);
743
-
744
- $foundAndroidPayCard = Braintree\PaymentMethod::find($paymentMethodToken);
745
-
746
- $this->assertSame($paymentMethodToken, $foundAndroidPayCard->token);
747
- $this->assertInstanceOf('Braintree\AndroidPayCard', $foundAndroidPayCard);
748
- $this->assertSame(Braintree\CreditCard::DISCOVER, $foundAndroidPayCard->virtualCardType);
749
- $this->assertSame("1117", $foundAndroidPayCard->virtualCardLast4);
750
- $this->assertSame(Braintree\CreditCard::VISA, $foundAndroidPayCard->sourceCardType);
751
- $this->assertSame("1111", $foundAndroidPayCard->sourceCardLast4);
752
- $this->assertSame($customer->id, $foundAndroidPayCard->customerId);
753
- $this->assertTrue($foundAndroidPayCard->default);
754
- $this->assertContains('android_pay', $foundAndroidPayCard->imageUrl);
755
- $this->assertTrue(intval($foundAndroidPayCard->expirationMonth) > 0);
756
- $this->assertTrue(intval($foundAndroidPayCard->expirationYear) > 0);
757
- }
758
-
759
- public function testFind_returnsCoinbaseAccounts()
760
- {
761
- $customer = Braintree\Customer::createNoValidate();
762
- $result = Braintree\PaymentMethod::create([
763
- 'customerId' => $customer->id,
764
- 'paymentMethodNonce' => Braintree\Test\Nonces::$coinbase
765
- ]);
766
-
767
- $this->assertTrue($result->success);
768
- $coinbaseAccount = $result->paymentMethod;
769
- $this->assertNotNull($coinbaseAccount->token);
770
- $foundCoinbaseAccount = Braintree\PaymentMethod::find($coinbaseAccount->token);
771
- $this->assertInstanceOf('Braintree\CoinbaseAccount', $foundCoinbaseAccount);
772
- $this->assertNotNull($foundCoinbaseAccount->userId);
773
- $this->assertNotNull($foundCoinbaseAccount->userName);
774
- $this->assertNotNull($foundCoinbaseAccount->userEmail);
775
- $this->assertNotNull($foundCoinbaseAccount->customerId);
776
- }
777
-
778
-
779
- public function testFind_returnsAbstractPaymentMethods()
780
- {
781
- $paymentMethodToken = 'ABSTRACT-' . strval(rand());
782
- $customer = Braintree\Customer::createNoValidate();
783
- $nonce = Braintree\Test\Nonces::$abstractTransactable;
784
- Braintree\PaymentMethod::create([
785
- 'customerId' => $customer->id,
786
- 'paymentMethodNonce' => $nonce,
787
- 'token' => $paymentMethodToken
788
- ]);
789
-
790
- $foundPaymentMethod = Braintree\PaymentMethod::find($paymentMethodToken);
791
-
792
- $this->assertSame($paymentMethodToken, $foundPaymentMethod-> token);
793
- }
794
-
795
- public function testFind_throwsIfCannotBeFound()
796
- {
797
- $this->setExpectedException('Braintree\Exception\NotFound');
798
- Braintree\PaymentMethod::find('NON_EXISTENT_TOKEN');
799
- }
800
-
801
- public function testUpdate_updatesTheCreditCard()
802
- {
803
- $customer = Braintree\Customer::createNoValidate();
804
- $creditCardResult = Braintree\CreditCard::create([
805
- 'cardholderName' => 'Original Holder',
806
- 'customerId' => $customer->id,
807
- 'cvv' => '123',
808
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
809
- 'expirationDate' => "05/2012"
810
- ]);
811
- $this->assertTrue($creditCardResult->success);
812
- $creditCard = $creditCardResult->creditCard;
813
-
814
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
815
- 'cardholderName' => 'New Holder',
816
- 'cvv' => '456',
817
- 'number' => Braintree\Test\CreditCardNumbers::$masterCard,
818
- 'expirationDate' => "06/2013"
819
- ]);
820
-
821
- $this->assertTrue($updateResult->success);
822
- $this->assertSame($updateResult->paymentMethod->token, $creditCard->token);
823
- $updatedCreditCard = $updateResult->paymentMethod;
824
- $this->assertSame("New Holder", $updatedCreditCard->cardholderName);
825
- $this->assertSame(substr(Braintree\Test\CreditCardNumbers::$masterCard, 0, 6), $updatedCreditCard->bin);
826
- $this->assertSame(substr(Braintree\Test\CreditCardNumbers::$masterCard, -4), $updatedCreditCard->last4);
827
- $this->assertSame("06/2013", $updatedCreditCard->expirationDate);
828
- }
829
-
830
- public function testUpdate_createsANewBillingAddressByDefault()
831
- {
832
- $customer = Braintree\Customer::createNoValidate();
833
- $creditCardResult = Braintree\CreditCard::create([
834
- 'customerId' => $customer->id,
835
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
836
- 'expirationDate' => "05/2012",
837
- 'billingAddress' => [
838
- 'streetAddress' => '123 Nigeria Ave'
839
- ]
840
- ]);
841
- $this->assertTrue($creditCardResult->success);
842
- $creditCard = $creditCardResult->creditCard;
843
-
844
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
845
- 'billingAddress' => [
846
- 'region' => 'IL'
847
- ]
848
- ]);
849
-
850
- $this->assertTrue($updateResult->success);
851
- $updatedCreditCard = $updateResult->paymentMethod;
852
- $this->assertSame("IL", $updatedCreditCard->billingAddress->region);
853
- $this->assertSame(NULL, $updatedCreditCard->billingAddress->streetAddress);
854
- $this->assertFalse($creditCard->billingAddress->id == $updatedCreditCard->billingAddress->id);
855
- }
856
-
857
- public function testUpdate_updatesTheBillingAddressIfOptionIsSpecified()
858
- {
859
- $customer = Braintree\Customer::createNoValidate();
860
- $creditCardResult = Braintree\CreditCard::create([
861
- 'customerId' => $customer->id,
862
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
863
- 'expirationDate' => "05/2012",
864
- 'billingAddress' => [
865
- 'streetAddress' => '123 Nigeria Ave'
866
- ]
867
- ]);
868
- $this->assertTrue($creditCardResult->success);
869
- $creditCard = $creditCardResult->creditCard;
870
-
871
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
872
- 'billingAddress' => [
873
- 'region' => 'IL',
874
- 'options' => [
875
- 'updateExisting' => 'true'
876
- ]
877
- ],
878
- ]);
879
-
880
- $this->assertTrue($updateResult->success);
881
- $updatedCreditCard = $updateResult->paymentMethod;
882
- $this->assertSame("IL", $updatedCreditCard->billingAddress->region);
883
- $this->assertSame("123 Nigeria Ave", $updatedCreditCard->billingAddress->streetAddress);
884
- $this->assertTrue($creditCard->billingAddress->id == $updatedCreditCard->billingAddress->id);
885
- }
886
-
887
- public function testUpdate_updatesTheCountryViaCodes()
888
- {
889
- $customer = Braintree\Customer::createNoValidate();
890
- $creditCardResult = Braintree\CreditCard::create([
891
- 'customerId' => $customer->id,
892
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
893
- 'expirationDate' => "05/2012",
894
- 'billingAddress' => [
895
- 'streetAddress' => '123 Nigeria Ave'
896
- ]
897
- ]);
898
- $this->assertTrue($creditCardResult->success);
899
- $creditCard = $creditCardResult->creditCard;
900
-
901
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
902
- 'billingAddress' => [
903
- 'countryName' => 'American Samoa',
904
- 'countryCodeAlpha2' => 'AS',
905
- 'countryCodeAlpha3' => 'ASM',
906
- 'countryCodeNumeric' => '016',
907
- 'options' => [
908
- 'updateExisting' => 'true'
909
- ]
910
- ],
911
- ]);
912
-
913
- $this->assertTrue($updateResult->success);
914
- $updatedCreditCard = $updateResult->paymentMethod;
915
- $this->assertSame("American Samoa", $updatedCreditCard->billingAddress->countryName);
916
- $this->assertSame("AS", $updatedCreditCard->billingAddress->countryCodeAlpha2);
917
- $this->assertSame("ASM", $updatedCreditCard->billingAddress->countryCodeAlpha3);
918
- $this->assertSame("016", $updatedCreditCard->billingAddress->countryCodeNumeric);
919
- }
920
-
921
- public function testUpdate_canPassExpirationMonthAndExpirationYear()
922
- {
923
- $customer = Braintree\Customer::createNoValidate();
924
- $creditCardResult = Braintree\CreditCard::create([
925
- 'customerId' => $customer->id,
926
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
927
- 'expirationDate' => "05/2012"
928
- ]);
929
- $this->assertTrue($creditCardResult->success);
930
- $creditCard = $creditCardResult->creditCard;
931
-
932
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
933
- 'number' => Braintree\Test\CreditCardNumbers::$masterCard,
934
- 'expirationMonth' => "07",
935
- 'expirationYear' => "2011"
936
- ]);
937
-
938
- $this->assertTrue($updateResult->success);
939
- $this->assertSame($updateResult->paymentMethod->token, $creditCard->token);
940
- $updatedCreditCard = $updateResult->paymentMethod;
941
- $this->assertSame("07", $updatedCreditCard->expirationMonth);
942
- $this->assertSame("07", $updatedCreditCard->expirationMonth);
943
- $this->assertSame("07/2011", $updatedCreditCard->expirationDate);
944
- }
945
-
946
- public function testUpdate_verifiesTheUpdateIfOptionsVerifyCardIsTrue()
947
- {
948
- $customer = Braintree\Customer::createNoValidate();
949
- $creditCardResult = Braintree\CreditCard::create([
950
- 'cardholderName' => 'Original Holder',
951
- 'customerId' => $customer->id,
952
- 'cvv' => '123',
953
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
954
- 'expirationDate' => "05/2012"
955
- ]);
956
- $this->assertTrue($creditCardResult->success);
957
- $creditCard = $creditCardResult->creditCard;
958
-
959
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
960
- 'cardholderName' => 'New Holder',
961
- 'cvv' => '456',
962
- 'number' => Braintree\Test\CreditCardNumbers::$failsSandboxVerification['MasterCard'],
963
- 'expirationDate' => "06/2013",
964
- 'options' => [
965
- 'verifyCard' => 'true'
966
- ]
967
- ]);
968
-
969
- $this->assertFalse($updateResult->success);
970
- $this->assertEquals(Braintree\Result\CreditCardVerification::PROCESSOR_DECLINED, $updateResult->creditCardVerification->status);
971
- $this->assertEquals(NULL, $updateResult->creditCardVerification->gatewayRejectionReason);
972
- }
973
-
974
- public function testUpdate_canUpdateTheBillingAddress()
975
- {
976
- $customer = Braintree\Customer::createNoValidate();
977
- $creditCardResult = Braintree\CreditCard::create([
978
- 'cardholderName' => 'Original Holder',
979
- 'customerId' => $customer->id,
980
- 'cvv' => '123',
981
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
982
- 'expirationDate' => '05/2012',
983
- 'billingAddress' => [
984
- 'firstName' => 'Old First Name',
985
- 'lastName' => 'Old Last Name',
986
- 'company' => 'Old Company',
987
- 'streetAddress' => '123 Old St',
988
- 'extendedAddress' => 'Apt Old',
989
- 'locality' => 'Old City',
990
- 'region' => 'Old State',
991
- 'postalCode' => '12345',
992
- 'countryName' => 'Canada'
993
- ]
994
- ]);
995
- $this->assertTrue($creditCardResult->success);
996
- $creditCard = $creditCardResult->creditCard;
997
-
998
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
999
- 'billingAddress' => [
1000
- 'firstName' => 'New First Name',
1001
- 'lastName' => 'New Last Name',
1002
- 'company' => 'New Company',
1003
- 'streetAddress' => '123 New St',
1004
- 'extendedAddress' => 'Apt New',
1005
- 'locality' => 'New City',
1006
- 'region' => 'New State',
1007
- 'postalCode' => '56789',
1008
- 'countryName' => 'United States of America'
1009
- ]
1010
- ]);
1011
-
1012
- $this->assertTrue($updateResult->success);
1013
- $address = $updateResult->paymentMethod->billingAddress;
1014
- $this->assertSame('New First Name', $address->firstName);
1015
- $this->assertSame('New Last Name', $address->lastName);
1016
- $this->assertSame('New Company', $address->company);
1017
- $this->assertSame('123 New St', $address->streetAddress);
1018
- $this->assertSame('Apt New', $address->extendedAddress);
1019
- $this->assertSame('New City', $address->locality);
1020
- $this->assertSame('New State', $address->region);
1021
- $this->assertSame('56789', $address->postalCode);
1022
- $this->assertSame('United States of America', $address->countryName);
1023
- }
1024
-
1025
- public function testUpdate_returnsAnErrorIfInvalid()
1026
- {
1027
- $customer = Braintree\Customer::createNoValidate();
1028
- $creditCardResult = Braintree\CreditCard::create([
1029
- 'cardholderName' => 'Original Holder',
1030
- 'customerId' => $customer->id,
1031
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1032
- 'expirationDate' => "05/2012"
1033
- ]);
1034
- $this->assertTrue($creditCardResult->success);
1035
- $creditCard = $creditCardResult->creditCard;
1036
-
1037
- $updateResult = Braintree\PaymentMethod::update($creditCard->token, [
1038
- 'cardholderName' => 'New Holder',
1039
- 'number' => 'invalid',
1040
- 'expirationDate' => "05/2014",
1041
- ]);
1042
-
1043
- $this->assertFalse($updateResult->success);
1044
- $numberErrors = $updateResult->errors->forKey('creditCard')->onAttribute('number');
1045
- $this->assertEquals("Credit card number must be 12-19 digits.", $numberErrors[0]->message);
1046
- }
1047
-
1048
- public function testUpdate_canUpdateTheDefault()
1049
- {
1050
- $customer = Braintree\Customer::createNoValidate();
1051
-
1052
- $creditCardResult1 = Braintree\CreditCard::create([
1053
- 'customerId' => $customer->id,
1054
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1055
- 'expirationDate' => "05/2009"
1056
- ]);
1057
- $this->assertTrue($creditCardResult1->success);
1058
- $creditCard1 = $creditCardResult1->creditCard;
1059
-
1060
- $creditCardResult2 = Braintree\CreditCard::create([
1061
- 'customerId' => $customer->id,
1062
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1063
- 'expirationDate' => "05/2009"
1064
- ]);
1065
- $this->assertTrue($creditCardResult2->success);
1066
- $creditCard2 = $creditCardResult2->creditCard;
1067
-
1068
- $this->assertTrue($creditCard1->default);
1069
- $this->assertFalse($creditCard2->default);
1070
-
1071
-
1072
- $updateResult = Braintree\PaymentMethod::update($creditCard2->token, [
1073
- 'options' => [
1074
- 'makeDefault' => 'true'
1075
- ]
1076
- ]);
1077
- $this->assertTrue($updateResult->success);
1078
-
1079
- $this->assertFalse(Braintree\PaymentMethod::find($creditCard1->token)->default);
1080
- $this->assertTrue(Braintree\PaymentMethod::find($creditCard2->token)->default);
1081
- }
1082
-
1083
- public function testUpdate_updatesAPaypalAccountsToken()
1084
- {
1085
- $customer = Braintree\Customer::createNoValidate();
1086
- $originalToken = 'paypal-account-' . strval(rand());
1087
- $customer = Braintree\Customer::createNoValidate();
1088
- $http = new HttpClientApi(Braintree\Configuration::$global);
1089
- $nonce = $http->nonceForPayPalAccount([
1090
- 'paypal_account' => [
1091
- 'consent_code' => 'consent-code',
1092
- 'token' => $originalToken
1093
- ]
1094
- ]);
1095
-
1096
- $originalResult = Braintree\PaymentMethod::create([
1097
- 'paymentMethodNonce' => $nonce,
1098
- 'customerId' => $customer->id
1099
- ]);
1100
- $this->assertTrue($originalResult->success);
1101
-
1102
- $originalPaypalAccount = $originalResult->paymentMethod;
1103
-
1104
- $updatedToken = 'UPDATED_TOKEN-' . strval(rand());
1105
- $updateResult = Braintree\PaymentMethod::update($originalPaypalAccount->token, [
1106
- 'token' => $updatedToken
1107
- ]);
1108
- $this->assertTrue($updateResult->success);
1109
-
1110
- $updatedPaypalAccount = Braintree\PaymentMethod::find($updatedToken);
1111
- $this->assertEquals($originalPaypalAccount->email, $updatedPaypalAccount->email);
1112
-
1113
- $this->setExpectedException('Braintree\Exception\NotFound', 'payment method with token ' . $originalToken . ' not found');
1114
- Braintree\PaymentMethod::find($originalToken);
1115
-
1116
- }
1117
-
1118
- public function testUpdate_canMakeAPaypalAccountTheDefaultPaymentMethod()
1119
- {
1120
- $customer = Braintree\Customer::createNoValidate();
1121
- $creditCardResult = Braintree\CreditCard::create([
1122
- 'customerId' => $customer->id,
1123
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1124
- 'expirationDate' => '05/2009',
1125
- 'options' => [
1126
- 'makeDefault' => 'true'
1127
- ]
1128
- ]);
1129
- $this->assertTrue($creditCardResult->success);
1130
- $creditCard = $creditCardResult->creditCard;
1131
-
1132
- $http = new HttpClientApi(Braintree\Configuration::$global);
1133
- $nonce = $http->nonceForPayPalAccount([
1134
- 'paypal_account' => [
1135
- 'consent_code' => 'consent-code',
1136
- ]
1137
- ]);
1138
-
1139
- $originalToken = Braintree\PaymentMethod::create([
1140
- 'paymentMethodNonce' => $nonce,
1141
- 'customerId' => $customer->id
1142
- ])->paymentMethod->token;
1143
-
1144
- $updateResult = Braintree\PaymentMethod::update($originalToken, [
1145
- 'options' => [
1146
- 'makeDefault' => 'true'
1147
- ]
1148
- ]);
1149
- $this->assertTrue($updateResult->success);
1150
-
1151
- $updatedPaypalAccount = Braintree\PaymentMethod::find($originalToken);
1152
- $this->assertTrue($updatedPaypalAccount->default);
1153
-
1154
- }
1155
-
1156
- public function testUpdate_returnsAnErrorIfATokenForAccountIsUsedToAttemptAnUpdate()
1157
- {
1158
- $customer = Braintree\Customer::createNoValidate();
1159
- $firstToken = 'paypal-account-' . strval(rand());
1160
- $secondToken = 'paypal-account-' . strval(rand());
1161
-
1162
- $http = new HttpClientApi(Braintree\Configuration::$global);
1163
- $firstNonce = $http->nonceForPayPalAccount([
1164
- 'paypal_account' => [
1165
- 'consent_code' => 'consent-code',
1166
- 'token' => $firstToken
1167
- ]
1168
- ]);
1169
- $firstResult = Braintree\PaymentMethod::create([
1170
- 'paymentMethodNonce' => $firstNonce,
1171
- 'customerId' => $customer->id
1172
- ]);
1173
- $this->assertTrue($firstResult->success);
1174
- $firstPaypalAccount = $firstResult->paymentMethod;
1175
-
1176
- $http = new HttpClientApi(Braintree\Configuration::$global);
1177
- $secondNonce = $http->nonceForPayPalAccount([
1178
- 'paypal_account' => [
1179
- 'consent_code' => 'consent-code',
1180
- 'token' => $secondToken
1181
- ]
1182
- ]);
1183
- $secondResult = Braintree\PaymentMethod::create([
1184
- 'paymentMethodNonce' => $secondNonce,
1185
- 'customerId' => $customer->id
1186
- ]);
1187
- $this->assertTrue($secondResult->success);
1188
- $secondPaypalAccount = $firstResult->paymentMethod;
1189
-
1190
-
1191
- $updateResult = Braintree\PaymentMethod::update($firstToken, [
1192
- 'token' => $secondToken
1193
- ]);
1194
-
1195
- $this->assertFalse($updateResult->success);
1196
- $resultErrors = $updateResult->errors->deepAll();
1197
- $this->assertEquals("92906", $resultErrors[0]->code);
1198
-
1199
- }
1200
-
1201
- public function testDelete_worksWithCreditCards()
1202
- {
1203
- $paymentMethodToken = 'CREDIT_CARD_TOKEN-' . strval(rand());
1204
- $customer = Braintree\Customer::createNoValidate();
1205
- $creditCardResult = Braintree\CreditCard::create([
1206
- 'customerId' => $customer->id,
1207
- 'number' => '5105105105105100',
1208
- 'expirationDate' => '05/2011',
1209
- 'token' => $paymentMethodToken
1210
- ]);
1211
- $this->assertTrue($creditCardResult->success);
1212
-
1213
- Braintree\PaymentMethod::delete($paymentMethodToken);
1214
-
1215
- $this->setExpectedException('Braintree\Exception\NotFound');
1216
- Braintree\PaymentMethod::find($paymentMethodToken);
1217
- self::integrationMerchantConfig();
1218
- }
1219
-
1220
- public function testDelete_worksWithPayPalAccounts()
1221
- {
1222
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
1223
- $customer = Braintree\Customer::createNoValidate();
1224
- $http = new HttpClientApi(Braintree\Configuration::$global);
1225
- $nonce = $http->nonceForPayPalAccount([
1226
- 'paypal_account' => [
1227
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
1228
- 'token' => $paymentMethodToken
1229
- ]
1230
- ]);
1231
-
1232
- $paypalAccountResult = Braintree\PaymentMethod::create([
1233
- 'customerId' => $customer->id,
1234
- 'paymentMethodNonce' => $nonce
1235
- ]);
1236
- $this->assertTrue($paypalAccountResult->success);
1237
-
1238
- Braintree\PaymentMethod::delete($paymentMethodToken);
1239
-
1240
- $this->setExpectedException('Braintree\Exception\NotFound');
1241
- Braintree\PaymentMethod::find($paymentMethodToken);
1242
- }
1243
-
1244
- public function testGrant_returnsASingleUseNonce()
1245
- {
1246
- $partnerMerchantGateway = new Braintree\Gateway([
1247
- 'environment' => 'development',
1248
- 'merchantId' => 'integration_merchant_public_id',
1249
- 'publicKey' => 'oauth_app_partner_user_public_key',
1250
- 'privateKey' => 'oauth_app_partner_user_private_key'
1251
- ]);
1252
-
1253
- $customer = $partnerMerchantGateway->customer()->create([
1254
- 'firstName' => 'Joe',
1255
- 'lastName' => 'Brown'
1256
- ])->customer;
1257
- $creditCard = $partnerMerchantGateway->creditCard()->create([
1258
- 'customerId' => $customer->id,
1259
- 'cardholderName' => 'Adam Davis',
1260
- 'number' => '4111111111111111',
1261
- 'expirationDate' => '05/2009'
1262
- ])->creditCard;
1263
-
1264
- $oauthAppGateway = new Braintree\Gateway([
1265
- 'clientId' => 'client_id$development$integration_client_id',
1266
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1267
- ]);
1268
-
1269
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1270
- 'merchant_public_id' => 'integration_merchant_id',
1271
- 'scope' => 'grant_payment_method'
1272
- ]);
1273
-
1274
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1275
- 'code' => $code,
1276
- ]);
1277
-
1278
- $grantingGateway = new Braintree\Gateway([
1279
- 'accessToken' => $credentials->accessToken
1280
- ]);
1281
-
1282
- $grantResult = $grantingGateway->paymentMethod()->grant($creditCard->token, false);
1283
- $this->assertTrue($grantResult->success);
1284
-
1285
- $result = Braintree\Transaction::sale([
1286
- 'amount' => '100.00',
1287
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
1288
- ]);
1289
- $this->assertTrue($result->success);
1290
-
1291
- $secondResult = Braintree\Transaction::sale([
1292
- 'amount' => '100.00',
1293
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
1294
- ]);
1295
- $this->assertFalse($secondResult->success);
1296
- }
1297
-
1298
- public function testGrant_returnsANonceThatIsNotVaultable()
1299
- {
1300
- $partnerMerchantGateway = new Braintree\Gateway([
1301
- 'environment' => 'development',
1302
- 'merchantId' => 'integration_merchant_public_id',
1303
- 'publicKey' => 'oauth_app_partner_user_public_key',
1304
- 'privateKey' => 'oauth_app_partner_user_private_key'
1305
- ]);
1306
-
1307
- $customer = $partnerMerchantGateway->customer()->create([
1308
- 'firstName' => 'Joe',
1309
- 'lastName' => 'Brown'
1310
- ])->customer;
1311
- $creditCard = $partnerMerchantGateway->creditCard()->create([
1312
- 'customerId' => $customer->id,
1313
- 'cardholderName' => 'Adam Davis',
1314
- 'number' => '4111111111111111',
1315
- 'expirationDate' => '05/2009'
1316
- ])->creditCard;
1317
-
1318
- $oauthAppGateway = new Braintree\Gateway([
1319
- 'clientId' => 'client_id$development$integration_client_id',
1320
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1321
- ]);
1322
-
1323
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1324
- 'merchant_public_id' => 'integration_merchant_id',
1325
- 'scope' => 'grant_payment_method'
1326
- ]);
1327
-
1328
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1329
- 'code' => $code,
1330
- ]);
1331
-
1332
- $grantingGateway = new Braintree\Gateway([
1333
- 'accessToken' => $credentials->accessToken
1334
- ]);
1335
-
1336
- $grantResult = $grantingGateway->paymentMethod()->grant($creditCard->token, false);
1337
-
1338
- $customer = $partnerMerchantGateway->customer()->create([
1339
- 'firstName' => 'Bob',
1340
- 'lastName' => 'Rob'
1341
- ])->customer;
1342
- $result = Braintree\PaymentMethod::create([
1343
- 'customerId' => $customer->id,
1344
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
1345
- ]);
1346
- $this->assertFalse($result->success);
1347
- }
1348
-
1349
- public function testGrant_returnsANonceThatIsVaultable()
1350
- {
1351
- $partnerMerchantGateway = new Braintree\Gateway([
1352
- 'environment' => 'development',
1353
- 'merchantId' => 'integration_merchant_public_id',
1354
- 'publicKey' => 'oauth_app_partner_user_public_key',
1355
- 'privateKey' => 'oauth_app_partner_user_private_key'
1356
- ]);
1357
-
1358
- $customer = $partnerMerchantGateway->customer()->create([
1359
- 'firstName' => 'Joe',
1360
- 'lastName' => 'Brown'
1361
- ])->customer;
1362
- $creditCard = $partnerMerchantGateway->creditCard()->create([
1363
- 'customerId' => $customer->id,
1364
- 'cardholderName' => 'Adam Davis',
1365
- 'number' => '4111111111111111',
1366
- 'expirationDate' => '05/2009'
1367
- ])->creditCard;
1368
-
1369
- $oauthAppGateway = new Braintree\Gateway([
1370
- 'clientId' => 'client_id$development$integration_client_id',
1371
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1372
- ]);
1373
-
1374
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1375
- 'merchant_public_id' => 'integration_merchant_id',
1376
- 'scope' => 'grant_payment_method'
1377
- ]);
1378
-
1379
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1380
- 'code' => $code,
1381
- ]);
1382
-
1383
- $grantingGateway = new Braintree\Gateway([
1384
- 'accessToken' => $credentials->accessToken
1385
- ]);
1386
-
1387
- $grantResult = $grantingGateway->paymentMethod()->grant($creditCard->token, true);
1388
-
1389
- $customer = Braintree\Customer::create([
1390
- 'firstName' => 'Bob',
1391
- 'lastName' => 'Rob'
1392
- ])->customer;
1393
- $result = Braintree\PaymentMethod::create([
1394
- 'customerId' => $customer->id,
1395
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
1396
- ]);
1397
- $this->assertTrue($result->success);
1398
- }
1399
-
1400
- public function testGrant_raisesAnErrorIfTokenIsNotFound()
1401
- {
1402
- $oauthAppGateway = new Braintree\Gateway([
1403
- 'clientId' => 'client_id$development$integration_client_id',
1404
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1405
- ]);
1406
-
1407
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1408
- 'merchant_public_id' => 'integration_merchant_id',
1409
- 'scope' => 'grant_payment_method'
1410
- ]);
1411
-
1412
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1413
- 'code' => $code,
1414
- ]);
1415
-
1416
- $grantingGateway = new Braintree\Gateway([
1417
- 'accessToken' => $credentials->accessToken
1418
- ]);
1419
-
1420
- $this->setExpectedException('Braintree\Exception\NotFound');
1421
- $grantResult = $grantingGateway->paymentMethod()->grant("not_a_real_token", false);
1422
- }
1423
-
1424
- public function testRevoke_rendersANonceUnusable()
1425
- {
1426
- $partnerMerchantGateway = new Braintree\Gateway([
1427
- 'environment' => 'development',
1428
- 'merchantId' => 'integration_merchant_public_id',
1429
- 'publicKey' => 'oauth_app_partner_user_public_key',
1430
- 'privateKey' => 'oauth_app_partner_user_private_key'
1431
- ]);
1432
-
1433
- $customer = $partnerMerchantGateway->customer()->create([
1434
- 'firstName' => 'Joe',
1435
- 'lastName' => 'Brown'
1436
- ])->customer;
1437
- $creditCard = $partnerMerchantGateway->creditCard()->create([
1438
- 'customerId' => $customer->id,
1439
- 'cardholderName' => 'Adam Davis',
1440
- 'number' => '4111111111111111',
1441
- 'expirationDate' => '05/2009'
1442
- ])->creditCard;
1443
-
1444
- $oauthAppGateway = new Braintree\Gateway([
1445
- 'clientId' => 'client_id$development$integration_client_id',
1446
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1447
- ]);
1448
-
1449
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1450
- 'merchant_public_id' => 'integration_merchant_id',
1451
- 'scope' => 'grant_payment_method'
1452
- ]);
1453
-
1454
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1455
- 'code' => $code,
1456
- ]);
1457
-
1458
- $grantingGateway = new Braintree\Gateway([
1459
- 'accessToken' => $credentials->accessToken
1460
- ]);
1461
-
1462
- $grantResult = $grantingGateway->paymentMethod()->grant($creditCard->token, false);
1463
- $revokeResult = $grantingGateway->paymentMethod()->revoke($creditCard->token);
1464
- $this->assertTrue($revokeResult->success);
1465
-
1466
- $result = Braintree\Transaction::sale([
1467
- 'amount' => '100.00',
1468
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
1469
- ]);
1470
- $this->assertFalse($result->success);
1471
- }
1472
-
1473
- public function testRevoke_raisesAnErrorIfTokenIsNotFound()
1474
- {
1475
- $oauthAppGateway = new Braintree\Gateway([
1476
- 'clientId' => 'client_id$development$integration_client_id',
1477
- 'clientSecret' => 'client_secret$development$integration_client_secret'
1478
- ]);
1479
-
1480
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
1481
- 'merchant_public_id' => 'integration_merchant_id',
1482
- 'scope' => 'grant_payment_method'
1483
- ]);
1484
-
1485
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
1486
- 'code' => $code,
1487
- ]);
1488
-
1489
- $grantingGateway = new Braintree\Gateway([
1490
- 'accessToken' => $credentials->accessToken
1491
- ]);
1492
-
1493
- $this->setExpectedException('Braintree\Exception\NotFound');
1494
- $grantResult = $grantingGateway->paymentMethod()->revoke("not_a_real_token");
1495
- }
1496
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/PlanTest.php DELETED
@@ -1,132 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Test\Helper;
8
- use Braintree;
9
-
10
- class PlanTest extends Setup
11
- {
12
- public function testAll_withNoPlans_returnsEmptyArray()
13
- {
14
- Helper::testMerchantConfig();
15
- $plans = Braintree\Plan::all();
16
- $this->assertEquals($plans, []);
17
- self::integrationMerchantConfig();
18
-
19
- }
20
-
21
- public function testAll_returnsAllPlans()
22
- {
23
- $newId = strval(rand());
24
- $params = [
25
- "id" => $newId,
26
- "billingDayOfMonth" => "1",
27
- "billingFrequency" => "1",
28
- "currencyIsoCode" => "USD",
29
- "description" => "some description",
30
- "name" => "php test plan",
31
- "numberOfBillingCycles" => "1",
32
- "price" => "1.00",
33
- "trialPeriod" => "false"
34
- ];
35
-
36
- $http = new Braintree\Http(Braintree\Configuration::$global);
37
- $path = Braintree\Configuration::$global->merchantPath() . '/plans/create_plan_for_tests';
38
- $http->post($path, ["plan" => $params]);
39
-
40
- $addOnParams = [
41
- "kind" => "add_on",
42
- "plan_id" => $newId,
43
- "amount" => "1.00",
44
- "name" => "add_on_name"
45
- ];
46
-
47
- $http = new Braintree\Http(Braintree\Configuration::$global);
48
- $path = Braintree\Configuration::$global->merchantPath() . '/modifications/create_modification_for_tests';
49
- $http->post($path, ['modification' => $addOnParams]);
50
-
51
- $discountParams = [
52
- "kind" => "discount",
53
- "plan_id" => $newId,
54
- "amount" => "1.00",
55
- "name" => "discount_name"
56
- ];
57
-
58
- $http = new Braintree\Http(Braintree\Configuration::$global);
59
- $path = Braintree\Configuration::$global->merchantPath() . '/modifications/create_modification_for_tests';
60
- $http->post($path, ["modification" => $discountParams]);
61
-
62
- $plans = Braintree\Plan::all();
63
-
64
- foreach ($plans as $plan)
65
- {
66
- if ($plan->id == $newId)
67
- {
68
- $actualPlan = $plan;
69
- }
70
- }
71
-
72
- $this->assertNotNull($actualPlan);
73
- $this->assertEquals($params["billingDayOfMonth"], $actualPlan->billingDayOfMonth);
74
- $this->assertEquals($params["billingFrequency"], $actualPlan->billingFrequency);
75
- $this->assertEquals($params["currencyIsoCode"], $actualPlan->currencyIsoCode);
76
- $this->assertEquals($params["description"], $actualPlan->description);
77
- $this->assertEquals($params["name"], $actualPlan->name);
78
- $this->assertEquals($params["numberOfBillingCycles"], $actualPlan->numberOfBillingCycles);
79
- $this->assertEquals($params["price"], $actualPlan->price);
80
-
81
- $addOn = $actualPlan->addOns[0];
82
- $this->assertEquals($addOnParams["name"], $addOn->name);
83
-
84
- $discount = $actualPlan->discounts[0];
85
- $this->assertEquals($discountParams["name"], $discount->name);
86
- }
87
-
88
- public function testGatewayAll_returnsAllPlans()
89
- {
90
- $newId = strval(rand());
91
- $params = [
92
- "id" => $newId,
93
- "billingDayOfMonth" => "1",
94
- "billingFrequency" => "1",
95
- "currencyIsoCode" => "USD",
96
- "description" => "some description",
97
- "name" => "php test plan",
98
- "numberOfBillingCycles" => "1",
99
- "price" => "1.00",
100
- "trialPeriod" => "false"
101
- ];
102
-
103
- $http = new Braintree\Http(Braintree\Configuration::$global);
104
- $path = Braintree\Configuration::$global->merchantPath() . '/plans/create_plan_for_tests';
105
- $http->post($path, ["plan" => $params]);
106
-
107
- $gateway = new Braintree\Gateway([
108
- 'environment' => 'development',
109
- 'merchantId' => 'integration_merchant_id',
110
- 'publicKey' => 'integration_public_key',
111
- 'privateKey' => 'integration_private_key'
112
- ]);
113
- $plans = $gateway->plan()->all();
114
-
115
- foreach ($plans as $plan)
116
- {
117
- if ($plan->id == $newId)
118
- {
119
- $actualPlan = $plan;
120
- }
121
- }
122
-
123
- $this->assertNotNull($actualPlan);
124
- $this->assertEquals($params["billingDayOfMonth"], $actualPlan->billingDayOfMonth);
125
- $this->assertEquals($params["billingFrequency"], $actualPlan->billingFrequency);
126
- $this->assertEquals($params["currencyIsoCode"], $actualPlan->currencyIsoCode);
127
- $this->assertEquals($params["description"], $actualPlan->description);
128
- $this->assertEquals($params["name"], $actualPlan->name);
129
- $this->assertEquals($params["numberOfBillingCycles"], $actualPlan->numberOfBillingCycles);
130
- $this->assertEquals($params["price"], $actualPlan->price);
131
- }
132
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/Result/ErrorTest.php DELETED
@@ -1,33 +0,0 @@
1
- <?php
2
- namespace Test\Integration\Result;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ErrorTest extends Setup
10
- {
11
- public function testValueForHtmlField()
12
- {
13
- $result = Braintree\Customer::create([
14
- 'email' => 'invalid-email',
15
- 'creditCard' => [
16
- 'number' => 'invalid-number',
17
- 'expirationDate' => 'invalid-exp',
18
- 'billingAddress' => [
19
- 'countryName' => 'invalid-country'
20
- ]
21
- ],
22
- 'customFields' => [
23
- 'store_me' => 'some custom value'
24
- ]
25
- ]);
26
- $this->assertEquals(false, $result->success);
27
- $this->assertEquals('invalid-email', $result->valueForHtmlField('customer[email]'));
28
- $this->assertEquals('', $result->valueForHtmlField('customer[credit_card][number]'));
29
- $this->assertEquals('invalid-exp', $result->valueForHtmlField('customer[credit_card][expiration_date]'));
30
- $this->assertEquals('invalid-country', $result->valueForHtmlField('customer[credit_card][billing_address][country_name]'));
31
- $this->assertEquals('some custom value', $result->valueForHtmlField('customer[custom_fields][store_me]'));
32
- }
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/SettlementBatchSummaryTest.php DELETED
@@ -1,95 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class SettlementBatchSummaryTest extends Setup
12
- {
13
- public function isMasterCard($record)
14
- {
15
- return $record['cardType'] == Braintree\CreditCard::MASTER_CARD;
16
- }
17
-
18
- public function testGenerate_returnsAnEmptyCollectionWhenThereIsNoData()
19
- {
20
- $result = Braintree\SettlementBatchSummary::generate('2000-01-01');
21
-
22
- $this->assertTrue($result->success);
23
- $this->assertEquals(0, count($result->settlementBatchSummary->records));
24
- }
25
-
26
- public function testGatewayGenerate_returnsAnEmptyCollectionWhenThereIsNoData()
27
- {
28
- $gateway = new Braintree\Gateway([
29
- 'environment' => 'development',
30
- 'merchantId' => 'integration_merchant_id',
31
- 'publicKey' => 'integration_public_key',
32
- 'privateKey' => 'integration_private_key'
33
- ]);
34
- $result = $gateway->settlementBatchSummary()->generate('2000-01-01');
35
-
36
- $this->assertTrue($result->success);
37
- $this->assertEquals(0, count($result->settlementBatchSummary->records));
38
- }
39
-
40
- public function testGenerate_returnsAnErrorIfTheDateCanNotBeParsed()
41
- {
42
- $result = Braintree\SettlementBatchSummary::generate('OMG NOT A DATE');
43
-
44
- $this->assertFalse($result->success);
45
- $errors = $result->errors->forKey('settlementBatchSummary')->onAttribute('settlementDate');
46
- $this->assertEquals(Braintree\Error\Codes::SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_INVALID, $errors[0]->code);
47
- }
48
-
49
- public function testGenerate_returnsTransactionsSettledOnAGivenDay()
50
- {
51
- $transaction = Braintree\Transaction::saleNoValidate([
52
- 'amount' => '100.00',
53
- 'creditCard' => [
54
- 'number' => '5105105105105100',
55
- 'expirationDate' => '05/12'
56
- ],
57
- 'options' => ['submitForSettlement' => true]
58
- ]);
59
- Braintree\Test\Transaction::settle($transaction->id);
60
-
61
- $today = new Datetime;
62
- $result = Braintree\SettlementBatchSummary::generate(Test\Helper::nowInEastern());
63
-
64
- $this->assertTrue($result->success);
65
- $masterCardRecords = array_filter($result->settlementBatchSummary->records, 'self::isMasterCard');
66
- $masterCardKeys = array_keys($masterCardRecords);
67
- $masterCardIndex = $masterCardKeys[0];
68
- $this->assertTrue(count($masterCardRecords) > 0);
69
- $this->assertEquals(Braintree\CreditCard::MASTER_CARD, $masterCardRecords[$masterCardIndex]['cardType']);
70
- }
71
-
72
- public function testGenerate_canBeGroupedByACustomField()
73
- {
74
- $transaction = Braintree\Transaction::saleNoValidate([
75
- 'amount' => '100.00',
76
- 'creditCard' => [
77
- 'number' => '5105105105105100',
78
- 'expirationDate' => '05/12'
79
- ],
80
- 'customFields' => [
81
- 'store_me' => 'custom value'
82
- ],
83
- 'options' => ['submitForSettlement' => true]
84
- ]);
85
-
86
- Braintree\Test\Transaction::settle($transaction->id);
87
-
88
- $today = new Datetime;
89
- $result = Braintree\SettlementBatchSummary::generate(Test\Helper::nowInEastern(), 'store_me');
90
-
91
- $this->assertTrue($result->success);
92
- $this->assertTrue(count($result->settlementBatchSummary->records) > 0);
93
- $this->assertArrayHasKey('store_me', $result->settlementBatchSummary->records[0]);
94
- }
95
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/SubscriptionHelper.php DELETED
@@ -1,86 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- use Braintree;
5
-
6
- class SubscriptionHelper
7
- {
8
- public static function addOnDiscountPlan()
9
- {
10
- return [
11
- 'description' => "Plan for integration tests -- with add-ons and discounts",
12
- 'id' => "integration_plan_with_add_ons_and_discounts",
13
- 'price' => '9.99',
14
- 'trial_period' => true,
15
- 'trial_duration' => 2,
16
- 'trial_duration_unit' => 'day'
17
- ];
18
- }
19
-
20
- public static function billingDayOfMonthPlan()
21
- {
22
- return [
23
- 'description' => 'Plan for integration tests -- with billing day of month',
24
- 'id' => 'integration_plan_with_billing_day_of_month',
25
- 'numberOfBillingCycles' => 5,
26
- 'price' => '8.88',
27
- 'trial_period' => false
28
- ];
29
- }
30
-
31
- public static function trialPlan()
32
- {
33
- return [
34
- 'description' => 'Plan for integration tests -- with trial',
35
- 'id' => 'integration_trial_plan',
36
- 'numberOfBillingCycles' => 12,
37
- 'price' => '43.21',
38
- 'trial_period' => true,
39
- 'trial_duration' => 2,
40
- 'trial_duration_unit' => 'day'
41
- ];
42
- }
43
-
44
- public static function triallessPlan()
45
- {
46
- return [
47
- 'description' => 'Plan for integration tests -- without a trial',
48
- 'id' => 'integration_trialless_plan',
49
- 'numberOfBillingCycles' => 12,
50
- 'price' => '12.34',
51
- 'trial_period' => false
52
- ];
53
- }
54
-
55
- public static function createCreditCard()
56
- {
57
- $customer = Braintree\Customer::createNoValidate([
58
- 'creditCard' => [
59
- 'number' => '5105105105105100',
60
- 'expirationDate' => '05/2010'
61
- ]
62
- ]);
63
- return $customer->creditCards[0];
64
- }
65
-
66
- public static function createSubscription()
67
- {
68
- $plan = self::triallessPlan();
69
- $result = Braintree\Subscription::create([
70
- 'paymentMethodToken' => self::createCreditCard()->token,
71
- 'price' => '54.99',
72
- 'planId' => $plan['id']
73
- ]);
74
- return $result->subscription;
75
- }
76
-
77
- public static function compareModificationsById($left, $right)
78
- {
79
- return strcmp($left->id, $right->id);
80
- }
81
-
82
- public static function sortModificationsById(&$modifications)
83
- {
84
- usort($modifications, ['Test\Integration\SubscriptionHelper', 'compareModificationsById']);
85
- }
86
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/SubscriptionSearchTest.php DELETED
@@ -1,343 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class SubscriptionSearchTest extends Setup
12
- {
13
- public function testSearch_planIdIs()
14
- {
15
- $creditCard = SubscriptionHelper::createCreditCard();
16
- $triallessPlan = SubscriptionHelper::triallessPlan();
17
- $trialPlan = SubscriptionHelper::trialPlan();
18
-
19
- $trialSubscription = Braintree\Subscription::create([
20
- 'paymentMethodToken' => $creditCard->token,
21
- 'planId' => $trialPlan['id'],
22
- 'price' => '1'
23
- ])->subscription;
24
-
25
- $triallessSubscription = Braintree\Subscription::create([
26
- 'paymentMethodToken' => $creditCard->token,
27
- 'planId' => $triallessPlan['id'],
28
- 'price' => '1'
29
- ])->subscription;
30
-
31
- $collection = Braintree\Subscription::search([
32
- Braintree\SubscriptionSearch::planId()->is('integration_trial_plan'),
33
- Braintree\SubscriptionSearch::price()->is('1')
34
- ]);
35
-
36
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
37
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
38
- }
39
-
40
- public function test_noRequestsWhenIterating()
41
- {
42
- $resultsReturned = false;
43
- $collection = Braintree\Subscription::search([
44
- Braintree\SubscriptionSearch::planId()->is('imaginary')
45
- ]);
46
-
47
- foreach ($collection as $transaction) {
48
- $resultsReturned = true;
49
- break;
50
- }
51
-
52
- $this->assertSame(0, $collection->maximumCount());
53
- $this->assertEquals(false, $resultsReturned);
54
- }
55
-
56
- public function testSearch_inTrialPeriod()
57
- {
58
- $creditCard = SubscriptionHelper::createCreditCard();
59
- $triallessPlan = SubscriptionHelper::triallessPlan();
60
- $trialPlan = SubscriptionHelper::trialPlan();
61
-
62
- $trialSubscription = Braintree\Subscription::create([
63
- 'paymentMethodToken' => $creditCard->token,
64
- 'planId' => $trialPlan['id'],
65
- 'price' => '1'
66
- ])->subscription;
67
-
68
- $triallessSubscription = Braintree\Subscription::create([
69
- 'paymentMethodToken' => $creditCard->token,
70
- 'planId' => $triallessPlan['id'],
71
- 'price' => '1'
72
- ])->subscription;
73
-
74
- $subscriptions_in_trial = Braintree\Subscription::search([
75
- Braintree\SubscriptionSearch::inTrialPeriod()->is(true)
76
- ]);
77
-
78
- $this->assertTrue(Test\Helper::includes($subscriptions_in_trial, $trialSubscription));
79
- $this->assertFalse(Test\Helper::includes($subscriptions_in_trial, $triallessSubscription));
80
-
81
- $subscriptions_not_in_trial = Braintree\Subscription::search([
82
- Braintree\SubscriptionSearch::inTrialPeriod()->is(false)
83
- ]);
84
-
85
- $this->assertTrue(Test\Helper::includes($subscriptions_not_in_trial, $triallessSubscription));
86
- $this->assertFalse(Test\Helper::includes($subscriptions_not_in_trial, $trialSubscription));
87
- }
88
-
89
- public function testSearch_statusIsPastDue()
90
- {
91
- $found = false;
92
- $collection = Braintree\Subscription::search([
93
- Braintree\SubscriptionSearch::status()->in([Braintree\Subscription::PAST_DUE])
94
- ]);
95
- foreach ($collection AS $item) {
96
- $found = true;
97
- $this->assertEquals(Braintree\Subscription::PAST_DUE, $item->status);
98
- }
99
- $this->assertTrue($found);
100
- }
101
-
102
- public function testSearch_statusIsExpired()
103
- {
104
- $found = false;
105
- $collection = Braintree\Subscription::search([
106
- Braintree\SubscriptionSearch::status()->in([Braintree\Subscription::EXPIRED])
107
- ]);
108
- foreach ($collection as $item) {
109
- $found = true;
110
- $this->assertEquals(Braintree\Subscription::EXPIRED, $item->status);
111
- }
112
- $this->assertTrue($found);
113
- }
114
-
115
- public function testSearch_billingCyclesRemaing()
116
- {
117
- $creditCard = SubscriptionHelper::createCreditCard();
118
- $triallessPlan = SubscriptionHelper::triallessPlan();
119
-
120
- $subscription_4 = Braintree\Subscription::create([
121
- 'paymentMethodToken' => $creditCard->token,
122
- 'planId' => $triallessPlan['id'],
123
- 'numberOfBillingCycles' => 4
124
- ])->subscription;
125
-
126
- $subscription_8 = Braintree\Subscription::create([
127
- 'paymentMethodToken' => $creditCard->token,
128
- 'planId' => $triallessPlan['id'],
129
- 'numberOfBillingCycles' => 8
130
- ])->subscription;
131
-
132
- $subscription_10 = Braintree\Subscription::create([
133
- 'paymentMethodToken' => $creditCard->token,
134
- 'planId' => $triallessPlan['id'],
135
- 'numberOfBillingCycles' => 10
136
- ])->subscription;
137
-
138
- $collection = Braintree\Subscription::search([
139
- Braintree\SubscriptionSearch::billingCyclesRemaining()->between(5, 10)
140
- ]);
141
-
142
- $this->assertFalse(Test\Helper::includes($collection, $subscription_4));
143
- $this->assertTrue(Test\Helper::includes($collection, $subscription_8));
144
- $this->assertTrue(Test\Helper::includes($collection, $subscription_10));
145
- }
146
-
147
- public function testSearch_subscriptionId()
148
- {
149
- $creditCard = SubscriptionHelper::createCreditCard();
150
- $triallessPlan = SubscriptionHelper::triallessPlan();
151
-
152
- $rand_id = strval(rand());
153
-
154
- $subscription_1 = Braintree\Subscription::create([
155
- 'paymentMethodToken' => $creditCard->token,
156
- 'planId' => $triallessPlan['id'],
157
- 'id' => 'subscription_123_id_' . $rand_id
158
- ])->subscription;
159
-
160
- $subscription_2 = Braintree\Subscription::create([
161
- 'paymentMethodToken' => $creditCard->token,
162
- 'planId' => $triallessPlan['id'],
163
- 'id' => 'subscription_23_id_' . $rand_id
164
- ])->subscription;
165
-
166
- $subscription_3 = Braintree\Subscription::create([
167
- 'paymentMethodToken' => $creditCard->token,
168
- 'planId' => $triallessPlan['id'],
169
- 'id' => 'subscription_3_id_' . $rand_id
170
- ])->subscription;
171
-
172
- $collection = Braintree\Subscription::search([
173
- Braintree\SubscriptionSearch::id()->contains('23_id_')
174
- ]);
175
-
176
- $this->assertTrue(Test\Helper::includes($collection, $subscription_1));
177
- $this->assertTrue(Test\Helper::includes($collection, $subscription_2));
178
- $this->assertFalse(Test\Helper::includes($collection, $subscription_3));
179
- }
180
-
181
- public function testSearch_merchantAccountId()
182
- {
183
- $creditCard = SubscriptionHelper::createCreditCard();
184
- $triallessPlan = SubscriptionHelper::triallessPlan();
185
-
186
- $rand_id = strval(rand());
187
-
188
- $subscription_1 = Braintree\Subscription::create([
189
- 'paymentMethodToken' => $creditCard->token,
190
- 'planId' => $triallessPlan['id'],
191
- 'id' => strval(rand()) . '_subscription_' . $rand_id,
192
- 'price' => '2'
193
- ])->subscription;
194
-
195
- $subscription_2 = Braintree\Subscription::create([
196
- 'paymentMethodToken' => $creditCard->token,
197
- 'planId' => $triallessPlan['id'],
198
- 'id' => strval(rand()) . '_subscription_' . $rand_id,
199
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
200
- 'price' => '2'
201
- ])->subscription;
202
-
203
- $collection = Braintree\Subscription::search([
204
- Braintree\SubscriptionSearch::id()->endsWith('subscription_' . $rand_id),
205
- Braintree\SubscriptionSearch::merchantAccountId()->in([Test\Helper::nonDefaultMerchantAccountId()]),
206
- Braintree\SubscriptionSearch::price()->is('2')
207
- ]);
208
-
209
- $this->assertFalse(Test\Helper::includes($collection, $subscription_1));
210
- $this->assertTrue(Test\Helper::includes($collection, $subscription_2));
211
- }
212
-
213
- public function testSearch_bogusMerchantAccountId()
214
- {
215
- $creditCard = SubscriptionHelper::createCreditCard();
216
- $triallessPlan = SubscriptionHelper::triallessPlan();
217
-
218
- $rand_id = strval(rand());
219
-
220
- $subscription = Braintree\Subscription::create([
221
- 'paymentMethodToken' => $creditCard->token,
222
- 'planId' => $triallessPlan['id'],
223
- 'id' => strval(rand()) . '_subscription_' . $rand_id,
224
- 'price' => '11.38'
225
- ])->subscription;
226
-
227
- $collection = Braintree\Subscription::search([
228
- Braintree\SubscriptionSearch::id()->endsWith('subscription_' . $rand_id),
229
- Braintree\SubscriptionSearch::merchantAccountId()->in(['bogus_merchant_account']),
230
- Braintree\SubscriptionSearch::price()->is('11.38')
231
- ]);
232
-
233
- $this->assertFalse(Test\Helper::includes($collection, $subscription));
234
- }
235
-
236
- public function testSearch_daysPastDue()
237
- {
238
- $creditCard = SubscriptionHelper::createCreditCard();
239
- $triallessPlan = SubscriptionHelper::triallessPlan();
240
-
241
- $subscription = Braintree\Subscription::create([
242
- 'paymentMethodToken' => $creditCard->token,
243
- 'planId' => $triallessPlan['id']
244
- ])->subscription;
245
-
246
- $http = new Braintree\Http(Braintree\Configuration::$global);
247
- $path = Braintree\Configuration::$global->merchantPath() . '/subscriptions/' . $subscription->id . '/make_past_due';
248
- $http->put($path, ['daysPastDue' => 5]);
249
-
250
- $found = false;
251
- $collection = Braintree\Subscription::search([
252
- Braintree\SubscriptionSearch::daysPastDue()->between(2, 10)
253
- ]);
254
- foreach ($collection AS $item) {
255
- $found = true;
256
- $this->assertTrue($item->daysPastDue <= 10);
257
- $this->assertTrue($item->daysPastDue >= 2);
258
- }
259
- $this->assertTrue($found);
260
- }
261
-
262
- public function testSearch_price()
263
- {
264
- $creditCard = SubscriptionHelper::createCreditCard();
265
- $triallessPlan = SubscriptionHelper::triallessPlan();
266
-
267
- $subscription_850 = Braintree\Subscription::create([
268
- 'paymentMethodToken' => $creditCard->token,
269
- 'planId' => $triallessPlan['id'],
270
- 'price' => '8.50'
271
- ])->subscription;
272
-
273
- $subscription_851 = Braintree\Subscription::create([
274
- 'paymentMethodToken' => $creditCard->token,
275
- 'planId' => $triallessPlan['id'],
276
- 'price' => '8.51'
277
- ])->subscription;
278
-
279
- $subscription_852 = Braintree\Subscription::create([
280
- 'paymentMethodToken' => $creditCard->token,
281
- 'planId' => $triallessPlan['id'],
282
- 'price' => '8.52'
283
- ])->subscription;
284
-
285
- $collection = Braintree\Subscription::search([
286
- Braintree\SubscriptionSearch::price()->between('8.51', '8.52')
287
- ]);
288
-
289
- $this->assertTrue(Test\Helper::includes($collection, $subscription_851));
290
- $this->assertTrue(Test\Helper::includes($collection, $subscription_852));
291
- $this->assertFalse(Test\Helper::includes($collection, $subscription_850));
292
- }
293
-
294
- public function testSearch_nextBillingDate()
295
- {
296
- $creditCard = SubscriptionHelper::createCreditCard();
297
- $triallessPlan = SubscriptionHelper::triallessPlan();
298
- $trialPlan = SubscriptionHelper::trialPlan();
299
-
300
- $triallessSubscription = Braintree\Subscription::create([
301
- 'paymentMethodToken' => $creditCard->token,
302
- 'planId' => $triallessPlan['id'],
303
- ])->subscription;
304
-
305
- $trialSubscription = Braintree\Subscription::create([
306
- 'paymentMethodToken' => $creditCard->token,
307
- 'planId' => $trialPlan['id'],
308
- ])->subscription;
309
-
310
- $fiveDaysFromNow = new DateTime();
311
- $fiveDaysFromNow->modify("+5 days");
312
-
313
- $collection = Braintree\Subscription::search([
314
- Braintree\SubscriptionSearch::nextBillingDate()->greaterThanOrEqualTo($fiveDaysFromNow),
315
- ]);
316
-
317
- $this->assertTrue(Test\Helper::includes($collection, $triallessSubscription));
318
- $this->assertFalse(Test\Helper::includes($collection, $trialSubscription));
319
- }
320
-
321
- public function testSearch_transactionId()
322
- {
323
- $creditCard = SubscriptionHelper::createCreditCard();
324
- $triallessPlan = SubscriptionHelper::triallessPlan();
325
-
326
- $matchingSubscription = Braintree\Subscription::create([
327
- 'paymentMethodToken' => $creditCard->token,
328
- 'planId' => $triallessPlan['id'],
329
- ])->subscription;
330
-
331
- $nonMatchingSubscription = Braintree\Subscription::create([
332
- 'paymentMethodToken' => $creditCard->token,
333
- 'planId' => $triallessPlan['id'],
334
- ])->subscription;
335
-
336
- $collection = Braintree\Subscription::search([
337
- Braintree\SubscriptionSearch::transactionId()->is($matchingSubscription->transactions[0]->id),
338
- ]);
339
-
340
- $this->assertTrue(Test\Helper::includes($collection, $matchingSubscription));
341
- $this->assertFalse(Test\Helper::includes($collection, $nonMatchingSubscription));
342
- }
343
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/SubscriptionTest.php DELETED
@@ -1,1202 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class SubscriptionTest extends Setup
12
- {
13
- public function testCreate_doesNotAcceptBadAttributes()
14
- {
15
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: bad');
16
- $result = Braintree\Subscription::create([
17
- 'bad' => 'value'
18
- ]);
19
- }
20
-
21
- public function testCreate_whenSuccessful()
22
- {
23
- $creditCard = SubscriptionHelper::createCreditCard();
24
- $plan = SubscriptionHelper::triallessPlan();
25
- $result = Braintree\Subscription::create([
26
- 'paymentMethodToken' => $creditCard->token,
27
- 'planId' => $plan['id']
28
-
29
- ]);
30
- Test\Helper::assertPrintable($result);
31
- $this->assertTrue($result->success);
32
- $subscription = $result->subscription;
33
- $this->assertEquals($creditCard->token, $subscription->paymentMethodToken);
34
- $this->assertEquals(0, $subscription->failureCount);
35
- $this->assertEquals($plan['id'], $subscription->planId);
36
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $subscription->merchantAccountId);
37
- $this->assertEquals(Braintree\Subscription::ACTIVE, $subscription->status);
38
- $this->assertEquals('12.34', $subscription->nextBillAmount);
39
- $this->assertEquals('12.34', $subscription->nextBillingPeriodAmount);
40
- $this->assertEquals('0.00', $subscription->balance);
41
- $this->assertEquals(1, $subscription->currentBillingCycle);
42
- $this->assertInstanceOf('DateTime', $subscription->firstBillingDate);
43
- $this->assertInstanceOf('DateTime', $subscription->nextBillingDate);
44
- $this->assertInstanceOf('DateTime', $subscription->billingPeriodStartDate);
45
- $this->assertInstanceOf('DateTime', $subscription->billingPeriodEndDate);
46
- $this->assertInstanceOf('DateTime', $subscription->paidThroughDate);
47
- $this->assertInstanceOf('DateTime', $subscription->updatedAt);
48
- $this->assertInstanceOf('DateTime', $subscription->createdAt);
49
-
50
- $this->assertEquals('12.34', $subscription->statusHistory[0]->price);
51
- $this->assertEquals('0.00', $subscription->statusHistory[0]->balance);
52
- $this->assertEquals(Braintree\Subscription::ACTIVE, $subscription->statusHistory[0]->status);
53
- $this->assertEquals(Braintree\Subscription::API, $subscription->statusHistory[0]->subscriptionSource);
54
- }
55
-
56
- public function testGatewayCreate_whenSuccessful()
57
- {
58
- $creditCard = SubscriptionHelper::createCreditCard();
59
- $plan = SubscriptionHelper::triallessPlan();
60
-
61
- $gateway = new Braintree\Gateway([
62
- 'environment' => 'development',
63
- 'merchantId' => 'integration_merchant_id',
64
- 'publicKey' => 'integration_public_key',
65
- 'privateKey' => 'integration_private_key'
66
- ]);
67
- $result = $gateway->subscription()->create([
68
- 'paymentMethodToken' => $creditCard->token,
69
- 'planId' => $plan['id']
70
-
71
- ]);
72
- Test\Helper::assertPrintable($result);
73
- $this->assertTrue($result->success);
74
- $subscription = $result->subscription;
75
- $this->assertEquals($creditCard->token, $subscription->paymentMethodToken);
76
- $this->assertEquals(0, $subscription->failureCount);
77
- $this->assertEquals($plan['id'], $subscription->planId);
78
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $subscription->merchantAccountId);
79
- $this->assertEquals(Braintree\Subscription::ACTIVE, $subscription->status);
80
- }
81
-
82
- public function testCreate_withPaymentMethodNonce()
83
- {
84
- $customerId = Braintree\Customer::create()->customer->id;
85
- $http = new HttpClientApi(Braintree\Configuration::$global);
86
- $nonce = $http->nonce_for_new_card([
87
- "creditCard" => [
88
- "number" => "4111111111111111",
89
- "expirationMonth" => "11",
90
- "expirationYear" => "2099"
91
- ],
92
- "customerId" => $customerId,
93
- "share" => true
94
- ]);
95
- $plan = SubscriptionHelper::triallessPlan();
96
- $result = Braintree\Subscription::create([
97
- 'paymentMethodNonce' => $nonce,
98
- 'planId' => $plan['id']
99
- ]);
100
-
101
- $this->assertTrue($result->success);
102
-
103
- $transaction = $result->subscription->transactions[0];
104
- $this->assertEquals("411111", $transaction->creditCardDetails->bin);
105
- $this->assertEquals("1111", $transaction->creditCardDetails->last4);
106
- }
107
-
108
- public function testCreate_returnsTransactionWhenTransactionFails()
109
- {
110
- $creditCard = SubscriptionHelper::createCreditCard();
111
- $plan = SubscriptionHelper::triallessPlan();
112
- $result = Braintree\Subscription::create([
113
- 'paymentMethodToken' => $creditCard->token,
114
- 'planId' => $plan['id'],
115
- 'price' => Braintree\Test\TransactionAmounts::$decline
116
-
117
- ]);
118
- Test\Helper::assertPrintable($result);
119
- $this->assertFalse($result->success);
120
- $this->assertEquals(Braintree\Transaction::PROCESSOR_DECLINED, $result->transaction->status);
121
- }
122
-
123
- public function testCreate_canSetTheId()
124
- {
125
- $creditCard = SubscriptionHelper::createCreditCard();
126
- $newId = strval(rand());
127
- $plan = SubscriptionHelper::triallessPlan();
128
- $result = Braintree\Subscription::create([
129
- 'paymentMethodToken' => $creditCard->token,
130
- 'planId' => $plan['id'],
131
- 'id' => $newId
132
- ]);
133
-
134
- $this->assertTrue($result->success);
135
- $subscription = $result->subscription;
136
- $this->assertEquals($newId, $subscription->id);
137
- }
138
-
139
- public function testCreate_canSetTheMerchantAccountId()
140
- {
141
- $creditCard = SubscriptionHelper::createCreditCard();
142
- $plan = SubscriptionHelper::triallessPlan();
143
- $result = Braintree\Subscription::create([
144
- 'paymentMethodToken' => $creditCard->token,
145
- 'planId' => $plan['id'],
146
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId()
147
- ]);
148
-
149
- $this->assertTrue($result->success);
150
- $subscription = $result->subscription;
151
- $this->assertEquals(Test\Helper::nonDefaultMerchantAccountId(), $subscription->merchantAccountId);
152
- }
153
-
154
- public function testCreate_trialPeriodDefaultsToPlanWithoutTrial()
155
- {
156
- $creditCard = SubscriptionHelper::createCreditCard();
157
- $plan = SubscriptionHelper::triallessPlan();
158
- $result = Braintree\Subscription::create([
159
- 'paymentMethodToken' => $creditCard->token,
160
- 'planId' => $plan['id'],
161
- ]);
162
- $subscription = $result->subscription;
163
- $this->assertFalse($subscription->trialPeriod);
164
- $this->assertNull($subscription->trialDuration);
165
- $this->assertNull($subscription->trialDurationUnit);
166
- }
167
-
168
- public function testCreate_trialPeriondDefaultsToPlanWithTrial()
169
- {
170
- $creditCard = SubscriptionHelper::createCreditCard();
171
- $plan = SubscriptionHelper::trialPlan();
172
- $result = Braintree\Subscription::create([
173
- 'paymentMethodToken' => $creditCard->token,
174
- 'planId' => $plan['id'],
175
- ]);
176
- $subscription = $result->subscription;
177
- $this->assertTrue($subscription->trialPeriod);
178
- $this->assertEquals(2, $subscription->trialDuration);
179
- $this->assertEquals('day', $subscription->trialDurationUnit);
180
- }
181
-
182
- public function testCreate_alterPlanTrialPeriod()
183
- {
184
- $creditCard = SubscriptionHelper::createCreditCard();
185
- $plan = SubscriptionHelper::trialPlan();
186
- $result = Braintree\Subscription::create([
187
- 'paymentMethodToken' => $creditCard->token,
188
- 'planId' => $plan['id'],
189
- 'trialDuration' => 5,
190
- 'trialDurationUnit' => 'month'
191
- ]);
192
- $subscription = $result->subscription;
193
- $this->assertTrue($subscription->trialPeriod);
194
- $this->assertEquals(5, $subscription->trialDuration);
195
- $this->assertEquals('month', $subscription->trialDurationUnit);
196
- }
197
-
198
- public function testCreate_removePlanTrialPeriod()
199
- {
200
- $creditCard = SubscriptionHelper::createCreditCard();
201
- $plan = SubscriptionHelper::trialPlan();
202
- $result = Braintree\Subscription::create([
203
- 'paymentMethodToken' => $creditCard->token,
204
- 'planId' => $plan['id'],
205
- 'trialPeriod' => false,
206
- ]);
207
- $subscription = $result->subscription;
208
- $this->assertFalse($subscription->trialPeriod);
209
- }
210
-
211
- public function testCreate_createsATransactionIfNoTrialPeriod()
212
- {
213
- $creditCard = SubscriptionHelper::createCreditCard();
214
- $plan = SubscriptionHelper::triallessPlan();
215
- $result = Braintree\Subscription::create([
216
- 'paymentMethodToken' => $creditCard->token,
217
- 'planId' => $plan['id'],
218
- ]);
219
- $subscription = $result->subscription;
220
- $this->assertEquals(1, sizeof($subscription->transactions));
221
- $transaction = $subscription->transactions[0];
222
- $this->assertInstanceOf('Braintree\Transaction', $transaction);
223
- $this->assertEquals($plan['price'], $transaction->amount);
224
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
225
- $this->assertEquals($subscription->id, $transaction->subscriptionId);
226
- }
227
-
228
- public function testCreate_doesNotCreateTransactionIfTrialPeriod()
229
- {
230
- $creditCard = SubscriptionHelper::createCreditCard();
231
- $plan = SubscriptionHelper::trialPlan();
232
- $result = Braintree\Subscription::create([
233
- 'paymentMethodToken' => $creditCard->token,
234
- 'planId' => $plan['id'],
235
- ]);
236
- $subscription = $result->subscription;
237
- $this->assertEquals(0, sizeof($subscription->transactions));
238
- }
239
-
240
- public function testCreate_returnsATransactionWithSubscriptionBillingPeriod()
241
- {
242
- $creditCard = SubscriptionHelper::createCreditCard();
243
- $plan = SubscriptionHelper::triallessPlan();
244
- $result = Braintree\Subscription::create([
245
- 'paymentMethodToken' => $creditCard->token,
246
- 'planId' => $plan['id'],
247
- ]);
248
- $subscription = $result->subscription;
249
- $transaction = $subscription->transactions[0];
250
- $this->assertEquals($subscription->billingPeriodStartDate, $transaction->subscriptionDetails->billingPeriodStartDate);
251
- $this->assertEquals($subscription->billingPeriodEndDate, $transaction->subscriptionDetails->billingPeriodEndDate);
252
- }
253
-
254
- public function testCreate_priceCanBeOverriden()
255
- {
256
- $creditCard = SubscriptionHelper::createCreditCard();
257
- $plan = SubscriptionHelper::trialPlan();
258
- $result = Braintree\Subscription::create([
259
- 'paymentMethodToken' => $creditCard->token,
260
- 'planId' => $plan['id'],
261
- 'price' => '2.00'
262
- ]);
263
- $subscription = $result->subscription;
264
- $this->assertEquals('2.00', $subscription->price);
265
- }
266
-
267
- public function testCreate_billingDayOfMonthIsInheritedFromPlan()
268
- {
269
- $creditCard = SubscriptionHelper::createCreditCard();
270
- $plan = SubscriptionHelper::billingDayOfMonthPlan();
271
- $result = Braintree\Subscription::create([
272
- 'paymentMethodToken' => $creditCard->token,
273
- 'planId' => $plan['id']
274
- ]);
275
- $subscription = $result->subscription;
276
- $this->assertEquals(5, $subscription->billingDayOfMonth);
277
- }
278
-
279
- public function testCreate_billingDayOfMonthCanBeOverriden()
280
- {
281
- $creditCard = SubscriptionHelper::createCreditCard();
282
- $plan = SubscriptionHelper::billingDayOfMonthPlan();
283
- $result = Braintree\Subscription::create([
284
- 'paymentMethodToken' => $creditCard->token,
285
- 'planId' => $plan['id'],
286
- 'billingDayOfMonth' => 14
287
- ]);
288
- $subscription = $result->subscription;
289
- $this->assertEquals(14, $subscription->billingDayOfMonth);
290
- }
291
-
292
- public function testCreate_billingDayOfMonthCanBeOverridenWithStartImmediately()
293
- {
294
- $creditCard = SubscriptionHelper::createCreditCard();
295
- $plan = SubscriptionHelper::billingDayOfMonthPlan();
296
- $result = Braintree\Subscription::create([
297
- 'paymentMethodToken' => $creditCard->token,
298
- 'planId' => $plan['id'],
299
- 'options' => ['startImmediately' => true]
300
- ]);
301
- $subscription = $result->subscription;
302
- $this->assertEquals(1, sizeof($subscription->transactions));
303
- }
304
-
305
- public function testCreate_firstBillingDateCanBeSet()
306
- {
307
- $creditCard = SubscriptionHelper::createCreditCard();
308
- $plan = SubscriptionHelper::billingDayOfMonthPlan();
309
-
310
- $tomorrow = new DateTime("now + 1 day");
311
- $tomorrow->setTime(0,0,0);
312
-
313
- $result = Braintree\Subscription::create([
314
- 'paymentMethodToken' => $creditCard->token,
315
- 'planId' => $plan['id'],
316
- 'firstBillingDate' => $tomorrow
317
- ]);
318
-
319
- $subscription = $result->subscription;
320
- $this->assertEquals($tomorrow, $subscription->firstBillingDate);
321
- $this->assertEquals(Braintree\Subscription::PENDING, $result->subscription->status);
322
- }
323
-
324
- public function testCreate_firstBillingDateInThePast()
325
- {
326
- $creditCard = SubscriptionHelper::createCreditCard();
327
- $plan = SubscriptionHelper::billingDayOfMonthPlan();
328
-
329
- $past = new DateTime("now - 3 days");
330
- $past->setTime(0,0,0);
331
-
332
- $result = Braintree\Subscription::create([
333
- 'paymentMethodToken' => $creditCard->token,
334
- 'planId' => $plan['id'],
335
- 'firstBillingDate' => $past
336
- ]);
337
-
338
- $this->assertFalse($result->success);
339
- $errors = $result->errors->forKey('subscription')->onAttribute('firstBillingDate');
340
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_IN_THE_PAST, $errors[0]->code);
341
- }
342
-
343
- public function testCreate_numberOfBillingCyclesCanBeOverridden()
344
- {
345
- $creditCard = SubscriptionHelper::createCreditCard();
346
- $plan = SubscriptionHelper::trialPlan();
347
- $result = Braintree\Subscription::create([
348
- 'paymentMethodToken' => $creditCard->token,
349
- 'planId' => $plan['id']
350
- ]);
351
- $subscription = $result->subscription;
352
- $this->assertEquals($plan['numberOfBillingCycles'], $subscription->numberOfBillingCycles);
353
-
354
- $result = Braintree\Subscription::create([
355
- 'numberOfBillingCycles' => '10',
356
- 'paymentMethodToken' => $creditCard->token,
357
- 'planId' => $plan['id']
358
- ]);
359
- $subscription = $result->subscription;
360
- $this->assertEquals(10, $subscription->numberOfBillingCycles);
361
- $this->assertFalse($subscription->neverExpires);
362
- }
363
-
364
- public function testCreate_numberOfBillingCyclesCanBeOverriddenToNeverExpire()
365
- {
366
- $creditCard = SubscriptionHelper::createCreditCard();
367
- $plan = SubscriptionHelper::trialPlan();
368
- $result = Braintree\Subscription::create([
369
- 'paymentMethodToken' => $creditCard->token,
370
- 'planId' => $plan['id']
371
- ]);
372
- $subscription = $result->subscription;
373
- $this->assertEquals($plan['numberOfBillingCycles'], $subscription->numberOfBillingCycles);
374
-
375
- $result = Braintree\Subscription::create([
376
- 'neverExpires' => true,
377
- 'paymentMethodToken' => $creditCard->token,
378
- 'planId' => $plan['id']
379
- ]);
380
- $subscription = $result->subscription;
381
- $this->assertNull($subscription->numberOfBillingCycles);
382
- $this->assertTrue($subscription->neverExpires);
383
- }
384
-
385
- public function testCreate_doesNotInheritAddOnsAndDiscountsWhenDoNotInheritAddOnsOrDiscountsIsSet()
386
- {
387
- $creditCard = SubscriptionHelper::createCreditCard();
388
- $plan = SubscriptionHelper::addOnDiscountPlan();
389
- $result = Braintree\Subscription::create([
390
- 'paymentMethodToken' => $creditCard->token,
391
- 'planId' => $plan['id'],
392
- 'options' => ['doNotInheritAddOnsOrDiscounts' => true]
393
- ]);
394
- $subscription = $result->subscription;
395
- $this->assertEquals(0, sizeof($subscription->addOns));
396
- $this->assertEquals(0, sizeof($subscription->discounts));
397
- }
398
-
399
- public function testCreate_inheritsAddOnsAndDiscountsFromPlanByDefault()
400
- {
401
- $creditCard = SubscriptionHelper::createCreditCard();
402
- $plan = SubscriptionHelper::addOnDiscountPlan();
403
- $result = Braintree\Subscription::create([
404
- 'paymentMethodToken' => $creditCard->token,
405
- 'planId' => $plan['id'],
406
- ]);
407
- $subscription = $result->subscription;
408
- $this->assertEquals(2, sizeof($subscription->addOns));
409
- $addOns = $subscription->addOns;
410
- SubscriptionHelper::sortModificationsById($addOns);
411
-
412
- $this->assertEquals($addOns[0]->amount, "10.00");
413
- $this->assertEquals($addOns[0]->quantity, 1);
414
- $this->assertEquals($addOns[0]->numberOfBillingCycles, null);
415
- $this->assertEquals($addOns[0]->neverExpires, true);
416
- $this->assertEquals($addOns[0]->currentBillingCycle, 0);
417
-
418
- $this->assertEquals($addOns[1]->amount, "20.00");
419
- $this->assertEquals($addOns[1]->quantity, 1);
420
- $this->assertEquals($addOns[1]->numberOfBillingCycles, null);
421
- $this->assertEquals($addOns[1]->neverExpires, true);
422
- $this->assertEquals($addOns[1]->currentBillingCycle, 0);
423
-
424
- $this->assertEquals(2, sizeof($subscription->discounts));
425
- $discounts = $subscription->discounts;
426
- SubscriptionHelper::sortModificationsById($discounts);
427
-
428
- $this->assertEquals($discounts[0]->amount, "11.00");
429
- $this->assertEquals($discounts[0]->quantity, 1);
430
- $this->assertEquals($discounts[0]->numberOfBillingCycles, null);
431
- $this->assertEquals($discounts[0]->neverExpires, true);
432
- $this->assertEquals($discounts[0]->currentBillingCycle, 0);
433
-
434
- $this->assertEquals($discounts[1]->amount, "7.00");
435
- $this->assertEquals($discounts[1]->quantity, 1);
436
- $this->assertEquals($discounts[1]->numberOfBillingCycles, null);
437
- $this->assertEquals($discounts[1]->neverExpires, true);
438
- $this->assertEquals($discounts[1]->currentBillingCycle, 0);
439
- }
440
-
441
- public function testCreate_allowsOverridingInheritedAddOnsAndDiscounts()
442
- {
443
- $creditCard = SubscriptionHelper::createCreditCard();
444
- $plan = SubscriptionHelper::addOnDiscountPlan();
445
- $result = Braintree\Subscription::create([
446
- 'paymentMethodToken' => $creditCard->token,
447
- 'planId' => $plan['id'],
448
- 'addOns' => [
449
- 'update' => [
450
- [
451
- 'amount' => '50.00',
452
- 'existingId' => 'increase_10',
453
- 'quantity' => 2,
454
- 'numberOfBillingCycles' => 5
455
- ],
456
- [
457
- 'amount' => '60.00',
458
- 'existingId' => 'increase_20',
459
- 'quantity' => 4,
460
- 'numberOfBillingCycles' => 9
461
- ]
462
- ],
463
- ],
464
- 'discounts' => [
465
- 'update' => [
466
- [
467
- 'amount' => '15.00',
468
- 'existingId' => 'discount_7',
469
- 'quantity' => 2,
470
- 'neverExpires' => true
471
- ]
472
- ]
473
- ]
474
- ]);
475
- $subscription = $result->subscription;
476
- $this->assertEquals(2, sizeof($subscription->addOns));
477
- $addOns = $subscription->addOns;
478
- SubscriptionHelper::sortModificationsById($addOns);
479
-
480
- $this->assertEquals($addOns[0]->amount, "50.00");
481
- $this->assertEquals($addOns[0]->quantity, 2);
482
- $this->assertEquals($addOns[0]->numberOfBillingCycles, 5);
483
- $this->assertEquals($addOns[0]->neverExpires, false);
484
- $this->assertEquals($addOns[0]->currentBillingCycle, 0);
485
-
486
- $this->assertEquals($addOns[1]->amount, "60.00");
487
- $this->assertEquals($addOns[1]->quantity, 4);
488
- $this->assertEquals($addOns[1]->numberOfBillingCycles, 9);
489
- $this->assertEquals($addOns[1]->neverExpires, false);
490
- $this->assertEquals($addOns[1]->currentBillingCycle, 0);
491
-
492
- $this->assertEquals(2, sizeof($subscription->discounts));
493
- $discounts = $subscription->discounts;
494
- SubscriptionHelper::sortModificationsById($discounts);
495
-
496
- $this->assertEquals($discounts[0]->amount, "11.00");
497
- $this->assertEquals($discounts[0]->quantity, 1);
498
- $this->assertEquals($discounts[0]->numberOfBillingCycles, null);
499
- $this->assertEquals($discounts[0]->neverExpires, true);
500
- $this->assertEquals($discounts[0]->currentBillingCycle, 0);
501
-
502
- $this->assertEquals($discounts[1]->amount, "15.00");
503
- $this->assertEquals($discounts[1]->quantity, 2);
504
- $this->assertEquals($discounts[1]->numberOfBillingCycles, null);
505
- $this->assertEquals($discounts[1]->neverExpires, true);
506
- $this->assertEquals($discounts[1]->currentBillingCycle, 0);
507
- }
508
-
509
- public function testCreate_allowsRemovalOfInheritedAddOnsAndDiscounts()
510
- {
511
- $creditCard = SubscriptionHelper::createCreditCard();
512
- $plan = SubscriptionHelper::addOnDiscountPlan();
513
- $result = Braintree\Subscription::create([
514
- 'paymentMethodToken' => $creditCard->token,
515
- 'planId' => $plan['id'],
516
- 'addOns' => [
517
- 'remove' => ['increase_10', 'increase_20']
518
- ],
519
- 'discounts' => [
520
- 'remove' => ['discount_7']
521
- ]
522
- ]);
523
- $subscription = $result->subscription;
524
- $this->assertEquals(0, sizeof($subscription->addOns));
525
-
526
- $this->assertEquals(1, sizeof($subscription->discounts));
527
-
528
- $this->assertEquals($subscription->discounts[0]->amount, "11.00");
529
- $this->assertEquals($subscription->discounts[0]->quantity, 1);
530
- $this->assertEquals($subscription->discounts[0]->numberOfBillingCycles, null);
531
- $this->assertEquals($subscription->discounts[0]->neverExpires, true);
532
- $this->assertEquals($subscription->discounts[0]->currentBillingCycle, 0);
533
- }
534
-
535
- public function testCreate_allowsAddingNewAddOnsAndDiscounts()
536
- {
537
- $creditCard = SubscriptionHelper::createCreditCard();
538
- $plan = SubscriptionHelper::addOnDiscountPlan();
539
- $result = Braintree\Subscription::create([
540
- 'paymentMethodToken' => $creditCard->token,
541
- 'planId' => $plan['id'],
542
- 'addOns' => [
543
- 'add' => [
544
- [
545
- 'inheritedFromId' => 'increase_30',
546
- 'amount' => '35.00',
547
- 'neverExpires' => true,
548
- 'quantity' => 2
549
- ],
550
- ],
551
- ],
552
- 'discounts' => [
553
- 'add' => [
554
- [
555
- 'inheritedFromId' => 'discount_15',
556
- 'amount' => '15.50',
557
- 'numberOfBillingCycles' => 10,
558
- 'quantity' => 3
559
- ]
560
- ]
561
- ]
562
- ]);
563
-
564
- $subscription = $result->subscription;
565
- $this->assertEquals(3, sizeof($subscription->addOns));
566
- $addOns = $subscription->addOns;
567
- SubscriptionHelper::sortModificationsById($addOns);
568
-
569
- $this->assertEquals($addOns[0]->amount, "10.00");
570
- $this->assertEquals($addOns[1]->amount, "20.00");
571
- $this->assertEquals($addOns[2]->id, "increase_30");
572
- $this->assertEquals($addOns[2]->amount, "35.00");
573
- $this->assertEquals($addOns[2]->neverExpires, true);
574
- $this->assertEquals($addOns[2]->numberOfBillingCycles, null);
575
- $this->assertEquals($addOns[2]->quantity, 2);
576
- $this->assertEquals($addOns[2]->currentBillingCycle, 0);
577
-
578
-
579
- $this->assertEquals(3, sizeof($subscription->discounts));
580
- $discounts = $subscription->discounts;
581
- SubscriptionHelper::sortModificationsById($discounts);
582
-
583
- $this->assertEquals($discounts[0]->amount, "11.00");
584
-
585
- $this->assertEquals($discounts[1]->amount, "15.50");
586
- $this->assertEquals($discounts[1]->id, "discount_15");
587
- $this->assertEquals($discounts[1]->neverExpires, false);
588
- $this->assertEquals($discounts[1]->numberOfBillingCycles, 10);
589
- $this->assertEquals($discounts[1]->quantity, 3);
590
- $this->assertEquals($discounts[1]->currentBillingCycle, 0);
591
-
592
- $this->assertEquals($discounts[2]->amount, "7.00");
593
- }
594
-
595
- public function testCreate_properlyParsesValidationErrorsForArrays()
596
- {
597
- $creditCard = SubscriptionHelper::createCreditCard();
598
- $plan = SubscriptionHelper::addOnDiscountPlan();
599
- $result = Braintree\Subscription::create([
600
- 'paymentMethodToken' => $creditCard->token,
601
- 'planId' => $plan['id'],
602
- 'addOns' => [
603
- 'update' => [
604
- [
605
- 'existingId' => 'increase_10',
606
- 'amount' => 'invalid',
607
- ],
608
- [
609
- 'existingId' => 'increase_20',
610
- 'quantity' => -10,
611
- ]
612
- ]
613
- ]
614
- ]);
615
-
616
- $this->assertFalse($result->success);
617
- $errors = $result->errors->forKey('subscription')->forKey('addOns')->forKey('update')->forIndex(0)->onAttribute('amount');
618
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_MODIFICATION_AMOUNT_IS_INVALID, $errors[0]->code);
619
- $errors = $result->errors->forKey('subscription')->forKey('addOns')->forKey('update')->forIndex(1)->onAttribute('quantity');
620
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_MODIFICATION_QUANTITY_IS_INVALID, $errors[0]->code);
621
- }
622
-
623
- public function testCreate_withDescriptor()
624
- {
625
- $creditCard = SubscriptionHelper::createCreditCard();
626
- $plan = SubscriptionHelper::triallessPlan();
627
- $result = Braintree\Subscription::create([
628
- 'paymentMethodToken' => $creditCard->token,
629
- 'planId' => $plan['id'],
630
- 'descriptor' => [
631
- 'name' => '123*123456789012345678',
632
- 'phone' => '3334445555',
633
- 'url' => 'ebay.com'
634
- ]
635
- ]);
636
- $this->assertTrue($result->success);
637
- $subscription = $result->subscription;
638
- $this->assertEquals('123*123456789012345678', $subscription->descriptor->name);
639
- $this->assertEquals('3334445555', $subscription->descriptor->phone);
640
- $this->assertEquals('ebay.com', $subscription->descriptor->url);
641
- $transaction = $subscription->transactions[0];
642
- $this->assertEquals('123*123456789012345678', $transaction->descriptor->name);
643
- $this->assertEquals('3334445555', $transaction->descriptor->phone);
644
- $this->assertEquals('ebay.com', $transaction->descriptor->url);
645
- }
646
-
647
- public function testCreate_withDescriptorValidation()
648
- {
649
- $creditCard = SubscriptionHelper::createCreditCard();
650
- $plan = SubscriptionHelper::addOnDiscountPlan();
651
- $result = Braintree\Subscription::create([
652
- 'paymentMethodToken' => $creditCard->token,
653
- 'planId' => $plan['id'],
654
- 'descriptor' => [
655
- 'name' => 'xxxxxx',
656
- 'phone' => 'xxxx',
657
- 'url' => '12345678901234'
658
- ]
659
- ]);
660
- $this->assertFalse($result->success);
661
- $subscription = $result->subscription;
662
-
663
- $errors = $result->errors->forKey('subscription')->forKey('descriptor')->onAttribute('name');
664
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_NAME_FORMAT_IS_INVALID, $errors[0]->code);
665
-
666
- $errors = $result->errors->forKey('subscription')->forKey('descriptor')->onAttribute('phone');
667
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_PHONE_FORMAT_IS_INVALID, $errors[0]->code);
668
-
669
- $errors = $result->errors->forKey('subscription')->forKey('descriptor')->onAttribute('url');
670
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_URL_FORMAT_IS_INVALID, $errors[0]->code);
671
- }
672
-
673
- public function testCreate_fromPayPalACcount()
674
- {
675
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
676
- $customer = Braintree\Customer::createNoValidate();
677
- $plan = SubscriptionHelper::triallessPlan();
678
- $http = new HttpClientApi(Braintree\Configuration::$global);
679
- $nonce = $http->nonceForPayPalAccount([
680
- 'paypal_account' => [
681
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
682
- 'token' => $paymentMethodToken
683
- ]
684
- ]);
685
-
686
- $paypalResult = Braintree\PaymentMethod::create([
687
- 'customerId' => $customer->id,
688
- 'paymentMethodNonce' => $nonce
689
- ]);
690
-
691
- $subscriptionResult = Braintree\Subscription::create([
692
- 'paymentMethodToken' => $paymentMethodToken,
693
- 'planId' => $plan['id']
694
-
695
- ]);
696
- $this->assertTrue($subscriptionResult->success);
697
- $transaction = $subscriptionResult->subscription->transactions[0];
698
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
699
- }
700
-
701
- public function testCreate_fromPayPalACcountDoesNotWorkWithFutureNonce()
702
- {
703
- $plan = SubscriptionHelper::triallessPlan();
704
- $nonce = Braintree\Test\Nonces::$paypalFuturePayment;
705
-
706
- $subscriptionResult = Braintree\Subscription::create([
707
- 'paymentMethodNonce' => $nonce,
708
- 'planId' => $plan['id']
709
-
710
- ]);
711
- $this->assertFalse($subscriptionResult->success);
712
- $errors = $subscriptionResult->errors->forKey('subscription')->errors;
713
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_PAYMENT_METHOD_NONCE_IS_INVALID, $errors[0]->code);
714
- }
715
-
716
- public function testCreate_fromPayPalACcountDoesNotWorkWithOnetimeNonce()
717
- {
718
- $plan = SubscriptionHelper::triallessPlan();
719
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
720
-
721
- $subscriptionResult = Braintree\Subscription::create([
722
- 'paymentMethodNonce' => $nonce,
723
- 'planId' => $plan['id']
724
-
725
- ]);
726
- $this->assertFalse($subscriptionResult->success);
727
- $errors = $subscriptionResult->errors->forKey('subscription')->errors;
728
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_PAYMENT_METHOD_NONCE_IS_INVALID, $errors[0]->code);
729
- }
730
-
731
- public function testValidationErrors_hasValidationErrorsOnId()
732
- {
733
- $creditCard = SubscriptionHelper::createCreditCard();
734
- $plan = SubscriptionHelper::triallessPlan();
735
- $result = Braintree\Subscription::create([
736
- 'paymentMethodToken' => $creditCard->token,
737
- 'planId' => $plan['id'],
738
- 'id' => 'invalid token'
739
- ]);
740
- $this->assertFalse($result->success);
741
- $errors = $result->errors->forKey('subscription')->onAttribute('id');
742
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_TOKEN_FORMAT_IS_INVALID, $errors[0]->code);
743
- }
744
-
745
- public function testFind()
746
- {
747
- $creditCard = SubscriptionHelper::createCreditCard();
748
- $plan = SubscriptionHelper::triallessPlan();
749
- $result = Braintree\Subscription::create([
750
- 'paymentMethodToken' => $creditCard->token,
751
- 'planId' => $plan['id']
752
- ]);
753
- $this->assertTrue($result->success);
754
- $subscription = Braintree\Subscription::find($result->subscription->id);
755
- $this->assertEquals($result->subscription->id, $subscription->id);
756
- $this->assertEquals($plan['id'], $subscription->planId);
757
- }
758
-
759
- public function testFind_throwsIfNotFound()
760
- {
761
- $this->setExpectedException('Braintree\Exception\NotFound', 'subscription with id does-not-exist not found');
762
- Braintree\Subscription::find('does-not-exist');
763
-
764
- }
765
-
766
- public function testUpdate_whenSuccessful()
767
- {
768
- $subscription = SubscriptionHelper::createSubscription();
769
- $newId = strval(rand());
770
- $newPlan = SubscriptionHelper::trialPlan();
771
- $result = Braintree\Subscription::update($subscription->id, [
772
- 'id' => $newId,
773
- 'price' => '999.99',
774
- 'planId' => $newPlan['id']
775
- ]);
776
- $this->assertTrue($result->success);
777
- $this->assertEquals($newId, $result->subscription->id);
778
- $this->assertEquals($newPlan['id'], $result->subscription->planId);
779
- $this->assertEquals('999.99', $result->subscription->price);
780
- }
781
-
782
- public function testUpdate_doesNotAcceptBadAttributes()
783
- {
784
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: bad');
785
- $result = Braintree\Subscription::update('id', [
786
- 'bad' => 'value'
787
- ]);
788
- }
789
-
790
- public function testUpdate_canUpdateNumberOfBillingCycles()
791
- {
792
- $plan = SubscriptionHelper::triallessPlan();
793
- $subscription = SubscriptionHelper::createSubscription();
794
- $this->assertEquals($plan['numberOfBillingCycles'], $subscription->numberOfBillingCycles);
795
-
796
- $updatedSubscription = Braintree\Subscription::update($subscription->id, [
797
- 'numberOfBillingCycles' => 15
798
- ])->subscription;
799
- $this->assertEquals(15, $updatedSubscription->numberOfBillingCycles);
800
- }
801
-
802
- public function testUpdate_canUpdateNumberOfBillingCyclesToNeverExpire()
803
- {
804
- $plan = SubscriptionHelper::triallessPlan();
805
- $subscription = SubscriptionHelper::createSubscription();
806
- $this->assertEquals($plan['numberOfBillingCycles'], $subscription->numberOfBillingCycles);
807
-
808
- $updatedSubscription = Braintree\Subscription::update($subscription->id, [
809
- 'neverExpires' => true
810
- ])->subscription;
811
- $this->assertNull($updatedSubscription->numberOfBillingCycles);
812
- }
813
-
814
- public function testUpdate_createsTransactionOnProration()
815
- {
816
- $subscription = SubscriptionHelper::createSubscription();
817
- $result = Braintree\Subscription::update($subscription->id, [
818
- 'price' => $subscription->price + 1,
819
- ]);
820
- $this->assertTrue($result->success);
821
- $this->assertEquals(sizeof($subscription->transactions) + 1, sizeof($result->subscription->transactions));
822
- }
823
-
824
- public function testUpdate_createsProratedTransactionWhenFlagIsPassedTrue()
825
- {
826
- $subscription = SubscriptionHelper::createSubscription();
827
- $result = Braintree\Subscription::update($subscription->id, [
828
- 'price' => $subscription->price + 1,
829
- 'options' => ['prorateCharges' => true]
830
- ]);
831
- $this->assertTrue($result->success);
832
- $this->assertEquals(sizeof($subscription->transactions) + 1, sizeof($result->subscription->transactions));
833
- }
834
-
835
- public function testUpdate_createsProratedTransactionWhenFlagIsPassedFalse()
836
- {
837
- $subscription = SubscriptionHelper::createSubscription();
838
- $result = Braintree\Subscription::update($subscription->id, [
839
- 'price' => $subscription->price + 1,
840
- 'options' => ['prorateCharges' => false]
841
- ]);
842
- $this->assertTrue($result->success);
843
- $this->assertEquals(sizeof($subscription->transactions), sizeof($result->subscription->transactions));
844
- }
845
-
846
- public function testUpdate_DoesNotUpdateSubscriptionWhenProrationTransactionFailsAndRevertIsTrue()
847
- {
848
- $subscription = SubscriptionHelper::createSubscription();
849
- $result = Braintree\Subscription::update($subscription->id, [
850
- 'price' => $subscription->price + 2100,
851
- 'options' => ['prorateCharges' => true, 'revertSubscriptionOnProrationFailure' => true]
852
- ]);
853
- $this->assertFalse($result->success);
854
- $this->assertEquals(sizeof($subscription->transactions) + 1, sizeof($result->subscription->transactions));
855
- $this->assertEquals(Braintree\Transaction::PROCESSOR_DECLINED, $result->subscription->transactions[0]->status);
856
- $this->assertEquals("0.00", $result->subscription->balance);
857
- $this->assertEquals($subscription->price, $result->subscription->price);
858
- }
859
-
860
- public function testUpdate_UpdatesSubscriptionWhenProrationTransactionFailsAndRevertIsFalse()
861
- {
862
- $subscription = SubscriptionHelper::createSubscription();
863
- $result = Braintree\Subscription::update($subscription->id, [
864
- 'price' => $subscription->price + 2100,
865
- 'options' => ['prorateCharges' => true, 'revertSubscriptionOnProrationFailure' => false]
866
- ]);
867
- $this->assertTrue($result->success);
868
- $this->assertEquals(sizeof($subscription->transactions) + 1, sizeof($result->subscription->transactions));
869
- $this->assertEquals(Braintree\Transaction::PROCESSOR_DECLINED, $result->subscription->transactions[0]->status);
870
- $this->assertEquals($result->subscription->transactions[0]->amount, $result->subscription->balance);
871
- $this->assertEquals($subscription->price + 2100, $result->subscription->price);
872
- }
873
-
874
- public function testUpdate_invalidSubscriptionId()
875
- {
876
- $this->setExpectedException('Braintree\Exception\NotFound');
877
- Braintree\Subscription::update('does-not-exist', []);
878
- }
879
-
880
- public function testUpdate_validationErrors()
881
- {
882
- $subscription = SubscriptionHelper::createSubscription();
883
- $result = Braintree\Subscription::update($subscription->id, ['price' => '']);
884
- $this->assertFalse($result->success);
885
- $errors = $result->errors->forKey('subscription')->onAttribute('price');
886
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_PRICE_CANNOT_BE_BLANK, $errors[0]->code);
887
- }
888
-
889
- public function testUpdate_cannotUpdateCanceledSubscription()
890
- {
891
- $subscription = SubscriptionHelper::createSubscription();
892
- Braintree\Subscription::cancel($subscription->id);
893
- $result = Braintree\Subscription::update($subscription->id, ['price' => '1.00']);
894
- $this->assertFalse($result->success);
895
- $errors = $result->errors->forKey('subscription')->onAttribute('base');
896
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_CANNOT_EDIT_CANCELED_SUBSCRIPTION, $errors[0]->code);
897
- }
898
-
899
- public function testUpdate_canUpdatePaymentMethodToken()
900
- {
901
- $oldCreditCard = SubscriptionHelper::createCreditCard();
902
- $plan = SubscriptionHelper::triallessPlan();
903
- $subscription = Braintree\Subscription::create([
904
- 'paymentMethodToken' => $oldCreditCard->token,
905
- 'price' => '54.99',
906
- 'planId' => $plan['id']
907
- ])->subscription;
908
-
909
- $newCreditCard = Braintree\CreditCard::createNoValidate([
910
- 'number' => '5105105105105100',
911
- 'expirationDate' => '05/2010',
912
- 'customerId' => $oldCreditCard->customerId
913
- ]);
914
-
915
- $result = Braintree\Subscription::update($subscription->id, [
916
- 'paymentMethodToken' => $newCreditCard->token
917
- ]);
918
- $this->assertTrue($result->success);
919
- $this->assertEquals($newCreditCard->token, $result->subscription->paymentMethodToken);
920
- }
921
-
922
- public function testUpdate_canUpdatePaymentMethodWithPaymentMethodNonce()
923
- {
924
- $oldCreditCard = SubscriptionHelper::createCreditCard();
925
- $plan = SubscriptionHelper::triallessPlan();
926
- $subscription = Braintree\Subscription::create([
927
- 'paymentMethodToken' => $oldCreditCard->token,
928
- 'price' => '54.99',
929
- 'planId' => $plan['id']
930
- ])->subscription;
931
-
932
- $customerId = Braintree\Customer::create()->customer->id;
933
- $http = new HttpClientApi(Braintree\Configuration::$global);
934
- $nonce = $http->nonce_for_new_card([
935
- "creditCard" => [
936
- "number" => "4111111111111111",
937
- "expirationMonth" => "11",
938
- "expirationYear" => "2099"
939
- ],
940
- "customerId" => $oldCreditCard->customerId,
941
- "share" => true
942
- ]);
943
-
944
- $result = Braintree\Subscription::update($subscription->id, [
945
- 'paymentMethodNonce' => $nonce
946
- ]);
947
-
948
- $this->assertTrue($result->success);
949
-
950
- $newCreditCard = Braintree\CreditCard::find($result->subscription->paymentMethodToken);
951
-
952
- $this->assertEquals("1111", $newCreditCard->last4);
953
- $this->assertNotEquals($oldCreditCard->last4, $newCreditCard->last4);
954
- }
955
-
956
- public function testUpdate_canUpdateAddOnsAndDiscounts()
957
- {
958
- $oldCreditCard = SubscriptionHelper::createCreditCard();
959
- $plan = SubscriptionHelper::addOnDiscountPlan();
960
- $subscription = Braintree\Subscription::create([
961
- 'paymentMethodToken' => $oldCreditCard->token,
962
- 'price' => '54.99',
963
- 'planId' => $plan['id']
964
- ])->subscription;
965
-
966
- $result = Braintree\Subscription::update($subscription->id, [
967
- 'addOns' => [
968
- 'update' => [
969
- [
970
- 'amount' => '99.99',
971
- 'existingId' => 'increase_10',
972
- 'quantity' => 99,
973
- 'numberOfBillingCycles' => 99
974
- ],
975
- [
976
- 'amount' => '22.22',
977
- 'existingId' => 'increase_20',
978
- 'quantity' => 22,
979
- 'neverExpires' => true
980
- ]
981
- ],
982
- ],
983
- 'discounts' => [
984
- 'update' => [
985
- [
986
- 'amount' => '33.33',
987
- 'existingId' => 'discount_11',
988
- 'quantity' => 33,
989
- 'numberOfBillingCycles' => 33
990
- ]
991
- ],
992
- ],
993
- ]);
994
- $this->assertTrue($result->success);
995
-
996
- $subscription = $result->subscription;
997
- $this->assertEquals(2, sizeof($subscription->addOns));
998
- $addOns = $subscription->addOns;
999
- SubscriptionHelper::sortModificationsById($addOns);
1000
-
1001
- $this->assertEquals($addOns[0]->id, "increase_10");
1002
- $this->assertEquals($addOns[0]->amount, "99.99");
1003
- $this->assertEquals($addOns[0]->neverExpires, false);
1004
- $this->assertEquals($addOns[0]->numberOfBillingCycles, 99);
1005
- $this->assertEquals($addOns[0]->quantity, 99);
1006
-
1007
- $this->assertEquals($addOns[1]->id, "increase_20");
1008
- $this->assertEquals($addOns[1]->amount, "22.22");
1009
- $this->assertEquals($addOns[1]->neverExpires, true);
1010
- $this->assertEquals($addOns[1]->numberOfBillingCycles, null);
1011
- $this->assertEquals($addOns[1]->quantity, 22);
1012
-
1013
- $this->assertEquals(2, sizeof($subscription->discounts));
1014
- $discounts = $subscription->discounts;
1015
- SubscriptionHelper::sortModificationsById($discounts);
1016
-
1017
- $this->assertEquals($discounts[0]->id, "discount_11");
1018
- $this->assertEquals($discounts[0]->amount, "33.33");
1019
- $this->assertEquals($discounts[0]->neverExpires, false);
1020
- $this->assertEquals($discounts[0]->numberOfBillingCycles, 33);
1021
- $this->assertEquals($discounts[0]->quantity, 33);
1022
- }
1023
-
1024
- public function testUpdate_canAddAndRemoveAddOnsAndDiscounts()
1025
- {
1026
- $oldCreditCard = SubscriptionHelper::createCreditCard();
1027
- $plan = SubscriptionHelper::addOnDiscountPlan();
1028
- $subscription = Braintree\Subscription::create([
1029
- 'paymentMethodToken' => $oldCreditCard->token,
1030
- 'price' => '54.99',
1031
- 'planId' => $plan['id']
1032
- ])->subscription;
1033
-
1034
- $result = Braintree\Subscription::update($subscription->id, [
1035
- 'addOns' => [
1036
- 'add' => [
1037
- [
1038
- 'amount' => '33.33',
1039
- 'inheritedFromId' => 'increase_30',
1040
- 'quantity' => 33,
1041
- 'numberOfBillingCycles' => 33
1042
- ]
1043
- ],
1044
- 'remove' => ['increase_10', 'increase_20']
1045
- ],
1046
- 'discounts' => [
1047
- 'add' => [
1048
- [
1049
- 'inheritedFromId' => 'discount_15',
1050
- ]
1051
- ],
1052
- 'remove' => ['discount_7']
1053
- ],
1054
- ]);
1055
- $this->assertTrue($result->success);
1056
-
1057
- $subscription = $result->subscription;
1058
- $this->assertEquals(1, sizeof($subscription->addOns));
1059
- $addOns = $subscription->addOns;
1060
- SubscriptionHelper::sortModificationsById($addOns);
1061
-
1062
- $this->assertEquals($addOns[0]->id, "increase_30");
1063
- $this->assertEquals($addOns[0]->amount, "33.33");
1064
- $this->assertEquals($addOns[0]->neverExpires, false);
1065
- $this->assertEquals($addOns[0]->numberOfBillingCycles, 33);
1066
- $this->assertEquals($addOns[0]->quantity, 33);
1067
-
1068
- $this->assertEquals(2, sizeof($subscription->discounts));
1069
- $discounts = $subscription->discounts;
1070
- SubscriptionHelper::sortModificationsById($discounts);
1071
-
1072
- $this->assertEquals($discounts[0]->id, "discount_11");
1073
- $this->assertEquals($discounts[1]->id, "discount_15");
1074
- $this->assertEquals($discounts[1]->amount, "15.00");
1075
- $this->assertEquals($discounts[1]->neverExpires, true);
1076
- $this->assertNull($discounts[1]->numberOfBillingCycles);
1077
- $this->assertEquals($discounts[1]->quantity, 1);
1078
- }
1079
-
1080
- public function testUpdate_canReplaceEntireSetOfAddonsAndDiscounts()
1081
- {
1082
- $oldCreditCard = SubscriptionHelper::createCreditCard();
1083
- $plan = SubscriptionHelper::addOnDiscountPlan();
1084
- $subscription = Braintree\Subscription::create([
1085
- 'paymentMethodToken' => $oldCreditCard->token,
1086
- 'price' => '54.99',
1087
- 'planId' => $plan['id']
1088
- ])->subscription;
1089
-
1090
- $result = Braintree\Subscription::update($subscription->id, [
1091
- 'addOns' => [
1092
- 'add' => [
1093
- ['inheritedFromId' => 'increase_30'],
1094
- ['inheritedFromId' => 'increase_20']
1095
- ]
1096
- ],
1097
- 'discounts' => [
1098
- 'add' => [
1099
- ['inheritedFromId' => 'discount_15']
1100
- ]
1101
- ],
1102
- 'options' => ['replaceAllAddOnsAndDiscounts' => true]
1103
- ]);
1104
- $this->assertTrue($result->success);
1105
- $subscription = $result->subscription;
1106
-
1107
- $this->assertEquals(2, sizeof($subscription->addOns));
1108
- $addOns = $subscription->addOns;
1109
- SubscriptionHelper::sortModificationsById($addOns);
1110
-
1111
- $this->assertEquals($addOns[0]->id, "increase_20");
1112
- $this->assertEquals($addOns[1]->id, "increase_30");
1113
-
1114
- $this->assertEquals(1, sizeof($subscription->discounts));
1115
- $discounts = $subscription->discounts;
1116
-
1117
- $this->assertEquals($discounts[0]->id, "discount_15");
1118
- }
1119
-
1120
- public function testUpdate_withDescriptor()
1121
- {
1122
- $creditCard = SubscriptionHelper::createCreditCard();
1123
- $plan = SubscriptionHelper::triallessPlan();
1124
- $subscription = Braintree\Subscription::create([
1125
- 'paymentMethodToken' => $creditCard->token,
1126
- 'planId' => $plan['id'],
1127
- 'descriptor' => [
1128
- 'name' => '123*123456789012345678',
1129
- 'phone' => '3334445555'
1130
- ]
1131
- ])->subscription;
1132
- $result = Braintree\Subscription::update($subscription->id, [
1133
- 'descriptor' => [
1134
- 'name' => '999*9999999',
1135
- 'phone' => '8887776666'
1136
- ]
1137
- ]);
1138
- $updatedSubscription = $result->subscription;
1139
- $this->assertEquals('999*9999999', $updatedSubscription->descriptor->name);
1140
- $this->assertEquals('8887776666', $updatedSubscription->descriptor->phone);
1141
- }
1142
-
1143
- public function testCancel_returnsSuccessIfCanceled()
1144
- {
1145
- $subscription = SubscriptionHelper::createSubscription();
1146
- $result = Braintree\Subscription::cancel($subscription->id);
1147
- $this->assertTrue($result->success);
1148
- $this->assertEquals(Braintree\Subscription::CANCELED, $result->subscription->status);
1149
- }
1150
-
1151
- public function testCancel_throwsErrorIfRecordNotFound()
1152
- {
1153
- $this->setExpectedException('Braintree\Exception\NotFound');
1154
- Braintree\Subscription::cancel('non-existing-id');
1155
- }
1156
-
1157
- public function testCancel_returnsErrorIfCancelingCanceledSubscription()
1158
- {
1159
- $subscription = SubscriptionHelper::createSubscription();
1160
- Braintree\Subscription::cancel($subscription->id);
1161
- $result = Braintree\Subscription::cancel($subscription->id);
1162
- $this->assertFalse($result->success);
1163
- $errors = $result->errors->forKey('subscription')->onAttribute('status');
1164
- $this->assertEquals(Braintree\Error\Codes::SUBSCRIPTION_STATUS_IS_CANCELED, $errors[0]->code);
1165
- }
1166
-
1167
- public function testRetryCharge_WithoutAmount()
1168
- {
1169
- $subscription = SubscriptionHelper::createSubscription();
1170
- $http = new Braintree\Http(Braintree\Configuration::$global);
1171
- $path = Braintree\Configuration::$global->merchantPath() . '/subscriptions/' . $subscription->id . '/make_past_due';
1172
- $http->put($path);
1173
-
1174
- $result = Braintree\Subscription::retryCharge($subscription->id);
1175
-
1176
- $this->assertTrue($result->success);
1177
- $transaction = $result->transaction;
1178
-
1179
- $this->assertEquals($subscription->price, $transaction->amount);
1180
- $this->assertNotNull($transaction->processorAuthorizationCode);
1181
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
1182
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1183
- }
1184
-
1185
- public function testRetryCharge_WithAmount()
1186
- {
1187
- $subscription = SubscriptionHelper::createSubscription();
1188
- $http = new Braintree\Http(Braintree\Configuration::$global);
1189
- $path = Braintree\Configuration::$global->merchantPath() . '/subscriptions/' . $subscription->id . '/make_past_due';
1190
- $http->put($path);
1191
-
1192
- $result = Braintree\Subscription::retryCharge($subscription->id, 1000);
1193
-
1194
- $this->assertTrue($result->success);
1195
- $transaction = $result->transaction;
1196
-
1197
- $this->assertEquals(1000, $transaction->amount);
1198
- $this->assertNotNull($transaction->processorAuthorizationCode);
1199
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
1200
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1201
- }
1202
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/TestTransactionTest.php DELETED
@@ -1,101 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class TestTransactionTest extends Setup
12
- {
13
- public function setUp()
14
- {
15
- Braintree\Configuration::environment('development');
16
- }
17
-
18
- /**
19
- * @after
20
- */
21
- public function tearDownResetBraintreeEnvironment()
22
- {
23
- Braintree\Configuration::environment('development');
24
- }
25
-
26
- /**
27
- * @expectedException Exception\TestOperationPerformedInProduction
28
- */
29
- public function testThrowingExceptionWhenProduction()
30
- {
31
- Braintree\Configuration::environment('production');
32
-
33
- $this->setExpectedException('Braintree\Exception\TestOperationPerformedInProduction');
34
-
35
- $transaction = Braintree\Test\Transaction::settle('foo');
36
- }
37
-
38
- public function testSettle()
39
- {
40
- $transaction = Braintree\Transaction::saleNoValidate([
41
- 'amount' => '100.00',
42
- 'creditCard' => [
43
- 'number' => '5105105105105100',
44
- 'expirationDate' => '05/12'
45
- ],
46
- 'options' => ['submitForSettlement' => true]
47
- ]);
48
-
49
- $transaction = Braintree\Test\Transaction::settle($transaction->id);
50
-
51
- $this->assertEquals('settled', $transaction->status);
52
- }
53
-
54
- public function testSettlementConfirmed()
55
- {
56
- $transaction = Braintree\Transaction::saleNoValidate([
57
- 'amount' => '100.00',
58
- 'creditCard' => [
59
- 'number' => '5105105105105100',
60
- 'expirationDate' => '05/12'
61
- ],
62
- 'options' => ['submitForSettlement' => true]
63
- ]);
64
-
65
- $transaction = Braintree\Test\Transaction::settlementConfirm($transaction->id);
66
-
67
- $this->assertEquals('settlement_confirmed', $transaction->status);
68
- }
69
-
70
- public function testSettlementDeclined()
71
- {
72
- $transaction = Braintree\Transaction::saleNoValidate([
73
- 'amount' => '100.00',
74
- 'creditCard' => [
75
- 'number' => '5105105105105100',
76
- 'expirationDate' => '05/12'
77
- ],
78
- 'options' => ['submitForSettlement' => true]
79
- ]);
80
-
81
- $transaction = Braintree\Test\Transaction::settlementDecline($transaction->id);
82
-
83
- $this->assertEquals('settlement_declined', $transaction->status);
84
- }
85
-
86
- public function testSettlementPending()
87
- {
88
- $transaction = Braintree\Transaction::saleNoValidate([
89
- 'amount' => '100.00',
90
- 'creditCard' => [
91
- 'number' => '5105105105105100',
92
- 'expirationDate' => '05/12'
93
- ],
94
- 'options' => ['submitForSettlement' => true]
95
- ]);
96
-
97
- $transaction = Braintree\Test\Transaction::settlementPending($transaction->id);
98
-
99
- $this->assertEquals('settlement_pending', $transaction->status);
100
- }
101
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/TextNodeTest.php DELETED
@@ -1,147 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class TextNodeTest extends Setup
11
- {
12
- public function testIs()
13
- {
14
- $creditCard = SubscriptionHelper::createCreditCard();
15
- $triallessPlan = SubscriptionHelper::triallessPlan();
16
- $trialPlan = SubscriptionHelper::trialPlan();
17
-
18
- $trialSubscription = Braintree\Subscription::create([
19
- 'paymentMethodToken' => $creditCard->token,
20
- 'planId' => $trialPlan['id'],
21
- 'price' => '5',
22
- ])->subscription;
23
-
24
- $triallessSubscription = Braintree\Subscription::create([
25
- 'paymentMethodToken' => $creditCard->token,
26
- 'planId' => $triallessPlan['id'],
27
- 'price' => '5',
28
- ])->subscription;
29
-
30
- $collection = Braintree\Subscription::search([
31
- Braintree\SubscriptionSearch::planId()->is("integration_trial_plan"),
32
- Braintree\SubscriptionSearch::price()->is('5')
33
- ]);
34
-
35
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
36
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
37
- }
38
-
39
- public function testIsNot()
40
- {
41
- $creditCard = SubscriptionHelper::createCreditCard();
42
- $triallessPlan = SubscriptionHelper::triallessPlan();
43
- $trialPlan = SubscriptionHelper::trialPlan();
44
-
45
- $trialSubscription = Braintree\Subscription::create([
46
- 'paymentMethodToken' => $creditCard->token,
47
- 'planId' => $trialPlan['id'],
48
- 'price' => '6',
49
- ])->subscription;
50
-
51
- $triallessSubscription = Braintree\Subscription::create([
52
- 'paymentMethodToken' => $creditCard->token,
53
- 'planId' => $triallessPlan['id'],
54
- 'price' => '6'
55
- ])->subscription;
56
-
57
- $collection = Braintree\Subscription::search([
58
- Braintree\SubscriptionSearch::planId()->isNot("integration_trialless_plan"),
59
- Braintree\SubscriptionSearch::price()->is("6")
60
- ]);
61
-
62
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
63
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
64
- }
65
-
66
- public function testStartsWith()
67
- {
68
- $creditCard = SubscriptionHelper::createCreditCard();
69
- $triallessPlan = SubscriptionHelper::triallessPlan();
70
- $trialPlan = SubscriptionHelper::trialPlan();
71
-
72
- $trialSubscription = Braintree\Subscription::create([
73
- 'paymentMethodToken' => $creditCard->token,
74
- 'planId' => $trialPlan['id'],
75
- 'price' => '7',
76
- ])->subscription;
77
-
78
- $triallessSubscription = Braintree\Subscription::create([
79
- 'paymentMethodToken' => $creditCard->token,
80
- 'planId' => $triallessPlan['id'],
81
- 'price' => '7',
82
- ])->subscription;
83
-
84
- $collection = Braintree\Subscription::search([
85
- Braintree\SubscriptionSearch::planId()->startsWith("integration_trial_pl"),
86
- Braintree\SubscriptionSearch::price()->is('7')
87
- ]);
88
-
89
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
90
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
91
- }
92
-
93
- public function testEndsWith()
94
- {
95
- $creditCard = SubscriptionHelper::createCreditCard();
96
- $triallessPlan = SubscriptionHelper::triallessPlan();
97
- $trialPlan = SubscriptionHelper::trialPlan();
98
-
99
- $trialSubscription = Braintree\Subscription::create([
100
- 'paymentMethodToken' => $creditCard->token,
101
- 'planId' => $trialPlan['id'],
102
- 'price' => '8'
103
- ])->subscription;
104
-
105
- $triallessSubscription = Braintree\Subscription::create([
106
- 'paymentMethodToken' => $creditCard->token,
107
- 'planId' => $triallessPlan['id'],
108
- 'price' => '8'
109
- ])->subscription;
110
-
111
- $collection = Braintree\Subscription::search([
112
- Braintree\SubscriptionSearch::planId()->endsWith("rial_plan"),
113
- Braintree\SubscriptionSearch::price()->is("8")
114
- ]);
115
-
116
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
117
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
118
- }
119
-
120
-
121
- public function testContains()
122
- {
123
- $creditCard = SubscriptionHelper::createCreditCard();
124
- $triallessPlan = SubscriptionHelper::triallessPlan();
125
- $trialPlan = SubscriptionHelper::trialPlan();
126
-
127
- $trialSubscription = Braintree\Subscription::create([
128
- 'paymentMethodToken' => $creditCard->token,
129
- 'planId' => $trialPlan['id'],
130
- 'price' => '9'
131
- ])->subscription;
132
-
133
- $triallessSubscription = Braintree\Subscription::create([
134
- 'paymentMethodToken' => $creditCard->token,
135
- 'planId' => $triallessPlan['id'],
136
- 'price' => '9'
137
- ])->subscription;
138
-
139
- $collection = Braintree\Subscription::search([
140
- Braintree\SubscriptionSearch::planId()->contains("ration_trial_pl"),
141
- Braintree\SubscriptionSearch::price()->is("9")
142
- ]);
143
-
144
- $this->assertTrue(Test\Helper::includes($collection, $trialSubscription));
145
- $this->assertFalse(Test\Helper::includes($collection, $triallessSubscription));
146
- }
147
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/TransactionAdvancedSearchTest.php DELETED
@@ -1,1573 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use DateTimeZone;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class TransactionAdvancedSearchTest extends Setup
12
- {
13
- public function testNoMatches()
14
- {
15
- $collection = Braintree\Transaction::search([
16
- Braintree\TransactionSearch::billingFirstName()->is('thisnameisnotreal')
17
- ]);
18
-
19
- $this->assertEquals(0, $collection->maximumCount());
20
- }
21
-
22
- public function test_noRequestsWhenIterating()
23
- {
24
- $resultsReturned = false;
25
- $collection = Braintree\Transaction::search([
26
- Braintree\TransactionSearch::billingFirstName()->is('thisnameisnotreal')
27
- ]);
28
-
29
- foreach($collection as $transaction) {
30
- $resultsReturned = true;
31
- break;
32
- }
33
-
34
- $this->assertSame(0, $collection->maximumCount());
35
- $this->assertEquals(false, $resultsReturned);
36
- }
37
-
38
- public function testSearchOnTextFields()
39
- {
40
- $firstName = 'Tim' . rand();
41
- $token = 'creditcard' . rand();
42
- $customerId = 'customer' . rand();
43
-
44
- $transaction = Braintree\Transaction::saleNoValidate([
45
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
46
- 'creditCard' => [
47
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
48
- 'expirationDate' => '05/2012',
49
- 'cardholderName' => 'Tom Smith',
50
- 'token' => $token,
51
- ],
52
- 'billing' => [
53
- 'company' => 'Braintree',
54
- 'countryName' => 'United States of America',
55
- 'extendedAddress' => 'Suite 123',
56
- 'firstName' => $firstName,
57
- 'lastName' => 'Smith',
58
- 'locality' => 'Chicago',
59
- 'postalCode' => '12345',
60
- 'region' => 'IL',
61
- 'streetAddress' => '123 Main St'
62
- ],
63
- 'customer' => [
64
- 'company' => 'Braintree',
65
- 'email' => 'smith@example.com',
66
- 'fax' => '5551231234',
67
- 'firstName' => 'Tom',
68
- 'id' => $customerId,
69
- 'lastName' => 'Smith',
70
- 'phone' => '5551231234',
71
- 'website' => 'http://example.com',
72
- ],
73
- 'options' => [
74
- 'storeInVault' => true
75
- ],
76
- 'orderId' => 'myorder',
77
- 'shipping' => [
78
- 'company' => 'Braintree P.S.',
79
- 'countryName' => 'Mexico',
80
- 'extendedAddress' => 'Apt 456',
81
- 'firstName' => 'Thomas',
82
- 'lastName' => 'Smithy',
83
- 'locality' => 'Braintree',
84
- 'postalCode' => '54321',
85
- 'region' => 'MA',
86
- 'streetAddress' => '456 Road'
87
- ],
88
- ]);
89
-
90
- $search_criteria = [
91
- 'billingCompany' => "Braintree",
92
- 'billingCountryName' => "United States of America",
93
- 'billingExtendedAddress' => "Suite 123",
94
- 'billingFirstName' => $firstName,
95
- 'billingLastName' => "Smith",
96
- 'billingLocality' => "Chicago",
97
- 'billingPostalCode' => "12345",
98
- 'billingRegion' => "IL",
99
- 'billingStreetAddress' => "123 Main St",
100
- 'creditCardCardholderName' => "Tom Smith",
101
- 'creditCardExpirationDate' => "05/2012",
102
- 'creditCardNumber' => Braintree\Test\CreditCardNumbers::$visa,
103
- 'creditCardUniqueIdentifier' => $transaction->creditCardDetails->uniqueNumberIdentifier,
104
- 'customerCompany' => "Braintree",
105
- 'customerEmail' => "smith@example.com",
106
- 'customerFax' => "5551231234",
107
- 'customerFirstName' => "Tom",
108
- 'customerId' => $customerId,
109
- 'customerLastName' => "Smith",
110
- 'customerPhone' => "5551231234",
111
- 'customerWebsite' => "http://example.com",
112
- 'orderId' => "myorder",
113
- 'paymentMethodToken' => $token,
114
- 'paymentInstrumentType' => 'CreditCardDetail',
115
- 'processorAuthorizationCode' => $transaction->processorAuthorizationCode,
116
- 'shippingCompany' => "Braintree P.S.",
117
- 'shippingCountryName' => "Mexico",
118
- 'shippingExtendedAddress' => "Apt 456",
119
- 'shippingFirstName' => "Thomas",
120
- 'shippingLastName' => "Smithy",
121
- 'shippingLocality' => "Braintree",
122
- 'shippingPostalCode' => "54321",
123
- 'shippingRegion' => "MA",
124
- 'shippingStreetAddress' => "456 Road",
125
- 'user' => "integration_user_public_id"
126
- ];
127
-
128
- $query = [Braintree\TransactionSearch::id()->is($transaction->id)];
129
- foreach ($search_criteria AS $criterion => $value) {
130
- $query[] = Braintree\TransactionSearch::$criterion()->is($value);
131
- }
132
-
133
- $collection = Braintree\Transaction::search($query);
134
-
135
- $this->assertEquals(1, $collection->maximumCount());
136
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
137
-
138
- foreach ($search_criteria AS $criterion => $value) {
139
- $collection = Braintree\Transaction::search([
140
- Braintree\TransactionSearch::$criterion()->is($value),
141
- Braintree\TransactionSearch::id()->is($transaction->id)
142
- ]);
143
- $this->assertEquals(1, $collection->maximumCount());
144
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
145
-
146
- $collection = Braintree\Transaction::search([
147
- Braintree\TransactionSearch::$criterion()->is('invalid_attribute'),
148
- Braintree\TransactionSearch::id()->is($transaction->id)
149
- ]);
150
- $this->assertEquals(0, $collection->maximumCount());
151
- }
152
- }
153
-
154
- public function testIs()
155
- {
156
- $transaction = Braintree\Transaction::saleNoValidate([
157
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
158
- 'creditCard' => [
159
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
160
- 'expirationDate' => '05/2012',
161
- 'cardholderName' => 'tom smith'
162
- ]
163
- ]);
164
-
165
- $collection = Braintree\Transaction::search([
166
- Braintree\TransactionSearch::id()->is($transaction->id),
167
- Braintree\TransactionSearch::creditCardCardholderName()->is('tom smith')
168
- ]);
169
-
170
- $this->assertEquals(1, $collection->maximumCount());
171
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
172
-
173
- $collection = Braintree\Transaction::search([
174
- Braintree\TransactionSearch::id()->is($transaction->id),
175
- Braintree\TransactionSearch::creditCardCardholderName()->is('somebody else')
176
- ]);
177
-
178
- $this->assertEquals(0, $collection->maximumCount());
179
- }
180
-
181
- public function testIsNot()
182
- {
183
- $transaction = Braintree\Transaction::saleNoValidate([
184
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
185
- 'creditCard' => [
186
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
187
- 'expirationDate' => '05/2012',
188
- 'cardholderName' => 'tom smith'
189
- ]
190
- ]);
191
-
192
- $collection = Braintree\Transaction::search([
193
- Braintree\TransactionSearch::id()->is($transaction->id),
194
- Braintree\TransactionSearch::creditCardCardholderName()->isNot('somebody else')
195
- ]);
196
-
197
- $this->assertEquals(1, $collection->maximumCount());
198
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
199
-
200
- $collection = Braintree\Transaction::search([
201
- Braintree\TransactionSearch::id()->is($transaction->id),
202
- Braintree\TransactionSearch::creditCardCardholderName()->isNot('tom smith')
203
- ]);
204
-
205
- $this->assertEquals(0, $collection->maximumCount());
206
- }
207
-
208
- public function testEndsWith()
209
- {
210
- $transaction = Braintree\Transaction::saleNoValidate([
211
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
212
- 'creditCard' => [
213
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
214
- 'expirationDate' => '05/2012',
215
- 'cardholderName' => 'tom smith'
216
- ]
217
- ]);
218
-
219
- $collection = Braintree\Transaction::search([
220
- Braintree\TransactionSearch::id()->is($transaction->id),
221
- Braintree\TransactionSearch::creditCardCardholderName()->endsWith('m smith')
222
- ]);
223
-
224
- $this->assertEquals(1, $collection->maximumCount());
225
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
226
-
227
- $collection = Braintree\Transaction::search([
228
- Braintree\TransactionSearch::id()->is($transaction->id),
229
- Braintree\TransactionSearch::creditCardCardholderName()->endsWith('tom s')
230
- ]);
231
-
232
- $this->assertEquals(0, $collection->maximumCount());
233
- }
234
-
235
- public function testStartsWith()
236
- {
237
- $transaction = Braintree\Transaction::saleNoValidate([
238
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
239
- 'creditCard' => [
240
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
241
- 'expirationDate' => '05/2012',
242
- 'cardholderName' => 'tom smith'
243
- ]
244
- ]);
245
-
246
- $collection = Braintree\Transaction::search([
247
- Braintree\TransactionSearch::id()->is($transaction->id),
248
- Braintree\TransactionSearch::creditCardCardholderName()->startsWith('tom s')
249
- ]);
250
-
251
- $this->assertEquals(1, $collection->maximumCount());
252
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
253
-
254
- $collection = Braintree\Transaction::search([
255
- Braintree\TransactionSearch::id()->is($transaction->id),
256
- Braintree\TransactionSearch::creditCardCardholderName()->startsWith('m smith')
257
- ]);
258
-
259
- $this->assertEquals(0, $collection->maximumCount());
260
- }
261
-
262
- public function testContains()
263
- {
264
- $transaction = Braintree\Transaction::saleNoValidate([
265
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
266
- 'creditCard' => [
267
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
268
- 'expirationDate' => '05/2012',
269
- 'cardholderName' => 'tom smith'
270
- ]
271
- ]);
272
-
273
- $collection = Braintree\Transaction::search([
274
- Braintree\TransactionSearch::id()->is($transaction->id),
275
- Braintree\TransactionSearch::creditCardCardholderName()->contains('m sm')
276
- ]);
277
-
278
- $this->assertEquals(1, $collection->maximumCount());
279
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
280
-
281
- $collection = Braintree\Transaction::search([
282
- Braintree\TransactionSearch::id()->is($transaction->id),
283
- Braintree\TransactionSearch::creditCardCardholderName()->contains('something else')
284
- ]);
285
-
286
- $this->assertEquals(0, $collection->maximumCount());
287
- }
288
-
289
- public function test_multipleValueNode_createdUsing()
290
- {
291
- $transaction = Braintree\Transaction::saleNoValidate([
292
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
293
- 'creditCard' => [
294
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
295
- 'expirationDate' => '05/2012'
296
- ]
297
- ]);
298
-
299
- $collection = Braintree\Transaction::search([
300
- Braintree\TransactionSearch::id()->is($transaction->id),
301
- Braintree\TransactionSearch::createdUsing()->is(Braintree\Transaction::FULL_INFORMATION)
302
- ]);
303
- $this->assertEquals(1, $collection->maximumCount());
304
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
305
-
306
- $collection = Braintree\Transaction::search([
307
- Braintree\TransactionSearch::id()->is($transaction->id),
308
- Braintree\TransactionSearch::createdUsing()->in(
309
- [Braintree\Transaction::FULL_INFORMATION, Braintree\Transaction::TOKEN]
310
- )
311
- ]);
312
- $this->assertEquals(1, $collection->maximumCount());
313
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
314
-
315
- $collection = Braintree\Transaction::search([
316
- Braintree\TransactionSearch::id()->is($transaction->id),
317
- Braintree\TransactionSearch::createdUsing()->in([Braintree\Transaction::TOKEN])
318
- ]);
319
- $this->assertEquals(0, $collection->maximumCount());
320
- }
321
-
322
- public function test_multipleValueNode_paymentInstrumentType_is_creditCard()
323
- {
324
- $transaction = Braintree\Transaction::saleNoValidate([
325
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
326
- 'creditCard' => [
327
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
328
- 'expirationDate' => '05/2012'
329
- ]
330
- ]);
331
-
332
- $collection = Braintree\Transaction::search([
333
- Braintree\TransactionSearch::id()->is($transaction->id),
334
- Braintree\TransactionSearch::paymentInstrumentType()->is("CreditCardDetail")
335
- ]);
336
-
337
-
338
- $this->assertEquals($transaction->paymentInstrumentType, Braintree\PaymentInstrumentType::CREDIT_CARD);
339
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
340
- }
341
-
342
- public function test_multipleValueNode_paymentInstrumentType_is_paypal()
343
- {
344
- $transaction = Braintree\Transaction::saleNoValidate([
345
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
346
- 'paymentMethodNonce' => Braintree\Test\Nonces::$paypalOneTimePayment
347
- ]);
348
-
349
- $collection = Braintree\Transaction::search([
350
- Braintree\TransactionSearch::id()->is($transaction->id),
351
- Braintree\TransactionSearch::paymentInstrumentType()->is("PayPalDetail")
352
- ]);
353
-
354
-
355
- $this->assertEquals($transaction->paymentInstrumentType, Braintree\PaymentInstrumentType::PAYPAL_ACCOUNT);
356
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
357
- }
358
-
359
- public function test_multipleValueNode_paymentInstrumentType_is_applepay()
360
- {
361
- $transaction = Braintree\Transaction::saleNoValidate([
362
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
363
- 'paymentMethodNonce' => Braintree\Test\Nonces::$applePayVisa
364
- ]);
365
-
366
- $collection = Braintree\Transaction::search([
367
- Braintree\TransactionSearch::id()->is($transaction->id),
368
- Braintree\TransactionSearch::paymentInstrumentType()->is("ApplePayDetail")
369
- ]);
370
-
371
-
372
- $this->assertEquals($transaction->paymentInstrumentType, Braintree\PaymentInstrumentType::APPLE_PAY_CARD);
373
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
374
- }
375
-
376
- public function test_multipleValueNode_createdUsing_allowedValues()
377
- {
378
- $this->setExpectedException('InvalidArgumentException', 'Invalid argument(s) for created_using: noSuchCreatedUsing');
379
- $collection = Braintree\Transaction::search([
380
- Braintree\TransactionSearch::createdUsing()->is('noSuchCreatedUsing')
381
- ]);
382
- }
383
-
384
- public function test_multipleValueNode_creditCardCustomerLocation()
385
- {
386
- $transaction = Braintree\Transaction::saleNoValidate([
387
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
388
- 'creditCard' => [
389
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
390
- 'expirationDate' => '05/2012'
391
- ]
392
- ]);
393
-
394
- $collection = Braintree\Transaction::search([
395
- Braintree\TransactionSearch::id()->is($transaction->id),
396
- Braintree\TransactionSearch::creditCardCustomerLocation()->is(Braintree\CreditCard::US)
397
- ]);
398
- $this->assertEquals(1, $collection->maximumCount());
399
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
400
-
401
- $collection = Braintree\Transaction::search([
402
- Braintree\TransactionSearch::id()->is($transaction->id),
403
- Braintree\TransactionSearch::creditCardCustomerLocation()->in(
404
- [Braintree\CreditCard::US, Braintree\CreditCard::INTERNATIONAL]
405
- )
406
- ]);
407
- $this->assertEquals(1, $collection->maximumCount());
408
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
409
-
410
- $collection = Braintree\Transaction::search([
411
- Braintree\TransactionSearch::id()->is($transaction->id),
412
- Braintree\TransactionSearch::creditCardCustomerLocation()->in([Braintree\CreditCard::INTERNATIONAL])
413
- ]);
414
- $this->assertEquals(0, $collection->maximumCount());
415
- }
416
-
417
- public function test_multipleValueNode_creditCardCustomerLocation_allowedValues()
418
- {
419
- $this->setExpectedException('InvalidArgumentException', 'Invalid argument(s) for credit_card_customer_location: noSuchLocation');
420
- $collection = Braintree\Transaction::search([
421
- Braintree\TransactionSearch::creditCardCustomerLocation()->is('noSuchLocation')
422
- ]);
423
- }
424
-
425
- public function test_multipleValueNode_merchantAccountId()
426
- {
427
- $transaction = Braintree\Transaction::saleNoValidate([
428
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
429
- 'creditCard' => [
430
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
431
- 'expirationDate' => '05/2012'
432
- ]
433
- ]);
434
-
435
- $collection = Braintree\Transaction::search([
436
- Braintree\TransactionSearch::id()->is($transaction->id),
437
- Braintree\TransactionSearch::merchantAccountId()->is($transaction->merchantAccountId)
438
- ]);
439
- $this->assertEquals(1, $collection->maximumCount());
440
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
441
-
442
- $collection = Braintree\Transaction::search([
443
- Braintree\TransactionSearch::id()->is($transaction->id),
444
- Braintree\TransactionSearch::merchantAccountId()->in(
445
- [$transaction->merchantAccountId, "bogus_merchant_account_id"]
446
- )
447
- ]);
448
- $this->assertEquals(1, $collection->maximumCount());
449
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
450
-
451
- $collection = Braintree\Transaction::search([
452
- Braintree\TransactionSearch::id()->is($transaction->id),
453
- Braintree\TransactionSearch::merchantAccountId()->is('bogus_merchant_account_id')
454
- ]);
455
- $this->assertEquals(0, $collection->maximumCount());
456
- }
457
-
458
- public function test_multipleValueNode_creditCardType()
459
- {
460
- $transaction = Braintree\Transaction::saleNoValidate([
461
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
462
- 'creditCard' => [
463
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
464
- 'expirationDate' => '05/2012'
465
- ]
466
- ]);
467
-
468
- $collection = Braintree\Transaction::search([
469
- Braintree\TransactionSearch::id()->is($transaction->id),
470
- Braintree\TransactionSearch::creditCardCardType()->is($transaction->creditCardDetails->cardType)
471
- ]);
472
- $this->assertEquals(1, $collection->maximumCount());
473
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
474
-
475
- $collection = Braintree\Transaction::search([
476
- Braintree\TransactionSearch::id()->is($transaction->id),
477
- Braintree\TransactionSearch::creditCardCardType()->in(
478
- [$transaction->creditCardDetails->cardType, Braintree\CreditCard::CHINA_UNION_PAY]
479
- )
480
- ]);
481
- $this->assertEquals(1, $collection->maximumCount());
482
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
483
-
484
- $collection = Braintree\Transaction::search([
485
- Braintree\TransactionSearch::id()->is($transaction->id),
486
- Braintree\TransactionSearch::creditCardCardType()->is(Braintree\CreditCard::CHINA_UNION_PAY)
487
- ]);
488
- $this->assertEquals(0, $collection->maximumCount());
489
- }
490
-
491
- public function test_multipleValueNode_creditCardType_allowedValues()
492
- {
493
- $this->setExpectedException('InvalidArgumentException', 'Invalid argument(s) for credit_card_card_type: noSuchCardType');
494
- $collection = Braintree\Transaction::search([
495
- Braintree\TransactionSearch::creditCardCardType()->is('noSuchCardType')
496
- ]);
497
- }
498
-
499
- public function test_multipleValueNode_status()
500
- {
501
- $transaction = Braintree\Transaction::saleNoValidate([
502
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
503
- 'creditCard' => [
504
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
505
- 'expirationDate' => '05/2012'
506
- ]
507
- ]);
508
-
509
- $collection = Braintree\Transaction::search([
510
- Braintree\TransactionSearch::id()->is($transaction->id),
511
- Braintree\TransactionSearch::status()->is($transaction->status)
512
- ]);
513
- $this->assertEquals(1, $collection->maximumCount());
514
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
515
-
516
- $collection = Braintree\Transaction::search([
517
- Braintree\TransactionSearch::id()->is($transaction->id),
518
- Braintree\TransactionSearch::status()->in(
519
- [$transaction->status, Braintree\Transaction::SETTLED]
520
- )
521
- ]);
522
- $this->assertEquals(1, $collection->maximumCount());
523
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
524
-
525
- $collection = Braintree\Transaction::search([
526
- Braintree\TransactionSearch::id()->is($transaction->id),
527
- Braintree\TransactionSearch::status()->is(Braintree\Transaction::SETTLED)
528
- ]);
529
- $this->assertEquals(0, $collection->maximumCount());
530
- }
531
-
532
- public function test_multipleValueNode_status_authorizationExpired()
533
- {
534
- $collection = Braintree\Transaction::search([
535
- Braintree\TransactionSearch::status()->is(Braintree\Transaction::AUTHORIZATION_EXPIRED)
536
- ]);
537
- $this->assertGreaterThan(0, $collection->maximumCount());
538
- $this->assertEquals(Braintree\Transaction::AUTHORIZATION_EXPIRED, $collection->firstItem()->status);
539
- }
540
-
541
- public function test_multipleValueNode_status_allowedValues()
542
- {
543
- $this->setExpectedException('InvalidArgumentException', 'Invalid argument(s) for status: noSuchStatus');
544
- $collection = Braintree\Transaction::search([
545
- Braintree\TransactionSearch::status()->is('noSuchStatus')
546
- ]);
547
- }
548
-
549
- public function test_multipleValueNode_source()
550
- {
551
- $transaction = Braintree\Transaction::saleNoValidate([
552
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
553
- 'creditCard' => [
554
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
555
- 'expirationDate' => '05/2012'
556
- ]
557
- ]);
558
-
559
- $collection = Braintree\Transaction::search([
560
- Braintree\TransactionSearch::id()->is($transaction->id),
561
- Braintree\TransactionSearch::source()->is(Braintree\Transaction::API)
562
- ]);
563
- $this->assertEquals(1, $collection->maximumCount());
564
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
565
-
566
- $collection = Braintree\Transaction::search([
567
- Braintree\TransactionSearch::id()->is($transaction->id),
568
- Braintree\TransactionSearch::source()->in(
569
- [Braintree\Transaction::API, Braintree\Transaction::RECURRING]
570
- )
571
- ]);
572
- $this->assertEquals(1, $collection->maximumCount());
573
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
574
-
575
- $collection = Braintree\Transaction::search([
576
- Braintree\TransactionSearch::id()->is($transaction->id),
577
- Braintree\TransactionSearch::source()->is(Braintree\Transaction::RECURRING)
578
- ]);
579
- $this->assertEquals(0, $collection->maximumCount());
580
- }
581
-
582
- public function test_multipleValueNode_type()
583
- {
584
- $customer = Braintree\Customer::createNoValidate();
585
- $creditCard = Braintree\CreditCard::create([
586
- 'customerId' => $customer->id,
587
- 'cardholderName' => 'Joe Everyman' . rand(),
588
- 'number' => '5105105105105100',
589
- 'expirationDate' => '05/12'
590
- ])->creditCard;
591
-
592
- $sale = Braintree\Transaction::saleNoValidate([
593
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
594
- 'paymentMethodToken' => $creditCard->token,
595
- 'options' => ['submitForSettlement' => true]
596
- ]);
597
- $http = new Braintree\Http(Braintree\Configuration::$global);
598
- $path = Braintree\Configuration::$global->merchantPath() . '/transactions/' . $sale->id . '/settle';
599
- $http->put($path);
600
- $refund = Braintree\Transaction::refund($sale->id)->transaction;
601
-
602
- $credit = Braintree\Transaction::creditNoValidate([
603
- 'amount' => '100.00',
604
- 'paymentMethodToken' => $creditCard->token
605
- ]);
606
-
607
-
608
- $collection = Braintree\Transaction::search([
609
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
610
- Braintree\TransactionSearch::type()->is($sale->type)
611
- ]);
612
- $this->assertEquals(1, $collection->maximumCount());
613
-
614
-
615
- $collection = Braintree\Transaction::search([
616
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
617
- Braintree\TransactionSearch::type()->in(
618
- [$sale->type, $credit->type]
619
- )
620
- ]);
621
- $this->assertEquals(3, $collection->maximumCount());
622
-
623
-
624
- $collection = Braintree\Transaction::search([
625
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
626
- Braintree\TransactionSearch::type()->is($credit->type)
627
- ]);
628
- $this->assertEquals(2, $collection->maximumCount());
629
- }
630
-
631
- public function test_multipleValueNode_type_allowedValues()
632
- {
633
- $this->setExpectedException('InvalidArgumentException', 'Invalid argument(s) for type: noSuchType');
634
- $collection = Braintree\Transaction::search([
635
- Braintree\TransactionSearch::type()->is('noSuchType')
636
- ]);
637
- }
638
-
639
- public function test_multipleValueNode_type_withRefund()
640
- {
641
- $customer = Braintree\Customer::createNoValidate();
642
- $creditCard = Braintree\CreditCard::create([
643
- 'customerId' => $customer->id,
644
- 'cardholderName' => 'Joe Everyman' . rand(),
645
- 'number' => '5105105105105100',
646
- 'expirationDate' => '05/12'
647
- ])->creditCard;
648
-
649
- $sale = Braintree\Transaction::saleNoValidate([
650
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
651
- 'paymentMethodToken' => $creditCard->token,
652
- 'options' => ['submitForSettlement' => true]
653
- ]);
654
- $http = new Braintree\Http(Braintree\Configuration::$global);
655
- $path = Braintree\Configuration::$global->merchantPath() . '/transactions/' . $sale->id . '/settle';
656
- $http->put($path);
657
- $refund = Braintree\Transaction::refund($sale->id)->transaction;
658
-
659
- $credit = Braintree\Transaction::creditNoValidate([
660
- 'amount' => '100.00',
661
- 'paymentMethodToken' => $creditCard->token
662
- ]);
663
-
664
- $collection = Braintree\Transaction::search([
665
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
666
- Braintree\TransactionSearch::type()->is($credit->type),
667
- Braintree\TransactionSearch::refund()->is(True)
668
- ]);
669
- $this->assertEquals(1, $collection->maximumCount());
670
- $this->assertEquals($refund->id, $collection->firstItem()->id);
671
-
672
- $collection = Braintree\Transaction::search([
673
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
674
- Braintree\TransactionSearch::type()->is($credit->type),
675
- Braintree\TransactionSearch::refund()->is(False)
676
- ]);
677
- $this->assertEquals(1, $collection->maximumCount());
678
- $this->assertEquals($credit->id, $collection->firstItem()->id);
679
- }
680
-
681
- public function test_rangeNode_amount()
682
- {
683
- $customer = Braintree\Customer::createNoValidate();
684
- $creditCard = Braintree\CreditCard::create([
685
- 'customerId' => $customer->id,
686
- 'cardholderName' => 'Jane Everywoman' . rand(),
687
- 'number' => '5105105105105100',
688
- 'expirationDate' => '05/12'
689
- ])->creditCard;
690
-
691
- $t_1000 = Braintree\Transaction::saleNoValidate([
692
- 'amount' => '1000.00',
693
- 'paymentMethodToken' => $creditCard->token
694
- ]);
695
-
696
- $t_1500 = Braintree\Transaction::saleNoValidate([
697
- 'amount' => '1500.00',
698
- 'paymentMethodToken' => $creditCard->token
699
- ]);
700
-
701
- $t_1800 = Braintree\Transaction::saleNoValidate([
702
- 'amount' => '1800.00',
703
- 'paymentMethodToken' => $creditCard->token
704
- ]);
705
-
706
- $collection = Braintree\Transaction::search([
707
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
708
- Braintree\TransactionSearch::amount()->greaterThanOrEqualTo('1700')
709
- ]);
710
-
711
- $this->assertEquals(1, $collection->maximumCount());
712
- $this->assertEquals($t_1800->id, $collection->firstItem()->id);
713
-
714
- $collection = Braintree\Transaction::search([
715
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
716
- Braintree\TransactionSearch::amount()->lessThanOrEqualTo('1250')
717
- ]);
718
-
719
- $this->assertEquals(1, $collection->maximumCount());
720
- $this->assertEquals($t_1000->id, $collection->firstItem()->id);
721
-
722
- $collection = Braintree\Transaction::search([
723
- Braintree\TransactionSearch::creditCardCardholderName()->is($creditCard->cardholderName),
724
- Braintree\TransactionSearch::amount()->between('1100', '1600')
725
- ]);
726
-
727
- $this->assertEquals(1, $collection->maximumCount());
728
- $this->assertEquals($t_1500->id, $collection->firstItem()->id);
729
- }
730
-
731
- private function runDisbursementDateSearchTests($disbursementDateString, $comparison)
732
- {
733
- $knownDepositId = "deposittransaction";
734
- $now = new DateTime($disbursementDateString);
735
- $past = clone $now;
736
- $past->modify("-1 hour");
737
- $future = clone $now;
738
- $future->modify("+1 hour");
739
-
740
- $collections = [
741
- 'future' => Braintree\Transaction::search([
742
- Braintree\TransactionSearch::id()->is($knownDepositId),
743
- $comparison($future)
744
- ]),
745
- 'now' => Braintree\Transaction::search([
746
- Braintree\TransactionSearch::id()->is($knownDepositId),
747
- $comparison($now)
748
- ]),
749
- 'past' => Braintree\Transaction::search([
750
- Braintree\TransactionSearch::id()->is($knownDepositId),
751
- $comparison($past)
752
- ])
753
- ];
754
- return $collections;
755
- }
756
-
757
- public function test_rangeNode_disbursementDate_lessThanOrEqualTo()
758
- {
759
- $compareLessThan = function($time) {
760
- return Braintree\TransactionSearch::disbursementDate()->lessThanOrEqualTo($time);
761
- };
762
- $collection = $this->runDisbursementDateSearchTests("2013-04-10", $compareLessThan);
763
-
764
- $this->assertEquals(0, $collection['past']->maximumCount());
765
- $this->assertEquals(1, $collection['now']->maximumCount());
766
- $this->assertEquals(1, $collection['future']->maximumCount());
767
- }
768
-
769
- public function test_rangeNode_disbursementDate_GreaterThanOrEqualTo()
770
- {
771
- $comparison = function($time) {
772
- return Braintree\TransactionSearch::disbursementDate()->GreaterThanOrEqualTo($time);
773
- };
774
- $collection = $this->runDisbursementDateSearchTests("2013-04-11", $comparison);
775
-
776
- $this->assertEquals(1, $collection['past']->maximumCount());
777
- $this->assertEquals(0, $collection['now']->maximumCount());
778
- $this->assertEquals(0, $collection['future']->maximumCount());
779
- }
780
-
781
- public function test_rangeNode_disbursementDate_between()
782
- {
783
- $knownId = "deposittransaction";
784
-
785
- $now = new DateTime("2013-04-10");
786
- $past = clone $now;
787
- $past->modify("-1 day");
788
- $future = clone $now;
789
- $future->modify("+1 day");
790
- $future2 = clone $now;
791
- $future2->modify("+2 days");
792
-
793
- $collection = Braintree\Transaction::search([
794
- Braintree\TransactionSearch::id()->is($knownId),
795
- Braintree\TransactionSearch::disbursementDate()->between($past, $future)
796
- ]);
797
- $this->assertEquals(1, $collection->maximumCount());
798
- $this->assertEquals($knownId, $collection->firstItem()->id);
799
-
800
- $collection = Braintree\Transaction::search([
801
- Braintree\TransactionSearch::id()->is($knownId),
802
- Braintree\TransactionSearch::disbursementDate()->between($now, $future)
803
- ]);
804
- $this->assertEquals(1, $collection->maximumCount());
805
- $this->assertEquals($knownId, $collection->firstItem()->id);
806
-
807
- $collection = Braintree\Transaction::search([
808
- Braintree\TransactionSearch::id()->is($knownId),
809
- Braintree\TransactionSearch::disbursementDate()->between($past, $now)
810
- ]);
811
- $this->assertEquals(1, $collection->maximumCount());
812
- $this->assertEquals($knownId, $collection->firstItem()->id);
813
-
814
- $collection = Braintree\Transaction::search([
815
- Braintree\TransactionSearch::id()->is($knownId),
816
- Braintree\TransactionSearch::disbursementDate()->between($future, $future2)
817
- ]);
818
- $this->assertEquals(0, $collection->maximumCount());
819
- }
820
-
821
- public function test_rangeNode_disbursementDate_is()
822
- {
823
- $knownId = "deposittransaction";
824
-
825
- $now = new DateTime("2013-04-10");
826
- $past = clone $now;
827
- $past->modify("-1 day");
828
- $future = clone $now;
829
- $future->modify("+1 day");
830
- $future2 = clone $now;
831
- $future2->modify("+2 days");
832
-
833
- $collection = Braintree\Transaction::search([
834
- Braintree\TransactionSearch::id()->is($knownId),
835
- Braintree\TransactionSearch::disbursementDate()->is($past)
836
- ]);
837
- $this->assertEquals(0, $collection->maximumCount());
838
-
839
- $collection = Braintree\Transaction::search([
840
- Braintree\TransactionSearch::id()->is($knownId),
841
- Braintree\TransactionSearch::disbursementDate()->is($now)
842
- ]);
843
- $this->assertEquals(1, $collection->maximumCount());
844
- $this->assertEquals($knownId, $collection->firstItem()->id);
845
-
846
- $collection = Braintree\Transaction::search([
847
- Braintree\TransactionSearch::id()->is($knownId),
848
- Braintree\TransactionSearch::disbursementDate()->is($future)
849
- ]);
850
- $this->assertEquals(0, $collection->maximumCount());
851
- }
852
-
853
- private function rundisputeDateSearchTests($disputeDateString, $comparison)
854
- {
855
- $knowndisputedId = "disputedtransaction";
856
- $now = new DateTime($disputeDateString);
857
- $past = clone $now;
858
- $past->modify("-1 hour");
859
- $future = clone $now;
860
- $future->modify("+1 hour");
861
-
862
- $collections = [
863
- 'future' => Braintree\Transaction::search([
864
- Braintree\TransactionSearch::id()->is($knowndisputedId),
865
- $comparison($future)
866
- ]),
867
- 'now' => Braintree\Transaction::search([
868
- Braintree\TransactionSearch::id()->is($knowndisputedId),
869
- $comparison($now)
870
- ]),
871
- 'past' => Braintree\Transaction::search([
872
- Braintree\TransactionSearch::id()->is($knowndisputedId),
873
- $comparison($past)
874
- ])
875
- ];
876
- return $collections;
877
- }
878
-
879
- public function test_rangeNode_disputeDate_lessThanOrEqualTo()
880
- {
881
- $compareLessThan = function($time) {
882
- return Braintree\TransactionSearch::disputeDate()->lessThanOrEqualTo($time);
883
- };
884
- $collection = $this->rundisputeDateSearchTests("2014-03-01", $compareLessThan);
885
-
886
- $this->assertEquals(0, $collection['past']->maximumCount());
887
- $this->assertEquals(1, $collection['now']->maximumCount());
888
- $this->assertEquals(1, $collection['future']->maximumCount());
889
- }
890
-
891
- public function test_rangeNode_disputeDate_GreaterThanOrEqualTo()
892
- {
893
- $comparison = function($time) {
894
- return Braintree\TransactionSearch::disputeDate()->GreaterThanOrEqualTo($time);
895
- };
896
- $collection = $this->rundisputeDateSearchTests("2014-03-01", $comparison);
897
-
898
- $this->assertEquals(1, $collection['past']->maximumCount());
899
- $this->assertEquals(1, $collection['now']->maximumCount());
900
- $this->assertEquals(1, $collection['future']->maximumCount());
901
- }
902
-
903
- public function test_rangeNode_disputeDate_between()
904
- {
905
- $knownId = "disputedtransaction";
906
-
907
- $now = new DateTime("2014-03-01");
908
- $past = clone $now;
909
- $past->modify("-1 day");
910
- $future = clone $now;
911
- $future->modify("+1 day");
912
- $future2 = clone $now;
913
- $future2->modify("+2 days");
914
-
915
- $collection = Braintree\Transaction::search([
916
- Braintree\TransactionSearch::id()->is($knownId),
917
- Braintree\TransactionSearch::disputeDate()->between($past, $future)
918
- ]);
919
- $this->assertEquals(1, $collection->maximumCount());
920
- $this->assertEquals($knownId, $collection->firstItem()->id);
921
-
922
- $collection = Braintree\Transaction::search([
923
- Braintree\TransactionSearch::id()->is($knownId),
924
- Braintree\TransactionSearch::disputeDate()->between($now, $future)
925
- ]);
926
- $this->assertEquals(1, $collection->maximumCount());
927
- $this->assertEquals($knownId, $collection->firstItem()->id);
928
-
929
- $collection = Braintree\Transaction::search([
930
- Braintree\TransactionSearch::id()->is($knownId),
931
- Braintree\TransactionSearch::disputeDate()->between($past, $now)
932
- ]);
933
- $this->assertEquals(1, $collection->maximumCount());
934
- $this->assertEquals($knownId, $collection->firstItem()->id);
935
-
936
- $collection = Braintree\Transaction::search([
937
- Braintree\TransactionSearch::id()->is($knownId),
938
- Braintree\TransactionSearch::disputeDate()->between($future, $future2)
939
- ]);
940
- $this->assertEquals(0, $collection->maximumCount());
941
- }
942
-
943
- public function test_rangeNode_disputeDate_is()
944
- {
945
- $knownId = "disputedtransaction";
946
-
947
- $now = new DateTime("2014-03-01");
948
- $past = clone $now;
949
- $past->modify("-1 day");
950
- $future = clone $now;
951
- $future->modify("+1 day");
952
- $future2 = clone $now;
953
- $future2->modify("+2 days");
954
-
955
- $collection = Braintree\Transaction::search([
956
- Braintree\TransactionSearch::id()->is($knownId),
957
- Braintree\TransactionSearch::disputeDate()->is($past)
958
- ]);
959
- $this->assertEquals(0, $collection->maximumCount());
960
-
961
- $collection = Braintree\Transaction::search([
962
- Braintree\TransactionSearch::id()->is($knownId),
963
- Braintree\TransactionSearch::disputeDate()->is($now)
964
- ]);
965
- $this->assertEquals(1, $collection->maximumCount());
966
- $this->assertEquals($knownId, $collection->firstItem()->id);
967
-
968
- $collection = Braintree\Transaction::search([
969
- Braintree\TransactionSearch::id()->is($knownId),
970
- Braintree\TransactionSearch::disputeDate()->is($future)
971
- ]);
972
- $this->assertEquals(0, $collection->maximumCount());
973
- }
974
-
975
- public function test_rangeNode_createdAt_lessThanOrEqualTo()
976
- {
977
- $transaction = Braintree\Transaction::saleNoValidate([
978
- 'amount' => '1000.00',
979
- 'creditCard' => [
980
- 'cardholderName' => 'Ted Everywoman' . rand(),
981
- 'number' => '5105105105105100',
982
- 'expirationDate' => '05/12'
983
- ]
984
- ]);
985
- $past = clone $transaction->createdAt;
986
- $past->modify("-1 hour");
987
- $now = $transaction->createdAt;
988
- $future = clone $transaction->createdAt;
989
- $future->modify("+1 hour");
990
-
991
- $collection = Braintree\Transaction::search([
992
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
993
- Braintree\TransactionSearch::createdAt()->lessThanOrEqualTo($future)
994
- ]);
995
- $this->assertEquals(1, $collection->maximumCount());
996
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
997
-
998
- $collection = Braintree\Transaction::search([
999
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1000
- Braintree\TransactionSearch::createdAt()->lessThanOrEqualTo($now)
1001
- ]);
1002
- $this->assertEquals(1, $collection->maximumCount());
1003
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1004
-
1005
- $collection = Braintree\Transaction::search([
1006
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1007
- Braintree\TransactionSearch::createdAt()->lessThanOrEqualTo($past)
1008
- ]);
1009
- $this->assertEquals(0, $collection->maximumCount());
1010
- }
1011
-
1012
- public function test_rangeNode_createdAt_GreaterThanOrEqualTo()
1013
- {
1014
- $transaction = Braintree\Transaction::saleNoValidate([
1015
- 'amount' => '1000.00',
1016
- 'creditCard' => [
1017
- 'cardholderName' => 'Ted Everyman' . rand(),
1018
- 'number' => '5105105105105100',
1019
- 'expirationDate' => '05/12'
1020
- ]
1021
- ]);
1022
- $past = clone $transaction->createdAt;
1023
- $past->modify("-1 hour");
1024
- $now = $transaction->createdAt;
1025
- $future = clone $transaction->createdAt;
1026
- $future->modify("+1 hour");
1027
-
1028
- $collection = Braintree\Transaction::search([
1029
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1030
- Braintree\TransactionSearch::createdAt()->GreaterThanOrEqualTo($future)
1031
- ]);
1032
- $this->assertEquals(0, $collection->maximumCount());
1033
-
1034
- $collection = Braintree\Transaction::search([
1035
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1036
- Braintree\TransactionSearch::createdAt()->GreaterThanOrEqualTo($now)
1037
- ]);
1038
- $this->assertEquals(1, $collection->maximumCount());
1039
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1040
-
1041
- $collection = Braintree\Transaction::search([
1042
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1043
- Braintree\TransactionSearch::createdAt()->GreaterThanOrEqualTo($past)
1044
- ]);
1045
- $this->assertEquals(1, $collection->maximumCount());
1046
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1047
- }
1048
-
1049
-
1050
-
1051
- public function test_rangeNode_createdAt_between()
1052
- {
1053
- $transaction = Braintree\Transaction::saleNoValidate([
1054
- 'amount' => '1000.00',
1055
- 'creditCard' => [
1056
- 'cardholderName' => 'Ted Everyman' . rand(),
1057
- 'number' => '5105105105105100',
1058
- 'expirationDate' => '05/12'
1059
- ]
1060
- ]);
1061
- $past = clone $transaction->createdAt;
1062
- $past->modify("-1 hour");
1063
- $now = $transaction->createdAt;
1064
- $future = clone $transaction->createdAt;
1065
- $future->modify("+1 hour");
1066
- $future2 = clone $transaction->createdAt;
1067
- $future2->modify("+1 day");
1068
-
1069
- $collection = Braintree\Transaction::search([
1070
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1071
- Braintree\TransactionSearch::createdAt()->between($past, $future)
1072
- ]);
1073
- $this->assertEquals(1, $collection->maximumCount());
1074
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1075
-
1076
- $collection = Braintree\Transaction::search([
1077
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1078
- Braintree\TransactionSearch::createdAt()->between($now, $future)
1079
- ]);
1080
- $this->assertEquals(1, $collection->maximumCount());
1081
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1082
-
1083
- $collection = Braintree\Transaction::search([
1084
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1085
- Braintree\TransactionSearch::createdAt()->between($past, $now)
1086
- ]);
1087
- $this->assertEquals(1, $collection->maximumCount());
1088
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1089
-
1090
- $collection = Braintree\Transaction::search([
1091
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1092
- Braintree\TransactionSearch::createdAt()->between($future, $future2)
1093
- ]);
1094
- $this->assertEquals(0, $collection->maximumCount());
1095
- }
1096
-
1097
- public function test_rangeNode_createdAt_is()
1098
- {
1099
- $transaction = Braintree\Transaction::saleNoValidate([
1100
- 'amount' => '1000.00',
1101
- 'creditCard' => [
1102
- 'cardholderName' => 'Ted Everyman' . rand(),
1103
- 'number' => '5105105105105100',
1104
- 'expirationDate' => '05/12'
1105
- ]
1106
- ]);
1107
- $past = clone $transaction->createdAt;
1108
- $past->modify("-1 hour");
1109
- $now = $transaction->createdAt;
1110
- $future = clone $transaction->createdAt;
1111
- $future->modify("+1 hour");
1112
-
1113
- $collection = Braintree\Transaction::search([
1114
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1115
- Braintree\TransactionSearch::createdAt()->is($future)
1116
- ]);
1117
- $this->assertEquals(0, $collection->maximumCount());
1118
-
1119
- $collection = Braintree\Transaction::search([
1120
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1121
- Braintree\TransactionSearch::createdAt()->is($now)
1122
- ]);
1123
- $this->assertEquals(1, $collection->maximumCount());
1124
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1125
-
1126
- $collection = Braintree\Transaction::search([
1127
- Braintree\TransactionSearch::creditCardCardholderName()->is($transaction->creditCardDetails->cardholderName),
1128
- Braintree\TransactionSearch::createdAt()->is($past)
1129
- ]);
1130
- $this->assertEquals(0, $collection->maximumCount());
1131
- }
1132
-
1133
- public function test_rangeNode_createdAt_convertLocalToUTC()
1134
- {
1135
- $transaction = Braintree\Transaction::saleNoValidate([
1136
- 'amount' => '1000.00',
1137
- 'creditCard' => [
1138
- 'cardholderName' => 'Pingu Penguin' . rand(),
1139
- 'number' => '5105105105105100',
1140
- 'expirationDate' => '05/12'
1141
- ]
1142
- ]);
1143
-
1144
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("US/Pacific"));
1145
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("US/Pacific"));
1146
-
1147
- $collection = Braintree\Transaction::search([
1148
- Braintree\TransactionSearch::id()->is($transaction->id),
1149
- Braintree\TransactionSearch::createdAt()->between($ten_min_ago, $ten_min_from_now)
1150
- ]);
1151
-
1152
- $this->assertEquals(1, $collection->maximumCount());
1153
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1154
- }
1155
-
1156
- public function test_rangeNode_createdAt_handlesUTCDateTimes()
1157
- {
1158
- $transaction = Braintree\Transaction::saleNoValidate([
1159
- 'amount' => '1000.00',
1160
- 'creditCard' => [
1161
- 'cardholderName' => 'Pingu Penguin' . rand(),
1162
- 'number' => '5105105105105100',
1163
- 'expirationDate' => '05/12'
1164
- ]
1165
- ]);
1166
-
1167
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1168
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1169
-
1170
- $collection = Braintree\Transaction::search([
1171
- Braintree\TransactionSearch::id()->is($transaction->id),
1172
- Braintree\TransactionSearch::createdAt()->between($ten_min_ago, $ten_min_from_now)
1173
- ]);
1174
-
1175
- $this->assertEquals(1, $collection->maximumCount());
1176
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1177
- }
1178
-
1179
- public function test_rangeNode_authorizationExpiredAt()
1180
- {
1181
- $two_days_ago = date_create("now -2 days", new DateTimeZone("UTC"));
1182
- $yesterday = date_create("now -1 day", new DateTimeZone("UTC"));
1183
- $tomorrow = date_create("now +1 day", new DateTimeZone("UTC"));
1184
-
1185
- $collection = Braintree\Transaction::search([
1186
- Braintree\TransactionSearch::authorizationExpiredAt()->between($two_days_ago, $yesterday)
1187
- ]);
1188
-
1189
- $this->assertEquals(0, $collection->maximumCount());
1190
-
1191
- $collection = Braintree\Transaction::search([
1192
- Braintree\TransactionSearch::authorizationExpiredAt()->between($yesterday, $tomorrow)
1193
- ]);
1194
-
1195
- $this->assertGreaterThan(0, $collection->maximumCount());
1196
- $this->assertEquals(Braintree\Transaction::AUTHORIZATION_EXPIRED, $collection->firstItem()->status);
1197
- }
1198
-
1199
- public function test_rangeNode_authorizedAt()
1200
- {
1201
- $transaction = Braintree\Transaction::saleNoValidate([
1202
- 'amount' => '1000.00',
1203
- 'creditCard' => [
1204
- 'number' => '4111111111111111',
1205
- 'expirationDate' => '05/12'
1206
- ]
1207
- ]);
1208
-
1209
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1210
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1211
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1212
-
1213
- $collection = Braintree\Transaction::search([
1214
- Braintree\TransactionSearch::id()->is($transaction->id),
1215
- Braintree\TransactionSearch::authorizedAt()->between($twenty_min_ago, $ten_min_ago)
1216
- ]);
1217
-
1218
- $this->assertEquals(0, $collection->maximumCount());
1219
-
1220
- $collection = Braintree\Transaction::search([
1221
- Braintree\TransactionSearch::id()->is($transaction->id),
1222
- Braintree\TransactionSearch::authorizedAt()->between($ten_min_ago, $ten_min_from_now)
1223
- ]);
1224
-
1225
- $this->assertEquals(1, $collection->maximumCount());
1226
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1227
- }
1228
-
1229
- public function test_rangeNode_failedAt()
1230
- {
1231
- $transaction = Braintree\Transaction::sale([
1232
- 'amount' => '3000.00',
1233
- 'creditCard' => [
1234
- 'number' => '4111111111111111',
1235
- 'expirationDate' => '05/12'
1236
- ]
1237
- ])->transaction;
1238
-
1239
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1240
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1241
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1242
-
1243
- $collection = Braintree\Transaction::search([
1244
- Braintree\TransactionSearch::id()->is($transaction->id),
1245
- Braintree\TransactionSearch::failedAt()->between($twenty_min_ago, $ten_min_ago)
1246
- ]);
1247
-
1248
- $this->assertEquals(0, $collection->maximumCount());
1249
-
1250
- $collection = Braintree\Transaction::search([
1251
- Braintree\TransactionSearch::id()->is($transaction->id),
1252
- Braintree\TransactionSearch::failedAt()->between($ten_min_ago, $ten_min_from_now)
1253
- ]);
1254
-
1255
- $this->assertEquals(1, $collection->maximumCount());
1256
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1257
- }
1258
-
1259
- public function test_rangeNode_gatewayRejectedAt()
1260
- {
1261
- $old_merchant_id = Braintree\Configuration::merchantId();
1262
- $old_public_key = Braintree\Configuration::publicKey();
1263
- $old_private_key = Braintree\Configuration::privateKey();
1264
-
1265
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
1266
- Braintree\Configuration::publicKey('processing_rules_public_key');
1267
- Braintree\Configuration::privateKey('processing_rules_private_key');
1268
-
1269
- $transaction = Braintree\Transaction::sale([
1270
- 'amount' => '1000.00',
1271
- 'creditCard' => [
1272
- 'number' => '4111111111111111',
1273
- 'expirationDate' => '05/12',
1274
- 'cvv' => '200'
1275
- ]
1276
- ])->transaction;
1277
-
1278
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1279
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1280
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1281
-
1282
- $collection = Braintree\Transaction::search([
1283
- Braintree\TransactionSearch::id()->is($transaction->id),
1284
- Braintree\TransactionSearch::gatewayRejectedAt()->between($twenty_min_ago, $ten_min_ago)
1285
- ]);
1286
-
1287
- $firstCount = $collection->maximumCount();
1288
-
1289
- $collection = Braintree\Transaction::search([
1290
- Braintree\TransactionSearch::id()->is($transaction->id),
1291
- Braintree\TransactionSearch::gatewayRejectedAt()->between($ten_min_ago, $ten_min_from_now)
1292
- ]);
1293
-
1294
- $secondCount = $collection->maximumCount();
1295
- $firstId = $collection->firstItem()->id;
1296
-
1297
- Braintree\Configuration::merchantId($old_merchant_id);
1298
- Braintree\Configuration::publicKey($old_public_key);
1299
- Braintree\Configuration::privateKey($old_private_key);
1300
-
1301
- $this->assertEquals(0, $firstCount);
1302
- $this->assertEquals(1, $secondCount);
1303
- $this->assertEquals($transaction->id, $firstId);
1304
- }
1305
-
1306
- public function test_rangeNode_processorDeclinedAt()
1307
- {
1308
- $transaction = Braintree\Transaction::sale([
1309
- 'amount' => '2000.00',
1310
- 'creditCard' => [
1311
- 'number' => '4111111111111111',
1312
- 'expirationDate' => '05/12'
1313
- ]
1314
- ])->transaction;
1315
-
1316
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1317
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1318
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1319
-
1320
- $collection = Braintree\Transaction::search([
1321
- Braintree\TransactionSearch::id()->is($transaction->id),
1322
- Braintree\TransactionSearch::processorDeclinedAt()->between($twenty_min_ago, $ten_min_ago)
1323
- ]);
1324
-
1325
- $this->assertEquals(0, $collection->maximumCount());
1326
-
1327
- $collection = Braintree\Transaction::search([
1328
- Braintree\TransactionSearch::id()->is($transaction->id),
1329
- Braintree\TransactionSearch::processorDeclinedAt()->between($ten_min_ago, $ten_min_from_now)
1330
- ]);
1331
-
1332
- $this->assertEquals(1, $collection->maximumCount());
1333
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1334
- }
1335
-
1336
- public function test_rangeNode_settledAt()
1337
- {
1338
- $transaction = Braintree\Transaction::saleNoValidate([
1339
- 'amount' => '1000.00',
1340
- 'creditCard' => [
1341
- 'number' => '4111111111111111',
1342
- 'expirationDate' => '05/12'
1343
- ],
1344
- 'options' => [
1345
- 'submitForSettlement' => true
1346
- ]
1347
- ]);
1348
-
1349
- $http = new Braintree\Http(Braintree\Configuration::$global);
1350
- $path = Braintree\Configuration::$global->merchantPath() . '/transactions/' . $transaction->id . '/settle';
1351
- $http->put($path);
1352
- $transaction = Braintree\Transaction::find($transaction->id);
1353
-
1354
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1355
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1356
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1357
-
1358
- $collection = Braintree\Transaction::search([
1359
- Braintree\TransactionSearch::id()->is($transaction->id),
1360
- Braintree\TransactionSearch::settledAt()->between($twenty_min_ago, $ten_min_ago)
1361
- ]);
1362
-
1363
- $this->assertEquals(0, $collection->maximumCount());
1364
-
1365
- $collection = Braintree\Transaction::search([
1366
- Braintree\TransactionSearch::id()->is($transaction->id),
1367
- Braintree\TransactionSearch::settledAt()->between($ten_min_ago, $ten_min_from_now)
1368
- ]);
1369
-
1370
- $this->assertEquals(1, $collection->maximumCount());
1371
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1372
- }
1373
-
1374
- public function test_rangeNode_submittedForSettlementAt()
1375
- {
1376
- $transaction = Braintree\Transaction::sale([
1377
- 'amount' => '1000.00',
1378
- 'creditCard' => [
1379
- 'number' => '4111111111111111',
1380
- 'expirationDate' => '05/12'
1381
- ],
1382
- 'options' => [
1383
- 'submitForSettlement' => true
1384
- ]
1385
- ])->transaction;
1386
-
1387
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1388
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1389
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1390
-
1391
- $collection = Braintree\Transaction::search([
1392
- Braintree\TransactionSearch::id()->is($transaction->id),
1393
- Braintree\TransactionSearch::submittedForSettlementAt()->between($twenty_min_ago, $ten_min_ago)
1394
- ]);
1395
-
1396
- $this->assertEquals(0, $collection->maximumCount());
1397
-
1398
- $collection = Braintree\Transaction::search([
1399
- Braintree\TransactionSearch::id()->is($transaction->id),
1400
- Braintree\TransactionSearch::submittedForSettlementAt()->between($ten_min_ago, $ten_min_from_now)
1401
- ]);
1402
-
1403
- $this->assertEquals(1, $collection->maximumCount());
1404
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1405
- }
1406
-
1407
- public function test_rangeNode_voidedAt()
1408
- {
1409
- $transaction = Braintree\Transaction::saleNoValidate([
1410
- 'amount' => '1000.00',
1411
- 'creditCard' => [
1412
- 'number' => '4111111111111111',
1413
- 'expirationDate' => '05/12'
1414
- ]
1415
- ]);
1416
-
1417
- $transaction = Braintree\Transaction::void($transaction->id)->transaction;
1418
-
1419
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1420
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1421
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1422
-
1423
- $collection = Braintree\Transaction::search([
1424
- Braintree\TransactionSearch::id()->is($transaction->id),
1425
- Braintree\TransactionSearch::voidedAt()->between($twenty_min_ago, $ten_min_ago)
1426
- ]);
1427
-
1428
- $this->assertEquals(0, $collection->maximumCount());
1429
-
1430
- $collection = Braintree\Transaction::search([
1431
- Braintree\TransactionSearch::id()->is($transaction->id),
1432
- Braintree\TransactionSearch::voidedAt()->between($ten_min_ago, $ten_min_from_now)
1433
- ]);
1434
-
1435
- $this->assertEquals(1, $collection->maximumCount());
1436
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1437
- }
1438
-
1439
- public function test_rangeNode_canSearchOnMultipleStatuses()
1440
- {
1441
- $transaction = Braintree\Transaction::sale([
1442
- 'amount' => '1000.00',
1443
- 'creditCard' => [
1444
- 'number' => '4111111111111111',
1445
- 'expirationDate' => '05/12'
1446
- ],
1447
- 'options' => [
1448
- 'submitForSettlement' => true
1449
- ]
1450
- ])->transaction;
1451
-
1452
- $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC"));
1453
- $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC"));
1454
- $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC"));
1455
-
1456
- $collection = Braintree\Transaction::search([
1457
- Braintree\TransactionSearch::id()->is($transaction->id),
1458
- Braintree\TransactionSearch::authorizedAt()->between($twenty_min_ago, $ten_min_ago),
1459
- Braintree\TransactionSearch::submittedForSettlementAt()->between($twenty_min_ago, $ten_min_ago)
1460
- ]);
1461
-
1462
- $this->assertEquals(0, $collection->maximumCount());
1463
-
1464
- $collection = Braintree\Transaction::search([
1465
- Braintree\TransactionSearch::id()->is($transaction->id),
1466
- Braintree\TransactionSearch::authorizedAt()->between($ten_min_ago, $ten_min_from_now),
1467
- Braintree\TransactionSearch::submittedForSettlementAt()->between($ten_min_ago, $ten_min_from_now)
1468
- ]);
1469
-
1470
- $this->assertEquals(1, $collection->maximumCount());
1471
- $this->assertEquals($transaction->id, $collection->firstItem()->id);
1472
- }
1473
-
1474
- public function test_advancedSearchGivesIterableResult()
1475
- {
1476
- $collection = Braintree\Transaction::search([
1477
- Braintree\TransactionSearch::creditCardNumber()->startsWith("411111")
1478
- ]);
1479
- $this->assertTrue($collection->maximumCount() > 100);
1480
-
1481
- $arr = [];
1482
- foreach($collection as $transaction) {
1483
- array_push($arr, $transaction->id);
1484
- }
1485
- $unique_transaction_ids = array_unique(array_values($arr));
1486
- $this->assertEquals($collection->maximumCount(), count($unique_transaction_ids));
1487
- }
1488
-
1489
- public function test_handles_search_timeout()
1490
- {
1491
- $this->setExpectedException('Braintree\Exception\DownForMaintenance');
1492
- $collection = Braintree\Transaction::search([
1493
- Braintree\TransactionSearch::amount()->is('-5')
1494
- ]);
1495
- }
1496
-
1497
- public function testHandlesPayPalAccounts()
1498
- {
1499
- $http = new HttpClientApi(Braintree\Configuration::$global);
1500
- $nonce = $http->nonceForPayPalAccount([
1501
- 'paypal_account' => [
1502
- 'access_token' => 'PAYPAL_ACCESS_TOKEN'
1503
- ]
1504
- ]);
1505
-
1506
- $result = Braintree\Transaction::sale([
1507
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
1508
- 'paymentMethodNonce' => $nonce
1509
- ]);
1510
-
1511
- $this->assertTrue($result->success);
1512
- $paypalDetails = $result->transaction->paypalDetails;
1513
-
1514
- $collection = Braintree\Transaction::search([
1515
- Braintree\TransactionSearch::paypalPaymentId()->is($paypalDetails->paymentId),
1516
- Braintree\TransactionSearch::paypalAuthorizationId()->is($paypalDetails->authorizationId),
1517
- Braintree\TransactionSearch::paypalPayerEmail()->is($paypalDetails->payerEmail)
1518
- ]);
1519
-
1520
- $this->assertEquals(1, $collection->maximumCount());
1521
- $this->assertEquals($result->transaction->id, $collection->firstItem()->id);
1522
- }
1523
-
1524
- public function testHandlesEuropeBankAccounts()
1525
- {
1526
- $gateway = new Braintree\Gateway([
1527
- 'environment' => 'development',
1528
- 'merchantId' => 'altpay_merchant',
1529
- 'publicKey' => 'altpay_merchant_public_key',
1530
- 'privateKey' => 'altpay_merchant_private_key'
1531
- ]);
1532
-
1533
- $result = $gateway->customer()->create();
1534
- $this->assertTrue($result->success);
1535
- $customer = $result->customer;
1536
- $clientApi = new HttpClientApi($gateway->config);
1537
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
1538
- "customerId" => $customer->id,
1539
- "sepa_mandate" => [
1540
- "locale" => "de-DE",
1541
- "bic" => "DEUTDEFF",
1542
- "iban" => "DE89370400440532013000",
1543
- "accountHolderName" => "Bob Holder",
1544
- "billingAddress" => [
1545
- "streetAddress" => "123 Currywurst Way",
1546
- "extendedAddress" => "Lager Suite",
1547
- "firstName" => "Wilhelm",
1548
- "lastName" => "Dix",
1549
- "locality" => "Frankfurt",
1550
- "postalCode" => "60001",
1551
- "countryCodeAlpha2" => "DE",
1552
- "region" => "Hesse"
1553
- ]
1554
- ]
1555
- ]);
1556
- $transactionResult = $gateway->transaction()->sale([
1557
- "customerId" => $customer->id,
1558
- "paymentMethodNonce" => $nonce,
1559
- "merchantAccountId" => "fake_sepa_ma",
1560
- "amount" => 100
1561
- ]);
1562
-
1563
- $this->assertTrue($transactionResult->success);
1564
-
1565
- $collection = $gateway->transaction()->search([
1566
- Braintree\TransactionSearch::customerId()->is($customer->id),
1567
- Braintree\TransactionSearch::europeBankAccountIban()->is("DE89370400440532013000")
1568
- ]);
1569
-
1570
- $this->assertEquals(1, $collection->maximumCount());
1571
- $this->assertEquals($transactionResult->transaction->id, $collection->firstItem()->id);
1572
- }
1573
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/TransactionTest.php DELETED
@@ -1,3629 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test;
8
- use Test\Setup;
9
- use Test\Braintree\CreditCardNumbers\CardTypeIndicators;
10
- use Braintree;
11
-
12
- class TransactionTest extends Setup
13
- {
14
- public function testCloneTransaction()
15
- {
16
- $result = Braintree\Transaction::sale([
17
- 'amount' => '100.00',
18
- 'orderId' => '123',
19
- 'creditCard' => [
20
- 'number' => '5105105105105100',
21
- 'expirationDate' => '05/2011',
22
- ],
23
- 'customer' => [
24
- 'firstName' => 'Dan',
25
- ],
26
- 'billing' => [
27
- 'firstName' => 'Carl',
28
- ],
29
- 'shipping' => [
30
- 'firstName' => 'Andrew',
31
- ]
32
- ]);
33
- $this->assertTrue($result->success);
34
- $transaction = $result->transaction;
35
-
36
- $cloneResult = Braintree\Transaction::cloneTransaction(
37
- $transaction->id,
38
- [
39
- 'amount' => '123.45',
40
- 'channel' => 'MyShoppingCartProvider',
41
- 'options' => ['submitForSettlement' => false]
42
- ]
43
- );
44
- Test\Helper::assertPrintable($cloneResult);
45
- $this->assertTrue($cloneResult->success);
46
- $cloneTransaction = $cloneResult->transaction;
47
- $this->assertEquals('Dan', $cloneTransaction->customerDetails->firstName);
48
- $this->assertEquals('Carl', $cloneTransaction->billingDetails->firstName);
49
- $this->assertEquals('Andrew', $cloneTransaction->shippingDetails->firstName);
50
- $this->assertEquals('510510******5100', $cloneTransaction->creditCardDetails->maskedNumber);
51
- $this->assertEquals('authorized', $cloneTransaction->status);
52
- $this->assertEquals('123.45', $cloneTransaction->amount);
53
- $this->assertEquals('MyShoppingCartProvider', $cloneTransaction->channel);
54
- }
55
-
56
- public function testCreateTransactionUsingNonce()
57
- {
58
- $http = new HttpClientApi(Braintree\Configuration::$global);
59
- $nonce = $http->nonce_for_new_card([
60
- "creditCard" => [
61
- "number" => "4111111111111111",
62
- "expirationMonth" => "11",
63
- "expirationYear" => "2099"
64
- ],
65
- "share" => true
66
- ]);
67
-
68
- $result = Braintree\Transaction::sale([
69
- 'amount' => '47.00',
70
- 'paymentMethodNonce' => $nonce
71
- ]);
72
-
73
- $this->assertTrue($result->success);
74
- $transaction = $result->transaction;
75
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
76
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
77
- $this->assertEquals('47.00', $transaction->amount);
78
- }
79
-
80
- public function testGatewayCreateTransactionUsingNonce()
81
- {
82
- $http = new HttpClientApi(Braintree\Configuration::$global);
83
- $nonce = $http->nonce_for_new_card([
84
- "creditCard" => [
85
- "number" => "4111111111111111",
86
- "expirationMonth" => "11",
87
- "expirationYear" => "2099"
88
- ],
89
- "share" => true
90
- ]);
91
-
92
- $gateway = new Braintree\Gateway([
93
- 'environment' => 'development',
94
- 'merchantId' => 'integration_merchant_id',
95
- 'publicKey' => 'integration_public_key',
96
- 'privateKey' => 'integration_private_key'
97
- ]);
98
- $result = $gateway->transaction()->sale([
99
- 'amount' => '47.00',
100
- 'paymentMethodNonce' => $nonce
101
- ]);
102
-
103
- $this->assertTrue($result->success);
104
- $transaction = $result->transaction;
105
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
106
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
107
- $this->assertEquals('47.00', $transaction->amount);
108
- }
109
-
110
- public function testCreateTransactionUsingEuropeBankAccountNonce()
111
- {
112
- $gateway = new Braintree\Gateway([
113
- 'environment' => 'development',
114
- 'merchantId' => 'altpay_merchant',
115
- 'publicKey' => 'altpay_merchant_public_key',
116
- 'privateKey' => 'altpay_merchant_private_key'
117
- ]);
118
-
119
- $result = $gateway->customer()->create();
120
- $this->assertTrue($result->success);
121
- $customer = $result->customer;
122
- $clientApi = new HttpClientApi($gateway->config);
123
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
124
- "customerId" => $customer->id,
125
- "sepa_mandate" => [
126
- "locale" => "de-DE",
127
- "bic" => "DEUTDEFF",
128
- "iban" => "DE89370400440532013000",
129
- "accountHolderName" => "Bob Holder",
130
- "billingAddress" => [
131
- "streetAddress" => "123 Currywurst Way",
132
- "extendedAddress" => "Lager Suite",
133
- "firstName" => "Wilhelm",
134
- "lastName" => "Dix",
135
- "locality" => "Frankfurt",
136
- "postalCode" => "60001",
137
- "countryCodeAlpha2" => "DE",
138
- "region" => "Hesse"
139
- ]
140
- ]
141
- ]);
142
-
143
- $result = $gateway->transaction()->sale([
144
- 'amount' => '47.00',
145
- 'merchantAccountId' => 'fake_sepa_ma',
146
- 'paymentMethodNonce' => $nonce
147
- ]);
148
-
149
- $this->assertTrue($result->success);
150
- $transaction = $result->transaction;
151
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
152
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
153
- $this->assertEquals('47.00', $transaction->amount);
154
- $this->assertEquals('DEUTDEFF', $transaction->europeBankAccount->bic);
155
- }
156
-
157
- public function testSettleAltPayTransaction()
158
- {
159
- $gateway = new Braintree\Gateway([
160
- 'environment' => 'development',
161
- 'merchantId' => 'altpay_merchant',
162
- 'publicKey' => 'altpay_merchant_public_key',
163
- 'privateKey' => 'altpay_merchant_private_key'
164
- ]);
165
-
166
- $result = $gateway->customer()->create();
167
- $this->assertTrue($result->success);
168
- $customer = $result->customer;
169
- $clientApi = new HttpClientApi($gateway->config);
170
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
171
- "customerId" => $customer->id,
172
- "sepa_mandate" => [
173
- "locale" => "de-DE",
174
- "bic" => "DEUTDEFF",
175
- "iban" => "DE89370400440532013000",
176
- "accountHolderName" => "Bob Holder",
177
- "billingAddress" => [
178
- "streetAddress" => "123 Currywurst Way",
179
- "extendedAddress" => "Lager Suite",
180
- "firstName" => "Wilhelm",
181
- "lastName" => "Dix",
182
- "locality" => "Frankfurt",
183
- "postalCode" => "60001",
184
- "countryCodeAlpha2" => "DE",
185
- "region" => "Hesse"
186
- ]
187
- ]
188
- ]);
189
-
190
- $result = $gateway->transaction()->sale([
191
- 'amount' => '47.00',
192
- 'merchantAccountId' => 'fake_sepa_ma',
193
- 'paymentMethodNonce' => $nonce,
194
- 'options' => [
195
- 'submitForSettlement' => true
196
- ]
197
- ]);
198
-
199
- $transaction = $result->transaction;
200
- $gateway->testing()->settle($transaction->id);
201
- $transaction = $gateway->transaction()->find($transaction->id);
202
- $this->assertSame(Braintree\Transaction::SETTLED, $transaction->status);
203
- }
204
-
205
- public function testSettlementConfirmAltPayTransaction()
206
- {
207
- $gateway = new Braintree\Gateway([
208
- 'environment' => 'development',
209
- 'merchantId' => 'altpay_merchant',
210
- 'publicKey' => 'altpay_merchant_public_key',
211
- 'privateKey' => 'altpay_merchant_private_key'
212
- ]);
213
-
214
- $result = $gateway->customer()->create();
215
- $this->assertTrue($result->success);
216
- $customer = $result->customer;
217
- $clientApi = new HttpClientApi($gateway->config);
218
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
219
- "customerId" => $customer->id,
220
- "sepa_mandate" => [
221
- "locale" => "de-DE",
222
- "bic" => "DEUTDEFF",
223
- "iban" => "DE89370400440532013000",
224
- "accountHolderName" => "Bob Holder",
225
- "billingAddress" => [
226
- "streetAddress" => "123 Currywurst Way",
227
- "extendedAddress" => "Lager Suite",
228
- "firstName" => "Wilhelm",
229
- "lastName" => "Dix",
230
- "locality" => "Frankfurt",
231
- "postalCode" => "60001",
232
- "countryCodeAlpha2" => "DE",
233
- "region" => "Hesse"
234
- ]
235
- ]
236
- ]);
237
-
238
- $result = $gateway->transaction()->sale([
239
- 'amount' => '47.00',
240
- 'merchantAccountId' => 'fake_sepa_ma',
241
- 'paymentMethodNonce' => $nonce,
242
- 'options' => [
243
- 'submitForSettlement' => true
244
- ]
245
- ]);
246
-
247
- $transaction = $result->transaction;
248
- $gateway->testing()->settlementConfirm($transaction->id);
249
- $transaction = $gateway->transaction()->find($transaction->id);
250
- $this->assertSame(Braintree\Transaction::SETTLEMENT_CONFIRMED, $transaction->status);
251
- }
252
-
253
- public function testSettlementDeclineAltPayTransaction()
254
- {
255
- $gateway = new Braintree\Gateway([
256
- 'environment' => 'development',
257
- 'merchantId' => 'altpay_merchant',
258
- 'publicKey' => 'altpay_merchant_public_key',
259
- 'privateKey' => 'altpay_merchant_private_key'
260
- ]);
261
-
262
- $result = $gateway->customer()->create();
263
- $this->assertTrue($result->success);
264
- $customer = $result->customer;
265
- $clientApi = new HttpClientApi($gateway->config);
266
- $nonce = $clientApi->nonceForNewEuropeanBankAccount([
267
- "customerId" => $customer->id,
268
- "sepa_mandate" => [
269
- "locale" => "de-DE",
270
- "bic" => "DEUTDEFF",
271
- "iban" => "DE89370400440532013000",
272
- "accountHolderName" => "Bob Holder",
273
- "billingAddress" => [
274
- "streetAddress" => "123 Currywurst Way",
275
- "extendedAddress" => "Lager Suite",
276
- "firstName" => "Wilhelm",
277
- "lastName" => "Dix",
278
- "locality" => "Frankfurt",
279
- "postalCode" => "60001",
280
- "countryCodeAlpha2" => "DE",
281
- "region" => "Hesse"
282
- ]
283
- ]
284
- ]);
285
-
286
- $result = $gateway->transaction()->sale([
287
- 'amount' => '47.00',
288
- 'merchantAccountId' => 'fake_sepa_ma',
289
- 'paymentMethodNonce' => $nonce,
290
- 'options' => [
291
- 'submitForSettlement' => true
292
- ]
293
- ]);
294
-
295
- $transaction = $result->transaction;
296
- $gateway->testing()->settlementConfirm($transaction->id);
297
- $gateway->testing()->settlementDecline($transaction->id);
298
- $transaction = $gateway->transaction()->find($transaction->id);
299
- $this->assertSame(Braintree\Transaction::SETTLEMENT_DECLINED, $transaction->status);
300
- }
301
-
302
- public function testCreateTransactionUsingFakeApplePayNonce()
303
- {
304
- $result = Braintree\Transaction::sale([
305
- 'amount' => '47.00',
306
- 'paymentMethodNonce' => Braintree\Test\Nonces::$applePayAmEx
307
- ]);
308
-
309
- $this->assertTrue($result->success);
310
- $transaction = $result->transaction;
311
- $this->assertEquals('47.00', $transaction->amount);
312
- $applePayDetails = $transaction->applePayCardDetails;
313
- $this->assertSame(Braintree\ApplePayCard::AMEX, $applePayDetails->cardType);
314
- $this->assertContains("AmEx ", $applePayDetails->sourceDescription);
315
- $this->assertContains("AmEx ", $applePayDetails->paymentInstrumentName);
316
- $this->assertTrue(intval($applePayDetails->expirationMonth) > 0);
317
- $this->assertTrue(intval($applePayDetails->expirationYear) > 0);
318
- $this->assertNotNull($applePayDetails->cardholderName);
319
- }
320
-
321
- public function testCreateTransactionUsingRawApplePayParams()
322
- {
323
- $result = Braintree\Transaction::sale([
324
- 'amount' => '1.02',
325
- 'apple_pay_card' => [
326
- 'number' => "370295001292109",
327
- 'cardholder_name' => "JANE SMITH",
328
- 'cryptogram' => "AAAAAAAA/COBt84dnIEcwAA3gAAGhgEDoLABAAhAgAABAAAALnNCLw==",
329
- 'expiration_month' => "10",
330
- 'expiration_year' => "17"
331
- ]
332
- ]);
333
- $this->assertTrue($result->success);
334
- }
335
-
336
- public function testCreateTransactionUsingFakeAndroidPayProxyCardNonce()
337
- {
338
- $result = Braintree\Transaction::sale([
339
- 'amount' => '47.00',
340
- 'paymentMethodNonce' => Braintree\Test\Nonces::$androidPayDiscover
341
- ]);
342
-
343
- $this->assertTrue($result->success);
344
- $transaction = $result->transaction;
345
- $this->assertEquals('47.00', $transaction->amount);
346
- $androidPayCardDetails = $transaction->androidPayCardDetails;
347
- $this->assertSame(Braintree\CreditCard::DISCOVER, $androidPayCardDetails->cardType);
348
- $this->assertSame("1117", $androidPayCardDetails->last4);
349
- $this->assertNull($androidPayCardDetails->token);
350
- $this->assertSame(Braintree\CreditCard::DISCOVER, $androidPayCardDetails->virtualCardType);
351
- $this->assertSame("1117", $androidPayCardDetails->virtualCardLast4);
352
- $this->assertSame(Braintree\CreditCard::VISA, $androidPayCardDetails->sourceCardType);
353
- $this->assertSame("1111", $androidPayCardDetails->sourceCardLast4);
354
- $this->assertSame("Visa 1111", $androidPayCardDetails->sourceDescription);
355
- $this->assertContains('android_pay', $androidPayCardDetails->imageUrl);
356
- $this->assertTrue(intval($androidPayCardDetails->expirationMonth) > 0);
357
- $this->assertTrue(intval($androidPayCardDetails->expirationYear) > 0);
358
- }
359
-
360
- public function testCreateTransactionUsingFakeAndroidPayNetworkTokenNonce()
361
- {
362
- $result = Braintree\Transaction::sale([
363
- 'amount' => '47.00',
364
- 'paymentMethodNonce' => Braintree\Test\Nonces::$androidPayMasterCard
365
- ]);
366
-
367
- $this->assertTrue($result->success);
368
- $transaction = $result->transaction;
369
- $this->assertEquals('47.00', $transaction->amount);
370
- $androidPayCardDetails = $transaction->androidPayCardDetails;
371
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCardDetails->cardType);
372
- $this->assertSame("4444", $androidPayCardDetails->last4);
373
- $this->assertNull($androidPayCardDetails->token);
374
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCardDetails->virtualCardType);
375
- $this->assertSame("4444", $androidPayCardDetails->virtualCardLast4);
376
- $this->assertSame(Braintree\CreditCard::MASTER_CARD, $androidPayCardDetails->sourceCardType);
377
- $this->assertSame("4444", $androidPayCardDetails->sourceCardLast4);
378
- $this->assertSame("MasterCard 4444", $androidPayCardDetails->sourceDescription);
379
- $this->assertContains('android_pay', $androidPayCardDetails->imageUrl);
380
- $this->assertTrue(intval($androidPayCardDetails->expirationMonth) > 0);
381
- $this->assertTrue(intval($androidPayCardDetails->expirationYear) > 0);
382
- }
383
-
384
- public function testCreateTransactionUsingFakeAmexExpressCheckoutNonce()
385
- {
386
- $result = Braintree\Transaction::sale([
387
- 'amount' => '47.00',
388
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
389
- 'paymentMethodNonce' => Braintree\Test\Nonces::$amexExpressCheckout
390
- ]);
391
-
392
- $this->assertTrue($result->success);
393
- $transaction = $result->transaction;
394
- $this->assertEquals('47.00', $transaction->amount);
395
- $amexExpressCheckoutCardDetails = $transaction->amexExpressCheckoutCardDetails;
396
-
397
- $this->assertSame(Braintree\CreditCard::AMEX, $amexExpressCheckoutCardDetails->cardType);
398
- $this->assertSame("341111", $amexExpressCheckoutCardDetails->bin);
399
- $this->assertSame("12/21", $amexExpressCheckoutCardDetails->cardMemberExpiryDate);
400
- $this->assertSame("0005", $amexExpressCheckoutCardDetails->cardMemberNumber);
401
- $this->assertNull($amexExpressCheckoutCardDetails->token);
402
- $this->assertNotNull($amexExpressCheckoutCardDetails->sourceDescription);
403
- $this->assertContains(".png", $amexExpressCheckoutCardDetails->imageUrl);
404
- $this->assertTrue(intval($amexExpressCheckoutCardDetails->expirationMonth) > 0);
405
- $this->assertTrue(intval($amexExpressCheckoutCardDetails->expirationYear) > 0);
406
- }
407
-
408
- public function testCreateTransactionUsingFakeVenmoAccountNonce()
409
- {
410
- $result = Braintree\Transaction::sale(array(
411
- 'amount' => '47.00',
412
- 'merchantAccountId' => Test\Helper::fakeVenmoAccountMerchantAccountId(),
413
- 'paymentMethodNonce' => Braintree\Test\Nonces::$venmoAccount
414
- ));
415
-
416
- $this->assertTrue($result->success);
417
- $transaction = $result->transaction;
418
- $this->assertEquals('47.00', $transaction->amount);
419
- $venmoAccountDetails = $transaction->venmoAccountDetails;
420
-
421
- $this->assertNull($venmoAccountDetails->token);
422
- $this->assertNotNull($venmoAccountDetails->sourceDescription);
423
- $this->assertContains(".png", $venmoAccountDetails->imageUrl);
424
- $this->assertSame("venmojoe", $venmoAccountDetails->username);
425
- $this->assertSame("Venmo-Joe-1", $venmoAccountDetails->venmoUserId);
426
- }
427
-
428
- public function testCreateTransactionUsingFakeCoinbaseNonce()
429
- {
430
- $result = Braintree\Transaction::sale([
431
- 'amount' => '17.00',
432
- 'paymentMethodNonce' => Braintree\Test\Nonces::$coinbase
433
- ]);
434
-
435
- $this->assertTrue($result->success);
436
- $transaction = $result->transaction;
437
- $this->assertNotNull($transaction->coinbaseDetails);
438
- $this->assertNotNull($transaction->coinbaseDetails->userId);
439
- $this->assertNotNull($transaction->coinbaseDetails->userName);
440
- $this->assertNotNull($transaction->coinbaseDetails->userEmail);
441
- }
442
-
443
- public function testCreateTransactionReturnsPaymentInstrumentType()
444
- {
445
- $http = new HttpClientApi(Braintree\Configuration::$global);
446
- $nonce = $http->nonce_for_new_card([
447
- "creditCard" => [
448
- "number" => "4111111111111111",
449
- "expirationMonth" => "11",
450
- "expirationYear" => "2099"
451
- ],
452
- "share" => true
453
- ]);
454
-
455
- $result = Braintree\Transaction::sale([
456
- 'amount' => '47.00',
457
- 'paymentMethodNonce' => $nonce
458
- ]);
459
-
460
- $this->assertTrue($result->success);
461
- $transaction = $result->transaction;
462
- $this->assertEquals(Braintree\PaymentInstrumentType::CREDIT_CARD, $transaction->paymentInstrumentType);
463
- }
464
-
465
- public function testCloneTransactionAndSubmitForSettlement()
466
- {
467
- $result = Braintree\Transaction::sale([
468
- 'amount' => '100.00',
469
- 'creditCard' => [
470
- 'number' => '5105105105105100',
471
- 'expirationDate' => '05/2011',
472
- ]
473
- ]);
474
-
475
- $this->assertTrue($result->success);
476
- $transaction = $result->transaction;
477
-
478
- $cloneResult = Braintree\Transaction::cloneTransaction($transaction->id, ['amount' => '123.45', 'options' => ['submitForSettlement' => true]]);
479
- $cloneTransaction = $cloneResult->transaction;
480
- $this->assertEquals('submitted_for_settlement', $cloneTransaction->status);
481
- }
482
-
483
- public function testCloneWithValidations()
484
- {
485
- $result = Braintree\Transaction::credit([
486
- 'amount' => '100.00',
487
- 'creditCard' => [
488
- 'number' => '5105105105105100',
489
- 'expirationDate' => '05/2011'
490
- ]
491
- ]);
492
- $this->assertTrue($result->success);
493
- $transaction = $result->transaction;
494
-
495
- $cloneResult = Braintree\Transaction::cloneTransaction($transaction->id, ['amount' => '123.45']);
496
- $this->assertFalse($cloneResult->success);
497
-
498
- $baseErrors = $cloneResult->errors->forKey('transaction')->onAttribute('base');
499
-
500
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_CANNOT_CLONE_CREDIT, $baseErrors[0]->code);
501
- }
502
-
503
- public function testSale()
504
- {
505
- $result = Braintree\Transaction::sale([
506
- 'amount' => '100.00',
507
- 'creditCard' => [
508
- 'cardholderName' => 'The Cardholder',
509
- 'number' => '5105105105105100',
510
- 'expirationDate' => '05/12'
511
- ]
512
- ]);
513
- $this->assertTrue($result->success);
514
- $transaction = $result->transaction;
515
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
516
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
517
- $this->assertEquals('100.00', $transaction->amount);
518
- $this->assertNotNull($transaction->processorAuthorizationCode);
519
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
520
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
521
- $this->assertEquals('The Cardholder', $transaction->creditCardDetails->cardholderName);
522
- }
523
-
524
- public function testSaleWithAccessToken()
525
- {
526
- $credentials = Test\Braintree\OAuthTestHelper::createCredentials([
527
- 'clientId' => 'client_id$development$integration_client_id',
528
- 'clientSecret' => 'client_secret$development$integration_client_secret',
529
- 'merchantId' => 'integration_merchant_id',
530
- ]);
531
-
532
- $gateway = new Braintree\Gateway([
533
- 'accessToken' => $credentials->accessToken,
534
- ]);
535
-
536
- $result = $gateway->transaction()->sale([
537
- 'amount' => '100.00',
538
- 'creditCard' => [
539
- 'cardholderName' => 'The Cardholder',
540
- 'number' => '5105105105105100',
541
- 'expirationDate' => '05/12'
542
- ]
543
- ]);
544
- $this->assertTrue($result->success);
545
- $transaction = $result->transaction;
546
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
547
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
548
- $this->assertEquals('100.00', $transaction->amount);
549
- $this->assertNotNull($transaction->processorAuthorizationCode);
550
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
551
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
552
- $this->assertEquals('The Cardholder', $transaction->creditCardDetails->cardholderName);
553
- }
554
-
555
- public function testSaleWithRiskData()
556
- {
557
- $result = Braintree\Transaction::sale([
558
- 'amount' => '100.00',
559
- 'creditCard' => [
560
- 'cardholderName' => 'The Cardholder',
561
- 'number' => '5105105105105100',
562
- 'expirationDate' => '05/12'
563
- ]
564
- ]);
565
- $this->assertTrue($result->success);
566
- $transaction = $result->transaction;
567
- $this->assertNotNull($transaction->riskData);
568
- $this->assertNotNull($transaction->riskData->decision);
569
- }
570
-
571
- public function testRecurring()
572
- {
573
- $result = Braintree\Transaction::sale([
574
- 'amount' => '100.00',
575
- 'recurring' => true,
576
- 'creditCard' => [
577
- 'cardholderName' => 'The Cardholder',
578
- 'number' => '5105105105105100',
579
- 'expirationDate' => '05/12'
580
- ]
581
- ]);
582
- $this->assertTrue($result->success);
583
- $transaction = $result->transaction;
584
- $this->assertEquals(true, $transaction->recurring);
585
- }
586
-
587
- public function testSale_withServiceFee()
588
- {
589
- $result = Braintree\Transaction::sale([
590
- 'amount' => '10.00',
591
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
592
- 'creditCard' => [
593
- 'number' => '5105105105105100',
594
- 'expirationDate' => '05/12'
595
- ],
596
- 'serviceFeeAmount' => '1.00'
597
- ]);
598
- $this->assertTrue($result->success);
599
- $transaction = $result->transaction;
600
- $this->assertEquals('1.00', $transaction->serviceFeeAmount);
601
- }
602
-
603
- public function testSale_isInvalidIfTransactionMerchantAccountIsNotSub()
604
- {
605
- $result = Braintree\Transaction::sale([
606
- 'amount' => '10.00',
607
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
608
- 'creditCard' => [
609
- 'number' => '5105105105105100',
610
- 'expirationDate' => '05/12'
611
- ],
612
- 'serviceFeeAmount' => '1.00'
613
- ]);
614
- $this->assertFalse($result->success);
615
- $transaction = $result->transaction;
616
- $serviceFeeErrors = $result->errors->forKey('transaction')->onAttribute('serviceFeeAmount');
617
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_SERVICE_FEE_AMOUNT_NOT_ALLOWED_ON_MASTER_MERCHANT_ACCOUNT, $serviceFeeErrors[0]->code);
618
- }
619
-
620
- public function testSale_isInvalidIfSubMerchantAccountHasNoServiceFee()
621
- {
622
- $result = Braintree\Transaction::sale([
623
- 'amount' => '10.00',
624
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
625
- 'creditCard' => [
626
- 'number' => '5105105105105100',
627
- 'expirationDate' => '05/12'
628
- ]
629
- ]);
630
- $this->assertFalse($result->success);
631
- $transaction = $result->transaction;
632
- $serviceFeeErrors = $result->errors->forKey('transaction')->onAttribute('merchantAccountId');
633
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_SUB_MERCHANT_ACCOUNT_REQUIRES_SERVICE_FEE_AMOUNT, $serviceFeeErrors[0]->code);
634
- }
635
-
636
- public function testSale_withVenmoSdkSession()
637
- {
638
- $result = Braintree\Transaction::sale([
639
- 'amount' => '10.00',
640
- 'creditCard' => [
641
- 'number' => '5105105105105100',
642
- 'expirationDate' => '05/12'
643
- ],
644
- 'options' => [
645
- 'venmoSdkSession' => Braintree\Test\VenmoSdk::getTestSession()
646
- ]
647
- ]);
648
- $this->assertEquals(true, $result->success);
649
- $transaction = $result->transaction;
650
- $this->assertEquals(true, $transaction->creditCardDetails->venmoSdk);
651
- }
652
-
653
- public function testSale_withVenmoSdkPaymentMethodCode()
654
- {
655
- $result = Braintree\Transaction::sale([
656
- 'amount' => '10.00',
657
- 'venmoSdkPaymentMethodCode' => Braintree\Test\VenmoSdk::$visaPaymentMethodCode
658
- ]);
659
- $this->assertTrue($result->success);
660
- $transaction = $result->transaction;
661
- $this->assertEquals("411111", $transaction->creditCardDetails->bin);
662
- }
663
-
664
- public function testSale_withLevel2Attributes()
665
- {
666
- $result = Braintree\Transaction::sale([
667
- 'amount' => '100.00',
668
- 'creditCard' => [
669
- 'cardholderName' => 'The Cardholder',
670
- 'expirationDate' => '05/2011',
671
- 'number' => '5105105105105100'
672
- ],
673
- 'taxExempt' => true,
674
- 'taxAmount' => '10.00',
675
- 'purchaseOrderNumber' => '12345'
676
- ]);
677
-
678
- $this->assertTrue($result->success);
679
- $transaction = $result->transaction;
680
-
681
- $this->assertTrue($transaction->taxExempt);
682
- $this->assertEquals('10.00', $transaction->taxAmount);
683
- $this->assertEquals('12345', $transaction->purchaseOrderNumber);
684
- }
685
-
686
- public function testSale_withInvalidTaxAmountAttribute()
687
- {
688
- $result = Braintree\Transaction::sale([
689
- 'amount' => '100.00',
690
- 'creditCard' => [
691
- 'cardholderName' => 'The Cardholder',
692
- 'expirationDate' => '05/2011',
693
- 'number' => '5105105105105100'
694
- ],
695
- 'taxAmount' => 'abc'
696
- ]);
697
-
698
- $this->assertFalse($result->success);
699
-
700
- $taxAmountErrors = $result->errors->forKey('transaction')->onAttribute('taxAmount');
701
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_TAX_AMOUNT_FORMAT_IS_INVALID, $taxAmountErrors[0]->code);
702
- }
703
-
704
- public function testSale_withServiceFeeTooLarge()
705
- {
706
- $result = Braintree\Transaction::sale([
707
- 'amount' => '10.00',
708
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
709
- 'creditCard' => [
710
- 'number' => '5105105105105100',
711
- 'expirationDate' => '05/12'
712
- ],
713
- 'serviceFeeAmount' => '20.00'
714
- ]);
715
- $this->assertFalse($result->success);
716
- $errors = $result->errors->forKey('transaction')->onAttribute('serviceFeeAmount');
717
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_SERVICE_FEE_AMOUNT_IS_TOO_LARGE, $errors[0]->code);
718
- }
719
-
720
- public function testSale_withTooLongPurchaseOrderAttribute()
721
- {
722
- $result = Braintree\Transaction::sale([
723
- 'amount' => '100.00',
724
- 'creditCard' => [
725
- 'cardholderName' => 'The Cardholder',
726
- 'expirationDate' => '05/2011',
727
- 'number' => '5105105105105100'
728
- ],
729
- 'purchaseOrderNumber' => 'aaaaaaaaaaaaaaaaaa'
730
- ]);
731
-
732
- $this->assertFalse($result->success);
733
-
734
- $purchaseOrderNumberErrors = $result->errors->forKey('transaction')->onAttribute('purchaseOrderNumber');
735
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_PURCHASE_ORDER_NUMBER_IS_TOO_LONG, $purchaseOrderNumberErrors[0]->code);
736
- }
737
-
738
- public function testSale_withInvalidPurchaseOrderNumber()
739
- {
740
- $result = Braintree\Transaction::sale([
741
- 'amount' => '100.00',
742
- 'creditCard' => [
743
- 'cardholderName' => 'The Cardholder',
744
- 'expirationDate' => '05/2011',
745
- 'number' => '5105105105105100'
746
- ],
747
- 'purchaseOrderNumber' => "\x80\x90\xA0"
748
- ]);
749
-
750
- $this->assertFalse($result->success);
751
-
752
- $purchaseOrderNumberErrors = $result->errors->forKey('transaction')->onAttribute('purchaseOrderNumber');
753
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_PURCHASE_ORDER_NUMBER_IS_INVALID, $purchaseOrderNumberErrors[0]->code);
754
- }
755
-
756
- public function testSale_withAllAttributes()
757
- {
758
- $result = Braintree\Transaction::sale([
759
- 'amount' => '100.00',
760
- 'orderId' => '123',
761
- 'channel' => 'MyShoppingCardProvider',
762
- 'creditCard' => [
763
- 'cardholderName' => 'The Cardholder',
764
- 'number' => '5105105105105100',
765
- 'expirationDate' => '05/2011',
766
- 'cvv' => '123'
767
- ],
768
- 'customer' => [
769
- 'firstName' => 'Dan',
770
- 'lastName' => 'Smith',
771
- 'company' => 'Braintree',
772
- 'email' => 'dan@example.com',
773
- 'phone' => '419-555-1234',
774
- 'fax' => '419-555-1235',
775
- 'website' => 'http://braintreepayments.com'
776
- ],
777
- 'billing' => [
778
- 'firstName' => 'Carl',
779
- 'lastName' => 'Jones',
780
- 'company' => 'Braintree',
781
- 'streetAddress' => '123 E Main St',
782
- 'extendedAddress' => 'Suite 403',
783
- 'locality' => 'Chicago',
784
- 'region' => 'IL',
785
- 'postalCode' => '60622',
786
- 'countryName' => 'United States of America',
787
- 'countryCodeAlpha2' => 'US',
788
- 'countryCodeAlpha3' => 'USA',
789
- 'countryCodeNumeric' => '840'
790
- ],
791
- 'shipping' => [
792
- 'firstName' => 'Andrew',
793
- 'lastName' => 'Mason',
794
- 'company' => 'Braintree',
795
- 'streetAddress' => '456 W Main St',
796
- 'extendedAddress' => 'Apt 2F',
797
- 'locality' => 'Bartlett',
798
- 'region' => 'IL',
799
- 'postalCode' => '60103',
800
- 'countryName' => 'United States of America',
801
- 'countryCodeAlpha2' => 'US',
802
- 'countryCodeAlpha3' => 'USA',
803
- 'countryCodeNumeric' => '840'
804
- ]
805
- ]);
806
- Test\Helper::assertPrintable($result);
807
- $this->assertTrue($result->success);
808
- $transaction = $result->transaction;
809
-
810
- $this->assertNotNull($transaction->id);
811
- $this->assertNotNull($transaction->createdAt);
812
- $this->assertNotNull($transaction->updatedAt);
813
- $this->assertNull($transaction->refundId);
814
-
815
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $transaction->merchantAccountId);
816
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
817
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
818
- $this->assertEquals('100.00', $transaction->amount);
819
- $this->assertEquals('USD', $transaction->currencyIsoCode);
820
- $this->assertEquals('123', $transaction->orderId);
821
- $this->assertEquals('MyShoppingCardProvider', $transaction->channel);
822
- $this->assertEquals('MasterCard', $transaction->creditCardDetails->cardType);
823
- $this->assertEquals('1000', $transaction->processorResponseCode);
824
- $this->assertEquals('Approved', $transaction->processorResponseText);
825
- $this->assertNull($transaction->voiceReferralNumber);
826
- $this->assertFalse($transaction->taxExempt);
827
-
828
- $this->assertEquals('M', $transaction->avsPostalCodeResponseCode);
829
- $this->assertEquals('M', $transaction->avsStreetAddressResponseCode);
830
- $this->assertEquals('M', $transaction->cvvResponseCode);
831
-
832
- $this->assertEquals('Dan', $transaction->customerDetails->firstName);
833
- $this->assertEquals('Smith', $transaction->customerDetails->lastName);
834
- $this->assertEquals('Braintree', $transaction->customerDetails->company);
835
- $this->assertEquals('dan@example.com', $transaction->customerDetails->email);
836
- $this->assertEquals('419-555-1234', $transaction->customerDetails->phone);
837
- $this->assertEquals('419-555-1235', $transaction->customerDetails->fax);
838
- $this->assertEquals('http://braintreepayments.com', $transaction->customerDetails->website);
839
-
840
- $this->assertEquals('Carl', $transaction->billingDetails->firstName);
841
- $this->assertEquals('Jones', $transaction->billingDetails->lastName);
842
- $this->assertEquals('Braintree', $transaction->billingDetails->company);
843
- $this->assertEquals('123 E Main St', $transaction->billingDetails->streetAddress);
844
- $this->assertEquals('Suite 403', $transaction->billingDetails->extendedAddress);
845
- $this->assertEquals('Chicago', $transaction->billingDetails->locality);
846
- $this->assertEquals('IL', $transaction->billingDetails->region);
847
- $this->assertEquals('60622', $transaction->billingDetails->postalCode);
848
- $this->assertEquals('United States of America', $transaction->billingDetails->countryName);
849
- $this->assertEquals('US', $transaction->billingDetails->countryCodeAlpha2);
850
- $this->assertEquals('USA', $transaction->billingDetails->countryCodeAlpha3);
851
- $this->assertEquals('840', $transaction->billingDetails->countryCodeNumeric);
852
-
853
- $this->assertEquals('Andrew', $transaction->shippingDetails->firstName);
854
- $this->assertEquals('Mason', $transaction->shippingDetails->lastName);
855
- $this->assertEquals('Braintree', $transaction->shippingDetails->company);
856
- $this->assertEquals('456 W Main St', $transaction->shippingDetails->streetAddress);
857
- $this->assertEquals('Apt 2F', $transaction->shippingDetails->extendedAddress);
858
- $this->assertEquals('Bartlett', $transaction->shippingDetails->locality);
859
- $this->assertEquals('IL', $transaction->shippingDetails->region);
860
- $this->assertEquals('60103', $transaction->shippingDetails->postalCode);
861
- $this->assertEquals('United States of America', $transaction->shippingDetails->countryName);
862
- $this->assertEquals('US', $transaction->shippingDetails->countryCodeAlpha2);
863
- $this->assertEquals('USA', $transaction->shippingDetails->countryCodeAlpha3);
864
- $this->assertEquals('840', $transaction->shippingDetails->countryCodeNumeric);
865
-
866
- $this->assertNotNull($transaction->processorAuthorizationCode);
867
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
868
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
869
- $this->assertEquals('510510******5100', $transaction->creditCardDetails->maskedNumber);
870
- $this->assertEquals('The Cardholder', $transaction->creditCardDetails->cardholderName);
871
- $this->assertEquals('05', $transaction->creditCardDetails->expirationMonth);
872
- $this->assertEquals('2011', $transaction->creditCardDetails->expirationYear);
873
- $this->assertNotNull($transaction->creditCardDetails->imageUrl);
874
- }
875
-
876
- public function testSale_withCustomFields()
877
- {
878
- $result = Braintree\Transaction::sale([
879
- 'amount' => '100.00',
880
- 'creditCard' => [
881
- 'number' => '5105105105105100',
882
- 'expirationDate' => '05/12'
883
- ],
884
- 'customFields' => [
885
- 'store_me' => 'custom value'
886
- ]
887
- ]);
888
- $this->assertTrue($result->success);
889
- $transaction = $result->transaction;
890
- $customFields = $transaction->customFields;
891
- $this->assertEquals('custom value', $customFields['store_me']);
892
- }
893
-
894
- public function testSale_withExpirationMonthAndYear()
895
- {
896
- $result = Braintree\Transaction::sale([
897
- 'amount' => '100.00',
898
- 'creditCard' => [
899
- 'number' => '5105105105105100',
900
- 'expirationMonth' => '5',
901
- 'expirationYear' => '2012'
902
- ]
903
- ]);
904
- $this->assertTrue($result->success);
905
- $transaction = $result->transaction;
906
- $this->assertEquals('05', $transaction->creditCardDetails->expirationMonth);
907
- $this->assertEquals('2012', $transaction->creditCardDetails->expirationYear);
908
- }
909
-
910
- public function testSale_underscoresAllCustomFields()
911
- {
912
- $result = Braintree\Transaction::sale([
913
- 'amount' => '100.00',
914
- 'creditCard' => [
915
- 'number' => '5105105105105100',
916
- 'expirationDate' => '05/12'
917
- ],
918
- 'customFields' => [
919
- 'storeMe' => 'custom value'
920
- ]
921
- ]);
922
- $this->assertTrue($result->success);
923
- $transaction = $result->transaction;
924
- $customFields = $transaction->customFields;
925
- $this->assertEquals('custom value', $customFields['store_me']);
926
- }
927
-
928
- public function testSale_withInvalidCustomField()
929
- {
930
- $result = Braintree\Transaction::sale([
931
- 'amount' => '100.00',
932
- 'creditCard' => [
933
- 'number' => '5105105105105100',
934
- 'expirationDate' => '05/12'
935
- ],
936
- 'customFields' => [
937
- 'invalidKey' => 'custom value'
938
- ]
939
- ]);
940
- $this->assertFalse($result->success);
941
- $errors = $result->errors->forKey('transaction')->onAttribute('customFields');
942
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_CUSTOM_FIELD_IS_INVALID, $errors[0]->code);
943
- $this->assertEquals('Custom field is invalid: invalidKey.', $errors[0]->message);
944
- }
945
-
946
- public function testSale_withMerchantAccountId()
947
- {
948
- $result = Braintree\Transaction::sale([
949
- 'amount' => '100.00',
950
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
951
- 'creditCard' => [
952
- 'number' => '5105105105105100',
953
- 'expirationDate' => '05/12'
954
- ]
955
- ]);
956
- $this->assertTrue($result->success);
957
- $transaction = $result->transaction;
958
- $this->assertEquals(Test\Helper::nonDefaultMerchantAccountId(), $transaction->merchantAccountId);
959
- }
960
-
961
- public function testSale_withoutMerchantAccountIdFallsBackToDefault()
962
- {
963
- $result = Braintree\Transaction::sale([
964
- 'amount' => '100.00',
965
- 'creditCard' => [
966
- 'number' => '5105105105105100',
967
- 'expirationDate' => '05/12'
968
- ]
969
- ]);
970
- $this->assertTrue($result->success);
971
- $transaction = $result->transaction;
972
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $transaction->merchantAccountId);
973
- }
974
-
975
- public function testSale_withShippingAddressId()
976
- {
977
- $customer = Braintree\Customer::create([
978
- 'firstName' => 'Mike',
979
- 'creditCard' => [
980
- 'cardholderName' => 'The Cardholder',
981
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
982
- 'expirationDate' => '05/12'
983
- ]
984
- ])->customer;
985
-
986
- $address = Braintree\Address::create([
987
- 'customerId' => $customer->id,
988
- 'streetAddress' => '123 Fake St.'
989
- ])->address;
990
-
991
- $result = Braintree\Transaction::sale([
992
- 'amount' => '100.00',
993
- 'customerId' => $customer->id,
994
- 'shippingAddressId' => $address->id
995
- ]);
996
- $this->assertTrue($result->success);
997
- $transaction = $result->transaction;
998
- $this->assertEquals('123 Fake St.', $transaction->shippingDetails->streetAddress);
999
- $this->assertEquals($address->id, $transaction->shippingDetails->id);
1000
- }
1001
-
1002
- public function testSale_withBillingAddressId()
1003
- {
1004
- $customer = Braintree\Customer::create([
1005
- 'firstName' => 'Mike',
1006
- 'creditCard' => [
1007
- 'cardholderName' => 'The Cardholder',
1008
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1009
- 'expirationDate' => '05/12'
1010
- ]
1011
- ])->customer;
1012
-
1013
- $address = Braintree\Address::create([
1014
- 'customerId' => $customer->id,
1015
- 'streetAddress' => '123 Fake St.'
1016
- ])->address;
1017
-
1018
- $result = Braintree\Transaction::sale([
1019
- 'amount' => '100.00',
1020
- 'customerId' => $customer->id,
1021
- 'billingAddressId' => $address->id
1022
- ]);
1023
- $this->assertTrue($result->success);
1024
- $transaction = $result->transaction;
1025
- $this->assertEquals('123 Fake St.', $transaction->billingDetails->streetAddress);
1026
- $this->assertEquals($address->id, $transaction->billingDetails->id);
1027
- }
1028
-
1029
- public function testSaleNoValidate()
1030
- {
1031
- $transaction = Braintree\Transaction::saleNoValidate([
1032
- 'amount' => '100.00',
1033
- 'creditCard' => [
1034
- 'number' => '5105105105105100',
1035
- 'expirationDate' => '05/12'
1036
- ]
1037
- ]);
1038
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1039
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
1040
- $this->assertEquals('100.00', $transaction->amount);
1041
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
1042
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
1043
- }
1044
-
1045
- public function testSale_withProcessorDecline()
1046
- {
1047
- $result = Braintree\Transaction::sale([
1048
- 'amount' => Braintree\Test\TransactionAmounts::$decline,
1049
- 'creditCard' => [
1050
- 'number' => '5105105105105100',
1051
- 'expirationDate' => '05/12'
1052
- ],
1053
- ]);
1054
- $this->assertFalse($result->success);
1055
- $this->assertEquals(Braintree\Transaction::PROCESSOR_DECLINED, $result->transaction->status);
1056
- $this->assertEquals(2000, $result->transaction->processorResponseCode);
1057
- $this->assertEquals("Do Not Honor", $result->transaction->processorResponseText);
1058
- $this->assertEquals("2000 : Do Not Honor", $result->transaction->additionalProcessorResponse);
1059
- }
1060
-
1061
- public function testSale_withExistingCustomer()
1062
- {
1063
- $customer = Braintree\Customer::create([
1064
- 'firstName' => 'Mike',
1065
- 'lastName' => 'Jones',
1066
- 'company' => 'Jones Co.',
1067
- 'email' => 'mike.jones@example.com',
1068
- 'phone' => '419.555.1234',
1069
- 'fax' => '419.555.1235',
1070
- 'website' => 'http://example.com'
1071
- ])->customer;
1072
-
1073
- $transaction = Braintree\Transaction::sale([
1074
- 'amount' => '100.00',
1075
- 'customerId' => $customer->id,
1076
- 'creditCard' => [
1077
- 'cardholderName' => 'The Cardholder',
1078
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1079
- 'expirationDate' => '05/12'
1080
- ]
1081
- ])->transaction;
1082
- $this->assertEquals($transaction->creditCardDetails->maskedNumber, '401288******1881');
1083
- $this->assertNull($transaction->vaultCreditCard());
1084
- }
1085
-
1086
- public function testSale_andStoreShippingAddressInVault()
1087
- {
1088
- $customer = Braintree\Customer::create([
1089
- 'firstName' => 'Mike',
1090
- 'lastName' => 'Jones',
1091
- 'company' => 'Jones Co.',
1092
- 'email' => 'mike.jones@example.com',
1093
- 'phone' => '419.555.1234',
1094
- 'fax' => '419.555.1235',
1095
- 'website' => 'http://example.com'
1096
- ])->customer;
1097
-
1098
- $transaction = Braintree\Transaction::sale([
1099
- 'amount' => '100.00',
1100
- 'customerId' => $customer->id,
1101
- 'creditCard' => [
1102
- 'cardholderName' => 'The Cardholder',
1103
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1104
- 'expirationDate' => '05/12'
1105
- ],
1106
- 'shipping' => [
1107
- 'firstName' => 'Darren',
1108
- 'lastName' => 'Stevens'
1109
- ],
1110
- 'options' => [
1111
- 'storeInVault' => true,
1112
- 'storeShippingAddressInVault' => true
1113
- ]
1114
- ])->transaction;
1115
-
1116
- $customer = Braintree\Customer::find($customer->id);
1117
- $this->assertEquals('Darren', $customer->addresses[0]->firstName);
1118
- $this->assertEquals('Stevens', $customer->addresses[0]->lastName);
1119
- }
1120
-
1121
- public function testSale_withExistingCustomer_storeInVault()
1122
- {
1123
- $customer = Braintree\Customer::create([
1124
- 'firstName' => 'Mike',
1125
- 'lastName' => 'Jones',
1126
- 'company' => 'Jones Co.',
1127
- 'email' => 'mike.jones@example.com',
1128
- 'phone' => '419.555.1234',
1129
- 'fax' => '419.555.1235',
1130
- 'website' => 'http://example.com'
1131
- ])->customer;
1132
-
1133
- $transaction = Braintree\Transaction::sale([
1134
- 'amount' => '100.00',
1135
- 'customerId' => $customer->id,
1136
- 'creditCard' => [
1137
- 'cardholderName' => 'The Cardholder',
1138
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
1139
- 'expirationDate' => '05/12'
1140
- ],
1141
- 'options' => [
1142
- 'storeInVault' => true
1143
- ]
1144
- ])->transaction;
1145
- $this->assertEquals($transaction->creditCardDetails->maskedNumber, '401288******1881');
1146
- $this->assertEquals($transaction->vaultCreditCard()->maskedNumber, '401288******1881');
1147
- }
1148
-
1149
- public function testCredit()
1150
- {
1151
- $result = Braintree\Transaction::credit([
1152
- 'amount' => '100.00',
1153
- 'creditCard' => [
1154
- 'number' => '5105105105105100',
1155
- 'expirationDate' => '05/12'
1156
- ]
1157
- ]);
1158
- $this->assertTrue($result->success);
1159
- $transaction = $result->transaction;
1160
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $transaction->status);
1161
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction->type);
1162
- $this->assertEquals('100.00', $transaction->amount);
1163
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
1164
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
1165
- }
1166
-
1167
- public function testCreditNoValidate()
1168
- {
1169
- $transaction = Braintree\Transaction::creditNoValidate([
1170
- 'amount' => '100.00',
1171
- 'creditCard' => [
1172
- 'number' => '5105105105105100',
1173
- 'expirationDate' => '05/12'
1174
- ]
1175
- ]);
1176
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction->type);
1177
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $transaction->status);
1178
- $this->assertEquals('100.00', $transaction->amount);
1179
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
1180
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
1181
- }
1182
-
1183
- public function testCredit_withMerchantAccountId()
1184
- {
1185
- $result = Braintree\Transaction::credit([
1186
- 'amount' => '100.00',
1187
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
1188
- 'creditCard' => [
1189
- 'number' => '5105105105105100',
1190
- 'expirationDate' => '05/12'
1191
- ]
1192
- ]);
1193
- $this->assertTrue($result->success);
1194
- $transaction = $result->transaction;
1195
- $this->assertEquals(Test\Helper::nonDefaultMerchantAccountId(), $transaction->merchantAccountId);
1196
- }
1197
-
1198
- public function testCredit_withoutMerchantAccountIdFallsBackToDefault()
1199
- {
1200
- $result = Braintree\Transaction::credit([
1201
- 'amount' => '100.00',
1202
- 'creditCard' => [
1203
- 'number' => '5105105105105100',
1204
- 'expirationDate' => '05/12'
1205
- ]
1206
- ]);
1207
- $this->assertTrue($result->success);
1208
- $transaction = $result->transaction;
1209
- $this->assertEquals(Test\Helper::defaultMerchantAccountId(), $transaction->merchantAccountId);
1210
- }
1211
-
1212
- public function testCredit_withServiceFeeNotAllowed()
1213
- {
1214
- $result = Braintree\Transaction::credit([
1215
- 'amount' => '100.00',
1216
- 'creditCard' => [
1217
- 'number' => '5105105105105100',
1218
- 'expirationDate' => '05/12'
1219
- ],
1220
- 'serviceFeeAmount' => '12.75'
1221
- ]);
1222
- $this->assertFalse($result->success);
1223
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1224
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_SERVICE_FEE_IS_NOT_ALLOWED_ON_CREDITS, $errors[0]->code);
1225
- }
1226
-
1227
- public function testSubmitForSettlement_nullAmount()
1228
- {
1229
- $transaction = Braintree\Transaction::saleNoValidate([
1230
- 'amount' => '100.00',
1231
- 'creditCard' => [
1232
- 'number' => '5105105105105100',
1233
- 'expirationDate' => '05/12'
1234
- ]
1235
- ]);
1236
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1237
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id);
1238
- $this->assertEquals(true, $submitResult->success);
1239
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
1240
- $this->assertEquals('100.00', $submitResult->transaction->amount);
1241
- }
1242
-
1243
- public function testSubmitForSettlement_amountLessThanServiceFee()
1244
- {
1245
- $transaction = Braintree\Transaction::saleNoValidate([
1246
- 'amount' => '10.00',
1247
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
1248
- 'creditCard' => [
1249
- 'number' => '5105105105105100',
1250
- 'expirationDate' => '05/12'
1251
- ],
1252
- 'serviceFeeAmount' => '5.00'
1253
- ]);
1254
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '1.00');
1255
- $errors = $submitResult->errors->forKey('transaction')->onAttribute('amount');
1256
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_SETTLEMENT_AMOUNT_IS_LESS_THAN_SERVICE_FEE_AMOUNT, $errors[0]->code);
1257
- }
1258
-
1259
- public function testSubmitForSettlement_withAmount()
1260
- {
1261
- $transaction = Braintree\Transaction::saleNoValidate([
1262
- 'amount' => '100.00',
1263
- 'creditCard' => [
1264
- 'number' => '5105105105105100',
1265
- 'expirationDate' => '05/12'
1266
- ]
1267
- ]);
1268
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1269
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '50.00');
1270
- $this->assertEquals(true, $submitResult->success);
1271
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
1272
- $this->assertEquals('50.00', $submitResult->transaction->amount);
1273
- }
1274
-
1275
- public function testSubmitForSettlement_withOrderId()
1276
- {
1277
- $transaction = Braintree\Transaction::saleNoValidate([
1278
- 'amount' => '100.00',
1279
- 'creditCard' => [
1280
- 'number' => '5105105105105100',
1281
- 'expirationDate' => '05/12'
1282
- ]
1283
- ]);
1284
-
1285
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1286
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '67.00', ['orderId' => 'ABC123']);
1287
- $this->assertEquals(true, $submitResult->success);
1288
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
1289
- $this->assertEquals('ABC123', $submitResult->transaction->orderId);
1290
- $this->assertEquals('67.00', $submitResult->transaction->amount);
1291
- }
1292
-
1293
- public function testSubmitForSettlement_withDescriptor()
1294
- {
1295
- $transaction = Braintree\Transaction::saleNoValidate([
1296
- 'amount' => '100.00',
1297
- 'creditCard' => [
1298
- 'number' => '5105105105105100',
1299
- 'expirationDate' => '05/12'
1300
- ]
1301
- ]);
1302
-
1303
- $params = [
1304
- 'descriptor' => [
1305
- 'name' => '123*123456789012345678',
1306
- 'phone' => '3334445555',
1307
- 'url' => 'ebay.com'
1308
- ]
1309
- ];
1310
-
1311
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1312
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '67.00', $params);
1313
- $this->assertEquals(true, $submitResult->success);
1314
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
1315
- $this->assertEquals('123*123456789012345678', $submitResult->transaction->descriptor->name);
1316
- $this->assertEquals('3334445555', $submitResult->transaction->descriptor->phone);
1317
- $this->assertEquals('ebay.com', $submitResult->transaction->descriptor->url);
1318
- }
1319
-
1320
- public function testSubmitForSettlement_withInvalidParams()
1321
- {
1322
- $transaction = Braintree\Transaction::saleNoValidate([
1323
- 'amount' => '100.00',
1324
- 'creditCard' => [
1325
- 'number' => '5105105105105100',
1326
- 'expirationDate' => '05/12'
1327
- ]
1328
- ]);
1329
-
1330
- $params = ['invalid' => 'invalid'];
1331
-
1332
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: invalid');
1333
- Braintree\Transaction::submitForSettlement($transaction->id, '67.00', $params);
1334
- }
1335
-
1336
- public function testSubmitForSettlementNoValidate_whenValidWithoutAmount()
1337
- {
1338
- $transaction = Braintree\Transaction::saleNoValidate([
1339
- 'amount' => '100.00',
1340
- 'creditCard' => [
1341
- 'number' => '5105105105105100',
1342
- 'expirationDate' => '05/12'
1343
- ]
1344
- ]);
1345
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1346
- $submittedTransaction = Braintree\Transaction::submitForSettlementNoValidate($transaction->id);
1347
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submittedTransaction->status);
1348
- $this->assertEquals('100.00', $submittedTransaction->amount);
1349
- }
1350
-
1351
- public function testSubmitForSettlementNoValidate_whenValidWithAmount()
1352
- {
1353
- $transaction = Braintree\Transaction::saleNoValidate([
1354
- 'amount' => '100.00',
1355
- 'creditCard' => [
1356
- 'number' => '5105105105105100',
1357
- 'expirationDate' => '05/12'
1358
- ]
1359
- ]);
1360
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1361
- $submittedTransaction = Braintree\Transaction::submitForSettlementNoValidate($transaction->id, '99.00');
1362
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submittedTransaction->status);
1363
- $this->assertEquals('99.00', $submittedTransaction->amount);
1364
- }
1365
-
1366
- public function testSubmitForSettlementNoValidate_whenInvalid()
1367
- {
1368
- $transaction = Braintree\Transaction::saleNoValidate([
1369
- 'amount' => '100.00',
1370
- 'creditCard' => [
1371
- 'number' => '5105105105105100',
1372
- 'expirationDate' => '05/12'
1373
- ]
1374
- ]);
1375
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1376
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
1377
- $submittedTransaction = Braintree\Transaction::submitForSettlementNoValidate($transaction->id, '101.00');
1378
- }
1379
-
1380
- public function testVoid()
1381
- {
1382
- $transaction = Braintree\Transaction::saleNoValidate([
1383
- 'amount' => '100.00',
1384
- 'creditCard' => [
1385
- 'number' => '5105105105105100',
1386
- 'expirationDate' => '05/12'
1387
- ]
1388
- ]);
1389
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1390
- $voidResult = Braintree\Transaction::void($transaction->id);
1391
- $this->assertEquals(true, $voidResult->success);
1392
- $this->assertEquals(Braintree\Transaction::VOIDED, $voidResult->transaction->status);
1393
- }
1394
-
1395
- public function test_countryValidationError_inconsistency()
1396
- {
1397
- $result = Braintree\Transaction::sale([
1398
- 'amount' => '100.00',
1399
- 'creditCard' => [
1400
- 'number' => '5105105105105100',
1401
- 'expirationDate' => '05/12'
1402
- ],
1403
- 'billing' => [
1404
- 'countryCodeAlpha2' => 'AS',
1405
- 'countryCodeAlpha3' => 'USA'
1406
- ]
1407
- ]);
1408
- $this->assertFalse($result->success);
1409
-
1410
- $errors = $result->errors->forKey('transaction')->forKey('billing')->onAttribute('base');
1411
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_INCONSISTENT_COUNTRY, $errors[0]->code);
1412
- }
1413
-
1414
- public function test_countryValidationError_incorrectAlpha2()
1415
- {
1416
- $result = Braintree\Transaction::sale([
1417
- 'amount' => '100.00',
1418
- 'creditCard' => [
1419
- 'number' => '5105105105105100',
1420
- 'expirationDate' => '05/12'
1421
- ],
1422
- 'billing' => [
1423
- 'countryCodeAlpha2' => 'ZZ'
1424
- ]
1425
- ]);
1426
- $this->assertFalse($result->success);
1427
-
1428
- $errors = $result->errors->forKey('transaction')->forKey('billing')->onAttribute('countryCodeAlpha2');
1429
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED, $errors[0]->code);
1430
- }
1431
-
1432
- public function test_countryValidationError_incorrectAlpha3()
1433
- {
1434
- $result = Braintree\Transaction::sale([
1435
- 'amount' => '100.00',
1436
- 'creditCard' => [
1437
- 'number' => '5105105105105100',
1438
- 'expirationDate' => '05/12'
1439
- ],
1440
- 'billing' => [
1441
- 'countryCodeAlpha3' => 'ZZZ'
1442
- ]
1443
- ]);
1444
- $this->assertFalse($result->success);
1445
-
1446
- $errors = $result->errors->forKey('transaction')->forKey('billing')->onAttribute('countryCodeAlpha3');
1447
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED, $errors[0]->code);
1448
- }
1449
-
1450
- public function test_countryValidationError_incorrectNumericCode()
1451
- {
1452
- $result = Braintree\Transaction::sale([
1453
- 'amount' => '100.00',
1454
- 'creditCard' => [
1455
- 'number' => '5105105105105100',
1456
- 'expirationDate' => '05/12'
1457
- ],
1458
- 'billing' => [
1459
- 'countryCodeNumeric' => '000'
1460
- ]
1461
- ]);
1462
- $this->assertFalse($result->success);
1463
-
1464
- $errors = $result->errors->forKey('transaction')->forKey('billing')->onAttribute('countryCodeNumeric');
1465
- $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED, $errors[0]->code);
1466
- }
1467
-
1468
- public function testVoid_withValidationError()
1469
- {
1470
- $transaction = Braintree\Transaction::saleNoValidate([
1471
- 'amount' => '100.00',
1472
- 'creditCard' => [
1473
- 'number' => '5105105105105100',
1474
- 'expirationDate' => '05/12'
1475
- ]
1476
- ]);
1477
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1478
- $voided = Braintree\Transaction::voidNoValidate($transaction->id);
1479
- $this->assertEquals(Braintree\Transaction::VOIDED, $voided->status);
1480
- $result = Braintree\Transaction::void($transaction->id);
1481
- $this->assertEquals(false, $result->success);
1482
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1483
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_CANNOT_BE_VOIDED, $errors[0]->code);
1484
- }
1485
-
1486
- public function testVoidNoValidate()
1487
- {
1488
- $transaction = Braintree\Transaction::saleNoValidate([
1489
- 'amount' => '100.00',
1490
- 'creditCard' => [
1491
- 'number' => '5105105105105100',
1492
- 'expirationDate' => '05/12'
1493
- ]
1494
- ]);
1495
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1496
- $voided = Braintree\Transaction::voidNoValidate($transaction->id);
1497
- $this->assertEquals(Braintree\Transaction::VOIDED, $voided->status);
1498
- }
1499
-
1500
- public function testVoidNoValidate_throwsIfNotInvalid()
1501
- {
1502
- $transaction = Braintree\Transaction::saleNoValidate([
1503
- 'amount' => '100.00',
1504
- 'creditCard' => [
1505
- 'number' => '5105105105105100',
1506
- 'expirationDate' => '05/12'
1507
- ]
1508
- ]);
1509
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1510
- $voided = Braintree\Transaction::voidNoValidate($transaction->id);
1511
- $this->assertEquals(Braintree\Transaction::VOIDED, $voided->status);
1512
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
1513
- $voided = Braintree\Transaction::voidNoValidate($transaction->id);
1514
- }
1515
-
1516
- public function testFind()
1517
- {
1518
- $result = Braintree\Transaction::sale([
1519
- 'amount' => '100.00',
1520
- 'creditCard' => [
1521
- 'number' => '5105105105105100',
1522
- 'expirationDate' => '05/12'
1523
- ]
1524
- ]);
1525
- $transaction = Braintree\Transaction::find($result->transaction->id);
1526
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
1527
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
1528
- $this->assertEquals('100.00', $transaction->amount);
1529
- $this->assertEquals('510510', $transaction->creditCardDetails->bin);
1530
- $this->assertEquals('5100', $transaction->creditCardDetails->last4);
1531
- }
1532
-
1533
- public function testFindExposesDisbursementDetails()
1534
- {
1535
- $transaction = Braintree\Transaction::find("deposittransaction");
1536
-
1537
- $this->assertEquals(true, $transaction->isDisbursed());
1538
-
1539
- $disbursementDetails = $transaction->disbursementDetails;
1540
- $this->assertEquals('100.00', $disbursementDetails->settlementAmount);
1541
- $this->assertEquals('USD', $disbursementDetails->settlementCurrencyIsoCode);
1542
- $this->assertEquals('1', $disbursementDetails->settlementCurrencyExchangeRate);
1543
- $this->assertEquals(false, $disbursementDetails->fundsHeld);
1544
- $this->assertEquals(true, $disbursementDetails->success);
1545
- $this->assertEquals(new DateTime('2013-04-10'), $disbursementDetails->disbursementDate);
1546
- }
1547
-
1548
- public function testFindExposesDisputes()
1549
- {
1550
- $transaction = Braintree\Transaction::find("disputedtransaction");
1551
-
1552
- $dispute = $transaction->disputes[0];
1553
- $this->assertEquals('250.00', $dispute->amount);
1554
- $this->assertEquals('USD', $dispute->currencyIsoCode);
1555
- $this->assertEquals(Braintree\Dispute::FRAUD, $dispute->reason);
1556
- $this->assertEquals(Braintree\Dispute::WON, $dispute->status);
1557
- $this->assertEquals(new DateTime('2014-03-01'), $dispute->receivedDate);
1558
- $this->assertEquals(new DateTime('2014-03-21'), $dispute->replyByDate);
1559
- $this->assertEquals("disputedtransaction", $dispute->transactionDetails->id);
1560
- $this->assertEquals("1000.00", $dispute->transactionDetails->amount);
1561
- $this->assertEquals(Braintree\Dispute::CHARGEBACK, $dispute->kind);
1562
- $this->assertEquals(new DateTime('2014-03-01'), $dispute->dateOpened);
1563
- $this->assertEquals(new DateTime('2014-03-07'), $dispute->dateWon);
1564
- }
1565
-
1566
- public function testFindExposesThreeDSecureInfo()
1567
- {
1568
- $transaction = Braintree\Transaction::find("threedsecuredtransaction");
1569
-
1570
- $info = $transaction->threeDSecureInfo;
1571
- $this->assertEquals("Y", $info->enrolled);
1572
- $this->assertEquals("authenticate_successful", $info->status);
1573
- $this->assertTrue($info->liabilityShifted);
1574
- $this->assertTrue($info->liabilityShiftPossible);
1575
- }
1576
-
1577
- public function testFindExposesNullThreeDSecureInfo()
1578
- {
1579
- $transaction = Braintree\Transaction::find("settledtransaction");
1580
-
1581
- $this->assertNull($transaction->threeDSecureInfo);
1582
- }
1583
-
1584
- public function testFindExposesRetrievals()
1585
- {
1586
- $transaction = Braintree\Transaction::find("retrievaltransaction");
1587
-
1588
- $dispute = $transaction->disputes[0];
1589
- $this->assertEquals('1000.00', $dispute->amount);
1590
- $this->assertEquals('USD', $dispute->currencyIsoCode);
1591
- $this->assertEquals(Braintree\Dispute::RETRIEVAL, $dispute->reason);
1592
- $this->assertEquals(Braintree\Dispute::OPEN, $dispute->status);
1593
- $this->assertEquals("retrievaltransaction", $dispute->transactionDetails->id);
1594
- $this->assertEquals("1000.00", $dispute->transactionDetails->amount);
1595
- }
1596
-
1597
- public function testFindExposesPayPalDetails()
1598
- {
1599
- $transaction = Braintree\Transaction::find("settledtransaction");
1600
- $this->assertNotNull($transaction->paypalDetails->debugId);
1601
- $this->assertNotNull($transaction->paypalDetails->payerEmail);
1602
- $this->assertNotNull($transaction->paypalDetails->authorizationId);
1603
- $this->assertNotNull($transaction->paypalDetails->payerId);
1604
- $this->assertNotNull($transaction->paypalDetails->payerFirstName);
1605
- $this->assertNotNull($transaction->paypalDetails->payerLastName);
1606
- $this->assertNotNull($transaction->paypalDetails->sellerProtectionStatus);
1607
- $this->assertNotNull($transaction->paypalDetails->captureId);
1608
- $this->assertNotNull($transaction->paypalDetails->refundId);
1609
- $this->assertNotNull($transaction->paypalDetails->transactionFeeAmount);
1610
- $this->assertNotNull($transaction->paypalDetails->transactionFeeCurrencyIsoCode);
1611
- }
1612
-
1613
- public function testSale_storeInVault()
1614
- {
1615
- $transaction = Braintree\Transaction::saleNoValidate([
1616
- 'amount' => '100.00',
1617
- 'creditCard' => [
1618
- 'cardholderName' => 'Card Holder',
1619
- 'number' => '5105105105105100',
1620
- 'expirationDate' => '05/12',
1621
- ],
1622
- 'customer' => [
1623
- 'firstName' => 'Dan',
1624
- 'lastName' => 'Smith',
1625
- 'company' => 'Braintree',
1626
- 'email' => 'dan@example.com',
1627
- 'phone' => '419-555-1234',
1628
- 'fax' => '419-555-1235',
1629
- 'website' => 'http://getbraintree.com'
1630
- ],
1631
- 'options' => [
1632
- 'storeInVault' => true
1633
- ]
1634
- ]);
1635
- $this->assertNotNull($transaction->creditCardDetails->token);
1636
- $creditCard = $transaction->vaultCreditCard();
1637
- $this->assertEquals('510510', $creditCard->bin);
1638
- $this->assertEquals('5100', $creditCard->last4);
1639
- $this->assertEquals('05/2012', $creditCard->expirationDate);
1640
- $this->assertEquals('Card Holder', $creditCard->cardholderName);
1641
- $customer = $transaction->vaultCustomer();
1642
- $this->assertEquals('Dan', $customer->firstName);
1643
- $this->assertEquals('Smith', $customer->lastName);
1644
- $this->assertEquals('Braintree', $customer->company);
1645
- $this->assertEquals('dan@example.com', $customer->email);
1646
- $this->assertEquals('419-555-1234', $customer->phone);
1647
- $this->assertEquals('419-555-1235', $customer->fax);
1648
- $this->assertEquals('http://getbraintree.com', $customer->website);
1649
- }
1650
-
1651
- public function testSale_storeInVaultOnSuccessWithSuccessfulTransaction()
1652
- {
1653
- $transaction = Braintree\Transaction::saleNoValidate([
1654
- 'amount' => '100.00',
1655
- 'creditCard' => [
1656
- 'cardholderName' => 'Card Holder',
1657
- 'number' => '5105105105105100',
1658
- 'expirationDate' => '05/12',
1659
- ],
1660
- 'customer' => [
1661
- 'firstName' => 'Dan',
1662
- 'lastName' => 'Smith',
1663
- 'company' => 'Braintree',
1664
- 'email' => 'dan@example.com',
1665
- 'phone' => '419-555-1234',
1666
- 'fax' => '419-555-1235',
1667
- 'website' => 'http://getbraintree.com'
1668
- ],
1669
- 'options' => [
1670
- 'storeInVaultOnSuccess' => true
1671
- ]
1672
- ]);
1673
- $this->assertNotNull($transaction->creditCardDetails->token);
1674
- $creditCard = $transaction->vaultCreditCard();
1675
- $this->assertEquals('510510', $creditCard->bin);
1676
- $this->assertEquals('5100', $creditCard->last4);
1677
- $this->assertEquals('05/2012', $creditCard->expirationDate);
1678
- $this->assertEquals('Card Holder', $creditCard->cardholderName);
1679
- $customer = $transaction->vaultCustomer();
1680
- $this->assertEquals('Dan', $customer->firstName);
1681
- $this->assertEquals('Smith', $customer->lastName);
1682
- $this->assertEquals('Braintree', $customer->company);
1683
- $this->assertEquals('dan@example.com', $customer->email);
1684
- $this->assertEquals('419-555-1234', $customer->phone);
1685
- $this->assertEquals('419-555-1235', $customer->fax);
1686
- $this->assertEquals('http://getbraintree.com', $customer->website);
1687
- }
1688
-
1689
- public function testSale_storeInVaultOnSuccessWithFailedTransaction()
1690
- {
1691
- $result = Braintree\Transaction::sale([
1692
- 'amount' => Braintree\Test\TransactionAmounts::$decline,
1693
- 'creditCard' => [
1694
- 'cardholderName' => 'Card Holder',
1695
- 'number' => '5105105105105100',
1696
- 'expirationDate' => '05/12',
1697
- ],
1698
- 'customer' => [
1699
- 'firstName' => 'Dan',
1700
- 'lastName' => 'Smith',
1701
- 'company' => 'Braintree',
1702
- 'email' => 'dan@example.com',
1703
- 'phone' => '419-555-1234',
1704
- 'fax' => '419-555-1235',
1705
- 'website' => 'http://getbraintree.com'
1706
- ],
1707
- 'options' => [
1708
- 'storeInVaultOnSuccess' => true
1709
- ]
1710
- ]);
1711
- $transaction = $result->transaction;
1712
- $this->assertNull($transaction->creditCardDetails->token);
1713
- $this->assertNull($transaction->vaultCreditCard());
1714
- $this->assertNull($transaction->customerDetails->id);
1715
- $this->assertNull($transaction->vaultCustomer());
1716
- }
1717
-
1718
- public function testSale_withFraudParams()
1719
- {
1720
- $result = Braintree\Transaction::sale([
1721
- 'deviceSessionId' => '123abc',
1722
- 'fraudMerchantId' => '456',
1723
- 'amount' => '100.00',
1724
- 'creditCard' => [
1725
- 'number' => '5105105105105100',
1726
- 'expirationDate' => '05/12',
1727
- ]
1728
- ]);
1729
-
1730
- $this->assertTrue($result->success);
1731
- }
1732
-
1733
- public function testSale_withDescriptor()
1734
- {
1735
- $result = Braintree\Transaction::sale([
1736
- 'amount' => '100.00',
1737
- 'creditCard' => [
1738
- 'number' => '5105105105105100',
1739
- 'expirationDate' => '05/12',
1740
- ],
1741
- 'descriptor' => [
1742
- 'name' => '123*123456789012345678',
1743
- 'phone' => '3334445555',
1744
- 'url' => 'ebay.com'
1745
- ]
1746
- ]);
1747
- $this->assertTrue($result->success);
1748
- $transaction = $result->transaction;
1749
- $this->assertEquals('123*123456789012345678', $transaction->descriptor->name);
1750
- $this->assertEquals('3334445555', $transaction->descriptor->phone);
1751
- $this->assertEquals('ebay.com', $transaction->descriptor->url);
1752
- }
1753
-
1754
- public function testSale_withDescriptorValidation()
1755
- {
1756
- $result = Braintree\Transaction::sale([
1757
- 'amount' => '100.00',
1758
- 'creditCard' => [
1759
- 'number' => '5105105105105100',
1760
- 'expirationDate' => '05/12',
1761
- ],
1762
- 'descriptor' => [
1763
- 'name' => 'badcompanyname12*badproduct12',
1764
- 'phone' => '%bad4445555',
1765
- 'url' => '12345678901234'
1766
- ]
1767
- ]);
1768
- $this->assertFalse($result->success);
1769
- $transaction = $result->transaction;
1770
-
1771
- $errors = $result->errors->forKey('transaction')->forKey('descriptor')->onAttribute('name');
1772
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_NAME_FORMAT_IS_INVALID, $errors[0]->code);
1773
-
1774
- $errors = $result->errors->forKey('transaction')->forKey('descriptor')->onAttribute('phone');
1775
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_PHONE_FORMAT_IS_INVALID, $errors[0]->code);
1776
-
1777
- $errors = $result->errors->forKey('transaction')->forKey('descriptor')->onAttribute('url');
1778
- $this->assertEquals(Braintree\Error\Codes::DESCRIPTOR_URL_FORMAT_IS_INVALID, $errors[0]->code);
1779
- }
1780
-
1781
- public function testSale_withHoldInEscrow()
1782
- {
1783
- $result = Braintree\Transaction::sale([
1784
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
1785
- 'amount' => '100.00',
1786
- 'creditCard' => [
1787
- 'number' => '5105105105105100',
1788
- 'expirationDate' => '05/12'
1789
- ],
1790
- 'options' => [
1791
- 'holdInEscrow' => true
1792
- ],
1793
- 'serviceFeeAmount' => '1.00'
1794
- ]);
1795
- $this->assertTrue($result->success);
1796
- $transaction = $result->transaction;
1797
- $this->assertEquals(Braintree\Transaction::ESCROW_HOLD_PENDING, $transaction->escrowStatus);
1798
- }
1799
-
1800
- public function testSale_withHoldInEscrowFailsForMasterMerchantAccount()
1801
- {
1802
- $result = Braintree\Transaction::sale([
1803
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
1804
- 'amount' => '100.00',
1805
- 'creditCard' => [
1806
- 'number' => '5105105105105100',
1807
- 'expirationDate' => '05/12'
1808
- ],
1809
- 'options' => [
1810
- 'holdInEscrow' => true
1811
- ]
1812
- ]);
1813
- $this->assertFalse($result->success);
1814
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1815
- $this->assertEquals(
1816
- Braintree\Error\Codes::TRANSACTION_CANNOT_HOLD_IN_ESCROW,
1817
- $errors[0]->code
1818
- );
1819
- }
1820
-
1821
- public function testSale_withThreeDSecureOptionRequired()
1822
- {
1823
- $http = new HttpClientApi(Braintree\Configuration::$global);
1824
- $nonce = $http->nonce_for_new_card([
1825
- "creditCard" => [
1826
- "number" => "4111111111111111",
1827
- "expirationMonth" => "11",
1828
- "expirationYear" => "2099"
1829
- ]
1830
- ]);
1831
-
1832
- $result = Braintree\Transaction::sale([
1833
- 'merchantAccountId' => Test\Helper::threeDSecureMerchantAccountId(),
1834
- 'amount' => '100.00',
1835
- 'creditCard' => [
1836
- 'number' => '4111111111111111',
1837
- 'expirationDate' => '05/09'
1838
- ],
1839
- 'options' => [
1840
- 'three_d_secure' => [
1841
- 'required' => true
1842
- ]
1843
- ]
1844
- ]);
1845
- $this->assertFalse($result->success);
1846
- $this->assertEquals(Braintree\Transaction::THREE_D_SECURE, $result->transaction->gatewayRejectionReason);
1847
- }
1848
-
1849
- public function testSale_withThreeDSecureToken()
1850
- {
1851
- $threeDSecureToken = Test\Helper::create3DSVerification(
1852
- Test\Helper::threeDSecureMerchantAccountId(),
1853
- [
1854
- 'number' => '4111111111111111',
1855
- 'expirationMonth' => '05',
1856
- 'expirationYear' => '2009'
1857
- ]
1858
- );
1859
- $result = Braintree\Transaction::sale([
1860
- 'merchantAccountId' => Test\Helper::threeDSecureMerchantAccountId(),
1861
- 'amount' => '100.00',
1862
- 'creditCard' => [
1863
- 'number' => '4111111111111111',
1864
- 'expirationDate' => '05/09'
1865
- ],
1866
- 'threeDSecureToken' => $threeDSecureToken
1867
- ]);
1868
- $this->assertTrue($result->success);
1869
- }
1870
-
1871
- public function testSale_returnsErrorIfThreeDSecureToken()
1872
- {
1873
- $result = Braintree\Transaction::sale([
1874
- 'merchantAccountId' => Test\Helper::threeDSecureMerchantAccountId(),
1875
- 'amount' => '100.00',
1876
- 'creditCard' => [
1877
- 'number' => '4111111111111111',
1878
- 'expirationDate' => '05/09'
1879
- ],
1880
- 'threeDSecureToken' => NULL
1881
- ]);
1882
- $this->assertFalse($result->success);
1883
- $errors = $result->errors->forKey('transaction')->onAttribute('threeDSecureToken');
1884
- $this->assertEquals(
1885
- Braintree\Error\Codes::TRANSACTION_THREE_D_SECURE_TOKEN_IS_INVALID,
1886
- $errors[0]->code
1887
- );
1888
- }
1889
-
1890
- public function testSale_returnsErrorIf3dsLookupDataDoesNotMatchTransactionData()
1891
- {
1892
- $threeDSecureToken = Test\Helper::create3DSVerification(
1893
- Test\Helper::threeDSecureMerchantAccountId(),
1894
- [
1895
- 'number' => '4111111111111111',
1896
- 'expirationMonth' => '05',
1897
- 'expirationYear' => '2009'
1898
- ]
1899
- );
1900
-
1901
- $result = Braintree\Transaction::sale([
1902
- 'merchantAccountId' => Test\Helper::threeDSecureMerchantAccountId(),
1903
- 'amount' => '100.00',
1904
- 'creditCard' => [
1905
- 'number' => '5105105105105100',
1906
- 'expirationDate' => '05/09'
1907
- ],
1908
- 'threeDSecureToken' => $threeDSecureToken
1909
- ]);
1910
- $this->assertFalse($result->success);
1911
- $errors = $result->errors->forKey('transaction')->onAttribute('threeDSecureToken');
1912
- $this->assertEquals(
1913
- Braintree\Error\Codes::TRANSACTION_THREE_D_SECURE_TRANSACTION_DATA_DOESNT_MATCH_VERIFY,
1914
- $errors[0]->code
1915
- );
1916
- }
1917
-
1918
- public function testHoldInEscrow_afterSale()
1919
- {
1920
- $result = Braintree\Transaction::sale([
1921
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
1922
- 'amount' => '100.00',
1923
- 'creditCard' => [
1924
- 'number' => '5105105105105100',
1925
- 'expirationDate' => '05/12'
1926
- ],
1927
- 'serviceFeeAmount' => '1.00'
1928
- ]);
1929
- $result = Braintree\Transaction::holdInEscrow($result->transaction->id);
1930
- $this->assertTrue($result->success);
1931
- $this->assertEquals(Braintree\Transaction::ESCROW_HOLD_PENDING, $result->transaction->escrowStatus);
1932
- }
1933
-
1934
- public function testHoldInEscrow_afterSaleFailsWithMasterMerchantAccount()
1935
- {
1936
- $result = Braintree\Transaction::sale([
1937
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
1938
- 'amount' => '100.00',
1939
- 'creditCard' => [
1940
- 'number' => '5105105105105100',
1941
- 'expirationDate' => '05/12'
1942
- ]
1943
- ]);
1944
- $result = Braintree\Transaction::holdInEscrow($result->transaction->id);
1945
- $this->assertFalse($result->success);
1946
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1947
- $this->assertEquals(
1948
- Braintree\Error\Codes::TRANSACTION_CANNOT_HOLD_IN_ESCROW,
1949
- $errors[0]->code
1950
- );
1951
- }
1952
-
1953
- public function testSubmitForRelease_FromEscrow()
1954
- {
1955
- $transaction = $this->createEscrowedTransaction();
1956
- $result = Braintree\Transaction::releaseFromEscrow($transaction->id);
1957
- $this->assertTrue($result->success);
1958
- $this->assertEquals(Braintree\Transaction::ESCROW_RELEASE_PENDING, $result->transaction->escrowStatus);
1959
- }
1960
-
1961
- public function testSubmitForRelease_fromEscrowFailsForTransactionsNotHeldInEscrow()
1962
- {
1963
- $result = Braintree\Transaction::sale([
1964
- 'merchantAccountId' => Test\Helper::nonDefaultMerchantAccountId(),
1965
- 'amount' => '100.00',
1966
- 'creditCard' => [
1967
- 'number' => '5105105105105100',
1968
- 'expirationDate' => '05/12'
1969
- ]
1970
- ]);
1971
- $result = Braintree\Transaction::releaseFromEscrow($result->transaction->id);
1972
- $this->assertFalse($result->success);
1973
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1974
- $this->assertEquals(
1975
- Braintree\Error\Codes::TRANSACTION_CANNOT_RELEASE_FROM_ESCROW,
1976
- $errors[0]->code
1977
- );
1978
- }
1979
-
1980
- public function testCancelRelease_fromEscrow()
1981
- {
1982
- $transaction = $this->createEscrowedTransaction();
1983
- $result = Braintree\Transaction::releaseFromEscrow($transaction->id);
1984
- $result = Braintree\Transaction::cancelRelease($transaction->id);
1985
- $this->assertTrue($result->success);
1986
- $this->assertEquals(
1987
- Braintree\Transaction::ESCROW_HELD,
1988
- $result->transaction->escrowStatus
1989
- );
1990
- }
1991
-
1992
- public function testCancelRelease_fromEscrowFailsIfTransactionNotSubmittedForRelease()
1993
- {
1994
- $transaction = $this->createEscrowedTransaction();
1995
- $result = Braintree\Transaction::cancelRelease($transaction->id);
1996
- $this->assertFalse($result->success);
1997
- $errors = $result->errors->forKey('transaction')->onAttribute('base');
1998
- $this->assertEquals(
1999
- Braintree\Error\Codes::TRANSACTION_CANNOT_CANCEL_RELEASE,
2000
- $errors[0]->code
2001
- );
2002
- }
2003
-
2004
- public function testCreateFromTransparentRedirect()
2005
- {
2006
- Test\Helper::suppressDeprecationWarnings();
2007
- $queryString = $this->createTransactionViaTr(
2008
- [
2009
- 'transaction' => [
2010
- 'customer' => [
2011
- 'first_name' => 'First'
2012
- ],
2013
- 'credit_card' => [
2014
- 'number' => '5105105105105100',
2015
- 'expiration_date' => '05/12'
2016
- ]
2017
- ]
2018
- ],
2019
- [
2020
- 'transaction' => [
2021
- 'type' => Braintree\Transaction::SALE,
2022
- 'amount' => '100.00'
2023
- ]
2024
- ]
2025
- );
2026
- $result = Braintree\Transaction::createFromTransparentRedirect($queryString);
2027
- Test\Helper::assertPrintable($result);
2028
- $this->assertTrue($result->success);
2029
- $this->assertEquals('100.00', $result->transaction->amount);
2030
- $this->assertEquals(Braintree\Transaction::SALE, $result->transaction->type);
2031
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $result->transaction->status);
2032
- $creditCard = $result->transaction->creditCardDetails;
2033
- $this->assertEquals('510510', $creditCard->bin);
2034
- $this->assertEquals('5100', $creditCard->last4);
2035
- $this->assertEquals('US', $creditCard->customerLocation);
2036
- $this->assertEquals('MasterCard', $creditCard->cardType);
2037
- $this->assertEquals('05/2012', $creditCard->expirationDate);
2038
- $this->assertEquals('510510******5100', $creditCard->maskedNumber);
2039
- $customer = $result->transaction->customerDetails;
2040
- $this->assertequals('First', $customer->firstName);
2041
- }
2042
-
2043
- public function testCreateFromTransparentRedirectWithInvalidParams()
2044
- {
2045
- Test\Helper::suppressDeprecationWarnings();
2046
- $queryString = $this->createTransactionViaTr(
2047
- [
2048
- 'transaction' => [
2049
- 'bad_key' => 'bad_value',
2050
- 'customer' => [
2051
- 'first_name' => 'First'
2052
- ],
2053
- 'credit_card' => [
2054
- 'number' => '5105105105105100',
2055
- 'expiration_date' => '05/12'
2056
- ]
2057
- ]
2058
- ],
2059
- [
2060
- 'transaction' => [
2061
- 'type' => Braintree\Transaction::SALE,
2062
- 'amount' => '100.00'
2063
- ]
2064
- ]
2065
- );
2066
- try {
2067
- $result = Braintree\Transaction::createFromTransparentRedirect($queryString);
2068
- $this->fail();
2069
- } catch (Braintree\Exception\Authorization $e) {
2070
- $this->assertEquals("Invalid params: transaction[bad_key]", $e->getMessage());
2071
- }
2072
- }
2073
-
2074
- public function testCreateFromTransparentRedirect_withParamsInTrData()
2075
- {
2076
- Test\Helper::suppressDeprecationWarnings();
2077
- $queryString = $this->createTransactionViaTr(
2078
- [
2079
- ],
2080
- [
2081
- 'transaction' => [
2082
- 'type' => Braintree\Transaction::SALE,
2083
- 'amount' => '100.00',
2084
- 'customer' => [
2085
- 'firstName' => 'First'
2086
- ],
2087
- 'creditCard' => [
2088
- 'number' => '5105105105105100',
2089
- 'expirationDate' => '05/12'
2090
- ]
2091
- ]
2092
- ]
2093
- );
2094
- $result = Braintree\Transaction::createFromTransparentRedirect($queryString);
2095
- $this->assertTrue($result->success);
2096
- $this->assertEquals('100.00', $result->transaction->amount);
2097
- $this->assertEquals(Braintree\Transaction::SALE, $result->transaction->type);
2098
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $result->transaction->status);
2099
- $creditCard = $result->transaction->creditCardDetails;
2100
- $this->assertEquals('510510', $creditCard->bin);
2101
- $this->assertEquals('5100', $creditCard->last4);
2102
- $this->assertEquals('US', $creditCard->customerLocation);
2103
- $this->assertEquals('MasterCard', $creditCard->cardType);
2104
- $this->assertEquals('05/2012', $creditCard->expirationDate);
2105
- $this->assertEquals('510510******5100', $creditCard->maskedNumber);
2106
- $customer = $result->transaction->customerDetails;
2107
- $this->assertequals('First', $customer->firstName);
2108
- }
2109
-
2110
- public function testCreateFromTransparentRedirect_withValidationErrors()
2111
- {
2112
- Test\Helper::suppressDeprecationWarnings();
2113
- $queryString = $this->createTransactionViaTr(
2114
- [
2115
- 'transaction' => [
2116
- 'customer' => [
2117
- 'first_name' => str_repeat('x', 256),
2118
- ],
2119
- 'credit_card' => [
2120
- 'number' => 'invalid',
2121
- 'expiration_date' => ''
2122
- ]
2123
- ]
2124
- ],
2125
- [
2126
- 'transaction' => ['type' => Braintree\Transaction::SALE]
2127
- ]
2128
- );
2129
- $result = Braintree\Transaction::createFromTransparentRedirect($queryString);
2130
- $this->assertFalse($result->success);
2131
- $errors = $result->errors->forKey('transaction')->forKey('customer')->onAttribute('firstName');
2132
- $this->assertEquals(Braintree\Error\Codes::CUSTOMER_FIRST_NAME_IS_TOO_LONG, $errors[0]->code);
2133
- $errors = $result->errors->forKey('transaction')->forKey('creditCard')->onAttribute('number');
2134
- $this->assertTrue(count($errors) > 0);
2135
- $errors = $result->errors->forKey('transaction')->forKey('creditCard')->onAttribute('expirationDate');
2136
- $this->assertEquals(Braintree\Error\Codes::CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED, $errors[0]->code);
2137
- }
2138
-
2139
- public function testRefund()
2140
- {
2141
- $transaction = $this->createTransactionToRefund();
2142
- $result = Braintree\Transaction::refund($transaction->id);
2143
- $this->assertTrue($result->success);
2144
- $refund = $result->transaction;
2145
- $this->assertEquals(Braintree\Transaction::CREDIT, $refund->type);
2146
- $this->assertEquals($transaction->id, $refund->refundedTransactionId);
2147
- $this->assertEquals($refund->id, Braintree\Transaction::find($transaction->id)->refundId);
2148
- }
2149
-
2150
- public function testRefundWithPartialAmount()
2151
- {
2152
- $transaction = $this->createTransactionToRefund();
2153
- $result = Braintree\Transaction::refund($transaction->id, '50.00');
2154
- $this->assertTrue($result->success);
2155
- $this->assertEquals(Braintree\Transaction::CREDIT, $result->transaction->type);
2156
- $this->assertEquals("50.00", $result->transaction->amount);
2157
- }
2158
-
2159
- public function testMultipleRefundsWithPartialAmounts()
2160
- {
2161
- $transaction = $this->createTransactionToRefund();
2162
-
2163
- $transaction1 = Braintree\Transaction::refund($transaction->id, '50.00')->transaction;
2164
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction1->type);
2165
- $this->assertEquals("50.00", $transaction1->amount);
2166
-
2167
- $transaction2 = Braintree\Transaction::refund($transaction->id, '50.00')->transaction;
2168
- $this->assertEquals(Braintree\Transaction::CREDIT, $transaction2->type);
2169
- $this->assertEquals("50.00", $transaction2->amount);
2170
-
2171
- $transaction = Braintree\Transaction::find($transaction->id);
2172
-
2173
- $expectedRefundIds = [$transaction1->id, $transaction2->id];
2174
- $refundIds = $transaction->refundIds;
2175
- sort($expectedRefundIds);
2176
- sort($refundIds);
2177
-
2178
- $this->assertEquals($expectedRefundIds, $refundIds);
2179
- }
2180
-
2181
- public function testRefundWithUnsuccessfulPartialAmount()
2182
- {
2183
- $transaction = $this->createTransactionToRefund();
2184
- $result = Braintree\Transaction::refund($transaction->id, '150.00');
2185
- $this->assertFalse($result->success);
2186
- $errors = $result->errors->forKey('transaction')->onAttribute('amount');
2187
- $this->assertEquals(
2188
- Braintree\Error\Codes::TRANSACTION_REFUND_AMOUNT_IS_TOO_LARGE,
2189
- $errors[0]->code
2190
- );
2191
- }
2192
-
2193
- public function testGatewayRejectionOnApplicationIncomplete()
2194
- {
2195
- $gateway = new Braintree\Gateway([
2196
- 'clientId' => 'client_id$development$integration_client_id',
2197
- 'clientSecret' => 'client_secret$development$integration_client_secret'
2198
- ]);
2199
-
2200
- $result = $gateway->merchant()->create([
2201
- 'email' => 'name@email.com',
2202
- 'countryCodeAlpha3' => 'USA',
2203
- 'paymentMethods' => ['credit_card', 'paypal']
2204
- ]);
2205
-
2206
- $gateway = new Braintree\Gateway([
2207
- 'accessToken' => $result->credentials->accessToken,
2208
- ]);
2209
-
2210
- $result = $gateway->transaction()->sale([
2211
- 'amount' => '4000.00',
2212
- 'creditCard' => [
2213
- 'number' => '4111111111111111',
2214
- 'expirationDate' => '05/20'
2215
- ]
2216
- ]);
2217
- $this->assertFalse($result->success);
2218
- $transaction = $result->transaction;
2219
- $this->assertEquals(Braintree\Transaction::APPLICATION_INCOMPLETE, $transaction->gatewayRejectionReason);
2220
- }
2221
-
2222
- public function testGatewayRejectionOnAvs()
2223
- {
2224
- $old_merchant_id = Braintree\Configuration::merchantId();
2225
- $old_public_key = Braintree\Configuration::publicKey();
2226
- $old_private_key = Braintree\Configuration::privateKey();
2227
-
2228
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
2229
- Braintree\Configuration::publicKey('processing_rules_public_key');
2230
- Braintree\Configuration::privateKey('processing_rules_private_key');
2231
-
2232
- $result = Braintree\Transaction::sale([
2233
- 'amount' => '100.00',
2234
- 'billing' => [
2235
- 'streetAddress' => '200 2nd Street'
2236
- ],
2237
- 'creditCard' => [
2238
- 'number' => '5105105105105100',
2239
- 'expirationDate' => '05/12'
2240
- ]
2241
- ]);
2242
-
2243
- Braintree\Configuration::merchantId($old_merchant_id);
2244
- Braintree\Configuration::publicKey($old_public_key);
2245
- Braintree\Configuration::privateKey($old_private_key);
2246
-
2247
- $this->assertFalse($result->success);
2248
- Test\Helper::assertPrintable($result);
2249
- $transaction = $result->transaction;
2250
-
2251
- $this->assertEquals(Braintree\Transaction::AVS, $transaction->gatewayRejectionReason);
2252
- }
2253
-
2254
- public function testGatewayRejectionOnAvsAndCvv()
2255
- {
2256
- $old_merchant_id = Braintree\Configuration::merchantId();
2257
- $old_public_key = Braintree\Configuration::publicKey();
2258
- $old_private_key = Braintree\Configuration::privateKey();
2259
-
2260
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
2261
- Braintree\Configuration::publicKey('processing_rules_public_key');
2262
- Braintree\Configuration::privateKey('processing_rules_private_key');
2263
-
2264
- $result = Braintree\Transaction::sale([
2265
- 'amount' => '100.00',
2266
- 'billing' => [
2267
- 'postalCode' => '20000'
2268
- ],
2269
- 'creditCard' => [
2270
- 'number' => '5105105105105100',
2271
- 'expirationDate' => '05/12',
2272
- 'cvv' => '200'
2273
- ]
2274
- ]);
2275
-
2276
- Braintree\Configuration::merchantId($old_merchant_id);
2277
- Braintree\Configuration::publicKey($old_public_key);
2278
- Braintree\Configuration::privateKey($old_private_key);
2279
-
2280
- $this->assertFalse($result->success);
2281
- $transaction = $result->transaction;
2282
-
2283
- $this->assertEquals(Braintree\Transaction::AVS_AND_CVV, $transaction->gatewayRejectionReason);
2284
- }
2285
-
2286
- public function testGatewayRejectionOnCvv()
2287
- {
2288
- $old_merchant_id = Braintree\Configuration::merchantId();
2289
- $old_public_key = Braintree\Configuration::publicKey();
2290
- $old_private_key = Braintree\Configuration::privateKey();
2291
-
2292
- Braintree\Configuration::merchantId('processing_rules_merchant_id');
2293
- Braintree\Configuration::publicKey('processing_rules_public_key');
2294
- Braintree\Configuration::privateKey('processing_rules_private_key');
2295
-
2296
- $result = Braintree\Transaction::sale([
2297
- 'amount' => '100.00',
2298
- 'creditCard' => [
2299
- 'number' => '5105105105105100',
2300
- 'expirationDate' => '05/12',
2301
- 'cvv' => '200'
2302
- ]
2303
- ]);
2304
-
2305
- Braintree\Configuration::merchantId($old_merchant_id);
2306
- Braintree\Configuration::publicKey($old_public_key);
2307
- Braintree\Configuration::privateKey($old_private_key);
2308
-
2309
- $this->assertFalse($result->success);
2310
- $transaction = $result->transaction;
2311
-
2312
- $this->assertEquals(Braintree\Transaction::CVV, $transaction->gatewayRejectionReason);
2313
- }
2314
-
2315
- public function testGatewayRejectionOnFraud()
2316
- {
2317
- $result = Braintree\Transaction::sale([
2318
- 'amount' => '100.00',
2319
- 'creditCard' => [
2320
- 'number' => '4000111111111511',
2321
- 'expirationDate' => '05/17',
2322
- 'cvv' => '333'
2323
- ]
2324
- ]);
2325
-
2326
- $this->assertFalse($result->success);
2327
- $this->assertEquals(Braintree\Transaction::FRAUD, $result->transaction->gatewayRejectionReason);
2328
- }
2329
-
2330
- public function testSnapshotPlanIdAddOnsAndDiscountsFromSubscription()
2331
- {
2332
- $creditCard = SubscriptionHelper::createCreditCard();
2333
- $plan = SubscriptionHelper::triallessPlan();
2334
- $result = Braintree\Subscription::create([
2335
- 'paymentMethodToken' => $creditCard->token,
2336
- 'planId' => $plan['id'],
2337
- 'addOns' => [
2338
- 'add' => [
2339
- [
2340
- 'amount' => '11.00',
2341
- 'inheritedFromId' => 'increase_10',
2342
- 'quantity' => 2,
2343
- 'numberOfBillingCycles' => 5
2344
- ],
2345
- [
2346
- 'amount' => '21.00',
2347
- 'inheritedFromId' => 'increase_20',
2348
- 'quantity' => 3,
2349
- 'numberOfBillingCycles' => 6
2350
- ]
2351
- ],
2352
- ],
2353
- 'discounts' => [
2354
- 'add' => [
2355
- [
2356
- 'amount' => '7.50',
2357
- 'inheritedFromId' => 'discount_7',
2358
- 'quantity' => 2,
2359
- 'neverExpires' => true
2360
- ]
2361
- ]
2362
- ]
2363
- ]);
2364
-
2365
- $transaction = $result->subscription->transactions[0];
2366
-
2367
- $this->assertEquals($transaction->planId, $plan['id']);
2368
-
2369
- $addOns = $transaction->addOns;
2370
- SubscriptionHelper::sortModificationsById($addOns);
2371
-
2372
- $this->assertEquals($addOns[0]->amount, "11.00");
2373
- $this->assertEquals($addOns[0]->id, "increase_10");
2374
- $this->assertEquals($addOns[0]->quantity, 2);
2375
- $this->assertEquals($addOns[0]->numberOfBillingCycles, 5);
2376
- $this->assertFalse($addOns[0]->neverExpires);
2377
-
2378
- $this->assertEquals($addOns[1]->amount, "21.00");
2379
- $this->assertEquals($addOns[1]->id, "increase_20");
2380
- $this->assertEquals($addOns[1]->quantity, 3);
2381
- $this->assertEquals($addOns[1]->numberOfBillingCycles, 6);
2382
- $this->assertFalse($addOns[1]->neverExpires);
2383
-
2384
- $discounts = $transaction->discounts;
2385
- $this->assertEquals($discounts[0]->amount, "7.50");
2386
- $this->assertEquals($discounts[0]->id, "discount_7");
2387
- $this->assertEquals($discounts[0]->quantity, 2);
2388
- $this->assertEquals($discounts[0]->numberOfBillingCycles, null);
2389
- $this->assertTrue($discounts[0]->neverExpires);
2390
- }
2391
-
2392
- public function createTransactionViaTr($regularParams, $trParams)
2393
- {
2394
- Test\Helper::suppressDeprecationWarnings();
2395
- $trData = Braintree\TransparentRedirect::transactionData(
2396
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
2397
- );
2398
- return Test\Helper::submitTrRequest(
2399
- Braintree\Transaction::createTransactionUrl(),
2400
- $regularParams,
2401
- $trData
2402
- );
2403
- }
2404
-
2405
- public function createTransactionToRefund()
2406
- {
2407
- $transaction = Braintree\Transaction::saleNoValidate([
2408
- 'amount' => '100.00',
2409
- 'creditCard' => [
2410
- 'number' => '5105105105105100',
2411
- 'expirationDate' => '05/12'
2412
- ],
2413
- 'options' => ['submitForSettlement' => true]
2414
- ]);
2415
- Braintree\Test\Transaction::settle($transaction->id);
2416
- return $transaction;
2417
- }
2418
-
2419
- public function createEscrowedTransaction()
2420
- {
2421
- $result = Braintree\Transaction::sale([
2422
- 'merchantAccountId' => Test\Helper::nonDefaultSubMerchantAccountId(),
2423
- 'amount' => '100.00',
2424
- 'creditCard' => [
2425
- 'number' => '5105105105105100',
2426
- 'expirationDate' => '05/12'
2427
- ],
2428
- 'options' => [
2429
- 'holdInEscrow' => true
2430
- ],
2431
- 'serviceFeeAmount' => '1.00'
2432
- ]);
2433
- Test\Helper::escrow($result->transaction->id);
2434
- return $result->transaction;
2435
- }
2436
-
2437
- public function testCardTypeIndicators()
2438
- {
2439
- $transaction = Braintree\Transaction::saleNoValidate([
2440
- 'amount' => '100.00',
2441
- 'creditCard' => [
2442
- 'number' => CardTypeIndicators::PREPAID,
2443
- 'expirationDate' => '05/12',
2444
- ]
2445
- ]);
2446
-
2447
- $this->assertEquals(Braintree\CreditCard::PREPAID_YES, $transaction->creditCardDetails->prepaid);
2448
-
2449
- $prepaid_card_transaction = Braintree\Transaction::saleNoValidate([
2450
- 'amount' => '100.00',
2451
- 'creditCard' => [
2452
- 'number' => CardTypeIndicators::COMMERCIAL,
2453
- 'expirationDate' => '05/12',
2454
- ]
2455
- ]);
2456
-
2457
- $this->assertEquals(Braintree\CreditCard::COMMERCIAL_YES, $prepaid_card_transaction->creditCardDetails->commercial);
2458
-
2459
- $transaction = Braintree\Transaction::saleNoValidate([
2460
- 'amount' => '100.00',
2461
- 'creditCard' => [
2462
- 'number' => CardTypeIndicators::PAYROLL,
2463
- 'expirationDate' => '05/12',
2464
- ]
2465
- ]);
2466
-
2467
- $this->assertEquals(Braintree\CreditCard::PAYROLL_YES, $transaction->creditCardDetails->payroll);
2468
-
2469
- $transaction = Braintree\Transaction::saleNoValidate([
2470
- 'amount' => '100.00',
2471
- 'creditCard' => [
2472
- 'number' => CardTypeIndicators::HEALTHCARE,
2473
- 'expirationDate' => '05/12',
2474
- ]
2475
- ]);
2476
-
2477
- $this->assertEquals(Braintree\CreditCard::HEALTHCARE_YES, $transaction->creditCardDetails->healthcare);
2478
-
2479
- $transaction = Braintree\Transaction::saleNoValidate([
2480
- 'amount' => '100.00',
2481
- 'creditCard' => [
2482
- 'number' => CardTypeIndicators::DURBIN_REGULATED,
2483
- 'expirationDate' => '05/12',
2484
- ]
2485
- ]);
2486
-
2487
- $this->assertEquals(Braintree\CreditCard::DURBIN_REGULATED_YES, $transaction->creditCardDetails->durbinRegulated);
2488
-
2489
- $transaction = Braintree\Transaction::saleNoValidate([
2490
- 'amount' => '100.00',
2491
- 'creditCard' => [
2492
- 'number' => CardTypeIndicators::DEBIT,
2493
- 'expirationDate' => '05/12',
2494
- ]
2495
- ]);
2496
-
2497
- $this->assertEquals(Braintree\CreditCard::DEBIT_YES, $transaction->creditCardDetails->debit);
2498
-
2499
- $transaction = Braintree\Transaction::saleNoValidate([
2500
- 'amount' => '100.00',
2501
- 'creditCard' => [
2502
- 'number' => CardTypeIndicators::ISSUING_BANK,
2503
- 'expirationDate' => '05/12',
2504
- ]
2505
- ]);
2506
-
2507
- $this->assertEquals("NETWORK ONLY", $transaction->creditCardDetails->issuingBank);
2508
-
2509
- $transaction = Braintree\Transaction::saleNoValidate([
2510
- 'amount' => '100.00',
2511
- 'creditCard' => [
2512
- 'number' => CardTypeIndicators::COUNTRY_OF_ISSUANCE,
2513
- 'expirationDate' => '05/12',
2514
- ]
2515
- ]);
2516
-
2517
- $this->assertEquals("USA", $transaction->creditCardDetails->countryOfIssuance);
2518
- }
2519
-
2520
-
2521
- public function testCreate_withVaultedPayPal()
2522
- {
2523
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2524
- $customer = Braintree\Customer::createNoValidate();
2525
- $http = new HttpClientApi(Braintree\Configuration::$global);
2526
- $nonce = $http->nonceForPayPalAccount([
2527
- 'paypal_account' => [
2528
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2529
- 'token' => $paymentMethodToken
2530
- ]
2531
- ]);
2532
-
2533
- Braintree\PaymentMethod::create([
2534
- 'customerId' => $customer->id,
2535
- 'paymentMethodNonce' => $nonce
2536
- ]);
2537
- $result = Braintree\Transaction::sale([
2538
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2539
- 'paymentMethodToken' => $paymentMethodToken,
2540
- ]);
2541
- $this->assertTrue($result->success);
2542
- $transaction = $result->transaction;
2543
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2544
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2545
- $this->assertNotNull($transaction->paypalDetails->debugId);
2546
- }
2547
-
2548
- public function testCreate_withFuturePayPal()
2549
- {
2550
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2551
- $http = new HttpClientApi(Braintree\Configuration::$global);
2552
- $nonce = $http->nonceForPayPalAccount([
2553
- 'paypal_account' => [
2554
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2555
- 'token' => $paymentMethodToken
2556
- ]
2557
- ]);
2558
-
2559
- $result = Braintree\Transaction::sale([
2560
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2561
- 'paymentMethodNonce' => $nonce,
2562
- ]);
2563
-
2564
- $this->assertTrue($result->success);
2565
- $transaction = $result->transaction;
2566
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2567
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2568
- $this->assertNotNull($transaction->paypalDetails->debugId);
2569
- $this->setExpectedException('Braintree\Exception\NotFound');
2570
- Braintree\PaymentMethod::find($paymentMethodToken);
2571
- }
2572
-
2573
- public function testCreate_withPayeeEmail()
2574
- {
2575
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2576
- $http = new HttpClientApi(Braintree\Configuration::$global);
2577
- $nonce = $http->nonceForPayPalAccount([
2578
- 'paypal_account' => [
2579
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2580
- 'token' => $paymentMethodToken
2581
- ]
2582
- ]);
2583
-
2584
- $result = Braintree\Transaction::sale([
2585
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2586
- 'paymentMethodNonce' => $nonce,
2587
- 'paypalAccount' => [
2588
- 'payeeEmail' => 'payee@example.com'
2589
- ]
2590
- ]);
2591
-
2592
- $this->assertTrue($result->success);
2593
- $transaction = $result->transaction;
2594
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2595
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2596
- $this->assertNotNull($transaction->paypalDetails->debugId);
2597
- $this->assertNotNull($transaction->paypalDetails->payeeEmail);
2598
- $this->setExpectedException('Braintree\Exception\NotFound');
2599
- Braintree\PaymentMethod::find($paymentMethodToken);
2600
- }
2601
-
2602
- public function testCreate_withPayeeEmailInOptions()
2603
- {
2604
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2605
- $http = new HttpClientApi(Braintree\Configuration::$global);
2606
- $nonce = $http->nonceForPayPalAccount([
2607
- 'paypal_account' => [
2608
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2609
- 'token' => $paymentMethodToken
2610
- ]
2611
- ]);
2612
-
2613
- $result = Braintree\Transaction::sale([
2614
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2615
- 'paymentMethodNonce' => $nonce,
2616
- 'paypalAccount' => [],
2617
- 'options' => [
2618
- 'payeeEmail' => 'payee@example.com'
2619
- ]
2620
- ]);
2621
-
2622
- $this->assertTrue($result->success);
2623
- $transaction = $result->transaction;
2624
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2625
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2626
- $this->assertNotNull($transaction->paypalDetails->debugId);
2627
- $this->assertNotNull($transaction->paypalDetails->payeeEmail);
2628
- $this->setExpectedException('Braintree\Exception\NotFound');
2629
- Braintree\PaymentMethod::find($paymentMethodToken);
2630
- }
2631
-
2632
- public function testCreate_withPayeeEmailInOptionsPayPal()
2633
- {
2634
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2635
- $http = new HttpClientApi(Braintree\Configuration::$global);
2636
- $nonce = $http->nonceForPayPalAccount([
2637
- 'paypal_account' => [
2638
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2639
- 'token' => $paymentMethodToken
2640
- ]
2641
- ]);
2642
-
2643
- $result = Braintree\Transaction::sale([
2644
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2645
- 'paymentMethodNonce' => $nonce,
2646
- 'paypalAccount' => [],
2647
- 'options' => [
2648
- 'paypal' => [
2649
- 'payeeEmail' => 'payee@example.com'
2650
- ]
2651
- ]
2652
- ]);
2653
-
2654
- $this->assertTrue($result->success);
2655
- $transaction = $result->transaction;
2656
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2657
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2658
- $this->assertNotNull($transaction->paypalDetails->debugId);
2659
- $this->assertNotNull($transaction->paypalDetails->payeeEmail);
2660
- $this->setExpectedException('Braintree\Exception\NotFound');
2661
- Braintree\PaymentMethod::find($paymentMethodToken);
2662
- }
2663
-
2664
- public function testCreate_withPayPalCustomField()
2665
- {
2666
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2667
- $http = new HttpClientApi(Braintree\Configuration::$global);
2668
- $nonce = $http->nonceForPayPalAccount([
2669
- 'paypal_account' => [
2670
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2671
- 'token' => $paymentMethodToken
2672
- ]
2673
- ]);
2674
-
2675
- $result = Braintree\Transaction::sale([
2676
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2677
- 'paymentMethodNonce' => $nonce,
2678
- 'paypalAccount' => [],
2679
- 'options' => [
2680
- 'paypal' => [
2681
- 'customField' => 'custom field stuff'
2682
- ]
2683
- ]
2684
- ]);
2685
-
2686
- $this->assertTrue($result->success);
2687
- $transaction = $result->transaction;
2688
- $this->assertEquals('custom field stuff', $transaction->paypalDetails->customField);
2689
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2690
- $this->assertNotNull($transaction->paypalDetails->debugId);
2691
- $this->setExpectedException('Braintree\Exception\NotFound');
2692
- Braintree\PaymentMethod::find($paymentMethodToken);
2693
- }
2694
-
2695
- public function testCreate_withPayPalSupplementaryData()
2696
- {
2697
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2698
- $http = new HttpClientApi(Braintree\Configuration::$global);
2699
- $nonce = $http->nonceForPayPalAccount([
2700
- 'paypal_account' => [
2701
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2702
- 'token' => $paymentMethodToken
2703
- ]
2704
- ]);
2705
-
2706
- $result = Braintree\Transaction::sale([
2707
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2708
- 'paymentMethodNonce' => $nonce,
2709
- 'paypalAccount' => [],
2710
- 'options' => [
2711
- 'paypal' => [
2712
- 'supplementaryData' => [
2713
- 'key1' => 'value',
2714
- 'key2' => 'value'
2715
- ]
2716
- ]
2717
- ]
2718
- ]);
2719
-
2720
- // note - supplementary data is not returned in response
2721
- $this->assertTrue($result->success);
2722
- }
2723
-
2724
- public function testCreate_withPayPalDescription()
2725
- {
2726
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2727
- $http = new HttpClientApi(Braintree\Configuration::$global);
2728
- $nonce = $http->nonceForPayPalAccount([
2729
- 'paypal_account' => [
2730
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2731
- 'token' => $paymentMethodToken
2732
- ]
2733
- ]);
2734
-
2735
- $result = Braintree\Transaction::sale([
2736
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2737
- 'paymentMethodNonce' => $nonce,
2738
- 'paypalAccount' => [],
2739
- 'options' => [
2740
- 'paypal' => [
2741
- 'description' => 'Product description'
2742
- ]
2743
- ]
2744
- ]);
2745
-
2746
- $this->assertTrue($result->success);
2747
- $transaction = $result->transaction;
2748
- $this->assertEquals('Product description', $transaction->paypalDetails->description);
2749
- }
2750
-
2751
- public function testCreate_withPayPalReturnsPaymentInstrumentType()
2752
- {
2753
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2754
- $http = new HttpClientApi(Braintree\Configuration::$global);
2755
- $nonce = $http->nonceForPayPalAccount([
2756
- 'paypal_account' => [
2757
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2758
- 'token' => $paymentMethodToken
2759
- ]
2760
- ]);
2761
-
2762
- $result = Braintree\Transaction::sale([
2763
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2764
- 'paymentMethodNonce' => $nonce,
2765
- ]);
2766
-
2767
- $this->assertTrue($result->success);
2768
- $transaction = $result->transaction;
2769
- $this->assertEquals(Braintree\PaymentInstrumentType::PAYPAL_ACCOUNT, $transaction->paymentInstrumentType);
2770
- $this->assertNotNull($transaction->paypalDetails->debugId);
2771
- }
2772
-
2773
- public function testCreate_withFuturePayPalAndVault()
2774
- {
2775
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2776
- $http = new HttpClientApi(Braintree\Configuration::$global);
2777
- $nonce = $http->nonceForPayPalAccount([
2778
- 'paypal_account' => [
2779
- 'consent_code' => 'PAYPAL_CONSENT_CODE',
2780
- 'token' => $paymentMethodToken
2781
- ]
2782
- ]);
2783
-
2784
- $result = Braintree\Transaction::sale([
2785
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2786
- 'paymentMethodNonce' => $nonce,
2787
- 'options' => [
2788
- 'storeInVault' => true
2789
- ]
2790
- ]);
2791
-
2792
- $this->assertTrue($result->success);
2793
- $transaction = $result->transaction;
2794
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2795
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2796
- $this->assertNotNull($transaction->paypalDetails->debugId);
2797
- $foundPayPalAccount = Braintree\PaymentMethod::find($paymentMethodToken);
2798
- $this->assertEquals($paymentMethodToken, $foundPayPalAccount->token);
2799
- }
2800
-
2801
- public function testCreate_withOnetimePayPal()
2802
- {
2803
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2804
- $http = new HttpClientApi(Braintree\Configuration::$global);
2805
- $nonce = $http->nonceForPayPalAccount([
2806
- 'paypal_account' => [
2807
- 'access_token' => 'PAYPAL_ACCESS_TOKEN',
2808
- 'token' => $paymentMethodToken
2809
- ]
2810
- ]);
2811
-
2812
- $result = Braintree\Transaction::sale([
2813
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2814
- 'paymentMethodNonce' => $nonce,
2815
- ]);
2816
-
2817
- $this->assertTrue($result->success);
2818
- $transaction = $result->transaction;
2819
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2820
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2821
- $this->assertNotNull($transaction->paypalDetails->debugId);
2822
- $this->setExpectedException('Braintree\Exception\NotFound');
2823
- Braintree\PaymentMethod::find($paymentMethodToken);
2824
- }
2825
-
2826
- public function testCreate_withOnetimePayPalAndDoesNotVault()
2827
- {
2828
- $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand());
2829
- $http = new HttpClientApi(Braintree\Configuration::$global);
2830
- $nonce = $http->nonceForPayPalAccount([
2831
- 'paypal_account' => [
2832
- 'access_token' => 'PAYPAL_ACCESS_TOKEN',
2833
- 'token' => $paymentMethodToken
2834
- ]
2835
- ]);
2836
-
2837
- $result = Braintree\Transaction::sale([
2838
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2839
- 'paymentMethodNonce' => $nonce,
2840
- 'options' => [
2841
- 'storeInVault' => true
2842
- ]
2843
- ]);
2844
-
2845
- $this->assertTrue($result->success);
2846
- $transaction = $result->transaction;
2847
- $this->assertEquals('payer@example.com', $transaction->paypalDetails->payerEmail);
2848
- $this->assertNotNull($transaction->paypalDetails->imageUrl);
2849
- $this->assertNotNull($transaction->paypalDetails->debugId);
2850
- $this->setExpectedException('Braintree\Exception\NotFound');
2851
- Braintree\PaymentMethod::find($paymentMethodToken);
2852
- }
2853
-
2854
- public function testCreate_withPayPalAndSubmitForSettlement()
2855
- {
2856
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2857
- $result = Braintree\Transaction::sale([
2858
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2859
- 'paymentMethodNonce' => $nonce,
2860
- 'options' => [
2861
- 'submitForSettlement' => true
2862
- ]
2863
- ]);
2864
-
2865
- $this->assertTrue($result->success);
2866
- $transaction = $result->transaction;
2867
- $this->assertEquals(Braintree\Transaction::SETTLING, $transaction->status);
2868
- }
2869
-
2870
- public function testCreate_withPayPalHandlesBadUnvalidatedNonces()
2871
- {
2872
- $http = new HttpClientApi(Braintree\Configuration::$global);
2873
- $nonce = $http->nonceForPayPalAccount([
2874
- 'paypal_account' => [
2875
- 'access_token' => 'PAYPAL_ACCESS_TOKEN',
2876
- 'consent_code' => 'PAYPAL_CONSENT_CODE'
2877
- ]
2878
- ]);
2879
-
2880
- $result = Braintree\Transaction::sale([
2881
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2882
- 'paymentMethodNonce' => $nonce,
2883
- 'options' => [
2884
- 'submitForSettlement' => true
2885
- ]
2886
- ]);
2887
-
2888
- $this->assertFalse($result->success);
2889
- $errors = $result->errors->forKey('transaction')->forKey('paypalAccount')->errors;
2890
- $this->assertEquals(Braintree\Error\Codes::PAYPAL_ACCOUNT_CANNOT_HAVE_BOTH_ACCESS_TOKEN_AND_CONSENT_CODE, $errors[0]->code);
2891
- }
2892
-
2893
- public function testCreate_withPayPalHandlesNonExistentNonces()
2894
- {
2895
- $result = Braintree\Transaction::sale([
2896
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2897
- 'paymentMethodNonce' => 'NON_EXISTENT_NONCE',
2898
- 'options' => [
2899
- 'submitForSettlement' => true
2900
- ]
2901
- ]);
2902
- $this->assertFalse($result->success);
2903
- $errors = $result->errors->forKey('transaction')->errors;
2904
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_PAYMENT_METHOD_NONCE_UNKNOWN, $errors[0]->code);
2905
- }
2906
-
2907
- public function testVoid_withPayPal()
2908
- {
2909
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2910
-
2911
- $result = Braintree\Transaction::sale([
2912
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2913
- 'paymentMethodNonce' => $nonce
2914
- ]);
2915
-
2916
- $this->assertTrue($result->success);
2917
- $voided_transaction = Braintree\Transaction::voidNoValidate($result->transaction->id);
2918
- $this->assertEquals(Braintree\Transaction::VOIDED, $voided_transaction->status);
2919
- }
2920
-
2921
- public function testVoid_failsOnDeclinedPayPal()
2922
- {
2923
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2924
-
2925
- $result = Braintree\Transaction::sale([
2926
- 'amount' => Braintree\Test\TransactionAmounts::$decline,
2927
- 'paymentMethodNonce' => $nonce
2928
- ]);
2929
- $this->setExpectedException('Braintree\Exception\ValidationsFailed');
2930
- Braintree\Transaction::voidNoValidate($result->transaction->id);
2931
- }
2932
-
2933
- public function testRefund_withPayPal()
2934
- {
2935
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2936
-
2937
- $transactionResult = Braintree\Transaction::sale([
2938
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2939
- 'paymentMethodNonce' => $nonce,
2940
- 'options' => [
2941
- 'submitForSettlement' => true
2942
- ]
2943
- ]);
2944
-
2945
- $this->assertTrue($transactionResult->success);
2946
- Braintree\Test\Transaction::settle($transactionResult->transaction->id);
2947
-
2948
- $result = Braintree\Transaction::refund($transactionResult->transaction->id);
2949
- $this->assertTrue($result->success);
2950
- $this->assertEquals($result->transaction->type, Braintree\Transaction::CREDIT);
2951
- }
2952
-
2953
- public function testRefund_withPayPalAssignsRefundId()
2954
- {
2955
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2956
-
2957
- $transactionResult = Braintree\Transaction::sale([
2958
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2959
- 'paymentMethodNonce' => $nonce,
2960
- 'options' => [
2961
- 'submitForSettlement' => true
2962
- ]
2963
- ]);
2964
-
2965
- $this->assertTrue($transactionResult->success);
2966
- $originalTransaction = $transactionResult->transaction;
2967
- Braintree\Test\Transaction::settle($transactionResult->transaction->id);
2968
-
2969
- $result = Braintree\Transaction::refund($transactionResult->transaction->id);
2970
- $this->assertTrue($result->success);
2971
- $refundTransaction = $result->transaction;
2972
- $updatedOriginalTransaction = Braintree\Transaction::find($originalTransaction->id);
2973
- $this->assertEquals($refundTransaction->id, $updatedOriginalTransaction->refundId);
2974
- }
2975
-
2976
- public function testRefund_withPayPalAssignsRefundedTransactionId()
2977
- {
2978
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
2979
-
2980
- $transactionResult = Braintree\Transaction::sale([
2981
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
2982
- 'paymentMethodNonce' => $nonce,
2983
- 'options' => [
2984
- 'submitForSettlement' => true
2985
- ]
2986
- ]);
2987
-
2988
- $this->assertTrue($transactionResult->success);
2989
- $originalTransaction = $transactionResult->transaction;
2990
- Braintree\Test\Transaction::settle($transactionResult->transaction->id);
2991
-
2992
- $result = Braintree\Transaction::refund($transactionResult->transaction->id);
2993
- $this->assertTrue($result->success);
2994
- $refundTransaction = $result->transaction;
2995
- $this->assertEquals($refundTransaction->refundedTransactionId, $originalTransaction->id);
2996
- }
2997
-
2998
- public function testRefund_withPayPalFailsifAlreadyRefunded()
2999
- {
3000
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
3001
-
3002
- $transactionResult = Braintree\Transaction::sale([
3003
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
3004
- 'paymentMethodNonce' => $nonce,
3005
- 'options' => [
3006
- 'submitForSettlement' => true
3007
- ]
3008
- ]);
3009
-
3010
- $this->assertTrue($transactionResult->success);
3011
- Braintree\Test\Transaction::settle($transactionResult->transaction->id);
3012
-
3013
- $firstRefund = Braintree\Transaction::refund($transactionResult->transaction->id);
3014
- $this->assertTrue($firstRefund->success);
3015
- $secondRefund = Braintree\Transaction::refund($transactionResult->transaction->id);
3016
- $this->assertFalse($secondRefund->success);
3017
- $errors = $secondRefund->errors->forKey('transaction')->errors;
3018
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_HAS_ALREADY_BEEN_REFUNDED, $errors[0]->code);
3019
- }
3020
-
3021
- public function testRefund_withPayPalFailsIfNotSettled()
3022
- {
3023
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
3024
-
3025
- $transactionResult = Braintree\Transaction::sale([
3026
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
3027
- 'paymentMethodNonce' => $nonce,
3028
- ]);
3029
-
3030
- $this->assertTrue($transactionResult->success);
3031
-
3032
- $result = Braintree\Transaction::refund($transactionResult->transaction->id);
3033
- $this->assertFalse($result->success);
3034
- $errors = $result->errors->forKey('transaction')->errors;
3035
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED, $errors[0]->code);
3036
- }
3037
-
3038
- public function testRefund_partialWithPayPal()
3039
- {
3040
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
3041
-
3042
- $transactionResult = Braintree\Transaction::sale([
3043
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
3044
- 'paymentMethodNonce' => $nonce,
3045
- 'options' => [
3046
- 'submitForSettlement' => true
3047
- ]
3048
- ]);
3049
-
3050
- $this->assertTrue($transactionResult->success);
3051
- Braintree\Test\Transaction::settle($transactionResult->transaction->id);
3052
-
3053
- $result = Braintree\Transaction::refund(
3054
- $transactionResult->transaction->id,
3055
- $transactionResult->transaction->amount / 2
3056
- );
3057
-
3058
- $this->assertTrue($result->success);
3059
- $this->assertEquals($result->transaction->type, Braintree\Transaction::CREDIT);
3060
- $this->assertEquals($result->transaction->amount, $transactionResult->transaction->amount / 2);
3061
- }
3062
-
3063
- public function testRefund_multiplePartialWithPayPal()
3064
- {
3065
- $nonce = Braintree\Test\Nonces::$paypalOneTimePayment;
3066
-
3067
- $transactionResult = Braintree\Transaction::sale([
3068
- 'amount' => Braintree\Test\TransactionAmounts::$authorize,
3069
- 'paymentMethodNonce' => $nonce,
3070
- 'options' => [
3071
- 'submitForSettlement' => true
3072
- ]
3073
- ]);
3074
-
3075
- $this->assertTrue($transactionResult->success);
3076
- $originalTransaction = $transactionResult->transaction;
3077
- Braintree\Test\Transaction::settle($originalTransaction->id);
3078
-
3079
- $firstRefund = Braintree\Transaction::refund(
3080
- $transactionResult->transaction->id,
3081
- $transactionResult->transaction->amount / 2
3082
- );
3083
- $this->assertTrue($firstRefund->success);
3084
- $firstRefundTransaction = $firstRefund->transaction;
3085
-
3086
- $secondRefund = Braintree\Transaction::refund(
3087
- $transactionResult->transaction->id,
3088
- $transactionResult->transaction->amount / 2
3089
- );
3090
- $this->assertTrue($secondRefund->success);
3091
- $secondRefundTransaction = $secondRefund->transaction;
3092
-
3093
-
3094
- $updatedOriginalTransaction = Braintree\Transaction::find($originalTransaction->id);
3095
- $expectedRefundIds = [$secondRefundTransaction->id, $firstRefundTransaction->id];
3096
-
3097
- $updatedRefundIds = $updatedOriginalTransaction->refundIds;
3098
-
3099
- $this->assertTrue(in_array($expectedRefundIds[0],$updatedRefundIds));
3100
- $this->assertTrue(in_array($expectedRefundIds[1],$updatedRefundIds));
3101
- }
3102
-
3103
- public function testIncludeProcessorSettlementResponseForSettlementDeclinedTransaction()
3104
- {
3105
- $result = Braintree\Transaction::sale([
3106
- "paymentMethodNonce" => Braintree\Test\Nonces::$paypalFuturePayment,
3107
- "amount" => "100",
3108
- "options" => [
3109
- "submitForSettlement" => true
3110
- ]
3111
- ]);
3112
-
3113
- $this->assertTrue($result->success);
3114
-
3115
- $transaction = $result->transaction;
3116
- Braintree\Test\Transaction::settlementDecline($transaction->id);
3117
-
3118
- $inline_transaction = Braintree\Transaction::find($transaction->id);
3119
- $this->assertEquals($inline_transaction->status, Braintree\Transaction::SETTLEMENT_DECLINED);
3120
- $this->assertEquals($inline_transaction->processorSettlementResponseCode, "4001");
3121
- $this->assertEquals($inline_transaction->processorSettlementResponseText, "Settlement Declined");
3122
- }
3123
-
3124
- public function testIncludeProcessorSettlementResponseForSettlementPendingTransaction()
3125
- {
3126
- $result = Braintree\Transaction::sale([
3127
- "paymentMethodNonce" => Braintree\Test\Nonces::$paypalFuturePayment,
3128
- "amount" => "100",
3129
- "options" => [
3130
- "submitForSettlement" => true
3131
- ]
3132
- ]);
3133
-
3134
- $this->assertTrue($result->success);
3135
-
3136
- $transaction = $result->transaction;
3137
- Braintree\Test\Transaction::settlementPending($transaction->id);
3138
-
3139
- $inline_transaction = Braintree\Transaction::find($transaction->id);
3140
- $this->assertEquals($inline_transaction->status, Braintree\Transaction::SETTLEMENT_PENDING);
3141
- $this->assertEquals($inline_transaction->processorSettlementResponseCode, "4002");
3142
- $this->assertEquals($inline_transaction->processorSettlementResponseText, "Settlement Pending");
3143
- }
3144
-
3145
- public function testSale_withLodgingIndustryData()
3146
- {
3147
- $result = Braintree\Transaction::sale([
3148
- 'amount' => '100.00',
3149
- 'creditCard' => [
3150
- 'number' => '5105105105105100',
3151
- 'expirationDate' => '05/12',
3152
- ],
3153
- 'industry' => [
3154
- 'industryType' => Braintree\Transaction::LODGING_INDUSTRY,
3155
- 'data' => [
3156
- 'folioNumber' => 'aaa',
3157
- 'checkInDate' => '2014-07-07',
3158
- 'checkOutDate' => '2014-07-09',
3159
- 'roomRate' => '239.00'
3160
- ]
3161
- ]
3162
- ]);
3163
- $this->assertTrue($result->success);
3164
- }
3165
-
3166
- public function testSale_withLodgingIndustryDataValidation()
3167
- {
3168
- $result = Braintree\Transaction::sale([
3169
- 'amount' => '100.00',
3170
- 'creditCard' => [
3171
- 'number' => '5105105105105100',
3172
- 'expirationDate' => '05/12',
3173
- ],
3174
- 'industry' => [
3175
- 'industryType' => Braintree\Transaction::LODGING_INDUSTRY,
3176
- 'data' => [
3177
- 'folioNumber' => 'aaa',
3178
- 'checkInDate' => '2014-07-07',
3179
- 'checkOutDate' => '2014-06-09',
3180
- 'roomRate' => '239.00'
3181
- ]
3182
- ]
3183
- ]);
3184
- $this->assertFalse($result->success);
3185
- $transaction = $result->transaction;
3186
-
3187
- $errors = $result->errors->forKey('transaction')->forKey('industry')->onAttribute('checkOutDate');
3188
- $this->assertEquals(Braintree\Error\Codes::INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_MUST_FOLLOW_CHECK_IN_DATE, $errors[0]->code);
3189
- }
3190
-
3191
- public function testSale_withTravelCruiseIndustryData()
3192
- {
3193
- $result = Braintree\Transaction::sale([
3194
- 'amount' => '100.00',
3195
- 'creditCard' => [
3196
- 'number' => '5105105105105100',
3197
- 'expirationDate' => '05/12',
3198
- ],
3199
- 'industry' => [
3200
- 'industryType' => Braintree\Transaction::TRAVEL_AND_CRUISE_INDUSTRY,
3201
- 'data' => [
3202
- 'travelPackage' => 'flight',
3203
- 'departureDate' => '2014-07-07',
3204
- 'lodgingCheckInDate' => '2014-07-09',
3205
- 'lodgingCheckOutDate' => '2014-07-10',
3206
- 'lodgingName' => 'Disney',
3207
- ]
3208
- ]
3209
- ]);
3210
- $this->assertTrue($result->success);
3211
- }
3212
-
3213
- public function testSale_withTravelCruiseIndustryDataValidation()
3214
- {
3215
- $result = Braintree\Transaction::sale([
3216
- 'amount' => '100.00',
3217
- 'creditCard' => [
3218
- 'number' => '5105105105105100',
3219
- 'expirationDate' => '05/12',
3220
- ],
3221
- 'industry' => [
3222
- 'industryType' => Braintree\Transaction::TRAVEL_AND_CRUISE_INDUSTRY,
3223
- 'data' => [
3224
- 'travelPackage' => 'invalid',
3225
- 'departureDate' => '2014-07-07',
3226
- 'lodgingCheckInDate' => '2014-07-09',
3227
- 'lodgingCheckOutDate' => '2014-07-10',
3228
- 'lodgingName' => 'Disney',
3229
- ]
3230
- ]
3231
- ]);
3232
- $this->assertFalse($result->success);
3233
- $transaction = $result->transaction;
3234
-
3235
- $errors = $result->errors->forKey('transaction')->forKey('industry')->onAttribute('travelPackage');
3236
- $this->assertEquals(Braintree\Error\Codes::INDUSTRY_DATA_TRAVEL_CRUISE_TRAVEL_PACKAGE_IS_INVALID, $errors[0]->code);
3237
- }
3238
-
3239
- public function testSale_withAmexRewardsSucceeds()
3240
- {
3241
- $result = Braintree\Transaction::sale([
3242
- 'amount' => '47.00',
3243
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3244
- 'creditCard' => [
3245
- 'cardholderName' => 'The Cardholder',
3246
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['Success'],
3247
- 'expirationDate' => '05/12'
3248
- ],
3249
- 'options' => [
3250
- 'submitForSettlement' => true,
3251
- 'amexRewards' => [
3252
- 'requestId' => 'ABC123',
3253
- 'points' => '100',
3254
- 'currencyAmount' => '1.00',
3255
- 'currencyIsoCode' => 'USD'
3256
- ]
3257
- ]
3258
- ]);
3259
-
3260
- $this->assertTrue($result->success);
3261
- $transaction = $result->transaction;
3262
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $transaction->status);
3263
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3264
- }
3265
-
3266
- public function testSale_withAmexRewardsSucceedsEvenIfCardIsIneligible()
3267
- {
3268
- $result = Braintree\Transaction::sale([
3269
- 'amount' => '47.00',
3270
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3271
- 'creditCard' => [
3272
- 'cardholderName' => 'The Cardholder',
3273
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['IneligibleCard'],
3274
- 'expirationDate' => '05/12'
3275
- ],
3276
- 'options' => [
3277
- 'submitForSettlement' => true,
3278
- 'amexRewards' => [
3279
- 'requestId' => 'ABC123',
3280
- 'points' => '100',
3281
- 'currencyAmount' => '1.00',
3282
- 'currencyIsoCode' => 'USD'
3283
- ]
3284
- ]
3285
- ]);
3286
-
3287
- $this->assertTrue($result->success);
3288
- $transaction = $result->transaction;
3289
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $transaction->status);
3290
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3291
- }
3292
-
3293
- public function testSale_withAmexRewardsSucceedsEvenIfCardBalanceIsInsufficient()
3294
- {
3295
- $result = Braintree\Transaction::sale([
3296
- 'amount' => '47.00',
3297
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3298
- 'creditCard' => [
3299
- 'cardholderName' => 'The Cardholder',
3300
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['InsufficientPoints'],
3301
- 'expirationDate' => '05/12'
3302
- ],
3303
- 'options' => [
3304
- 'submitForSettlement' => true,
3305
- 'amexRewards' => [
3306
- 'requestId' => 'ABC123',
3307
- 'points' => '100',
3308
- 'currencyAmount' => '1.00',
3309
- 'currencyIsoCode' => 'USD'
3310
- ]
3311
- ]
3312
- ]);
3313
-
3314
- $this->assertTrue($result->success);
3315
- $transaction = $result->transaction;
3316
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $transaction->status);
3317
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3318
- }
3319
-
3320
- public function testSubmitForSettlement_withAmexRewardsSucceeds()
3321
- {
3322
- $result = Braintree\Transaction::sale([
3323
- 'amount' => '47.00',
3324
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3325
- 'creditCard' => [
3326
- 'cardholderName' => 'The Cardholder',
3327
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['Success'],
3328
- 'expirationDate' => '05/12'
3329
- ],
3330
- 'options' => [
3331
- 'amexRewards' => [
3332
- 'requestId' => 'ABC123',
3333
- 'points' => '100',
3334
- 'currencyAmount' => '1.00',
3335
- 'currencyIsoCode' => 'USD'
3336
- ]
3337
- ]
3338
- ]);
3339
-
3340
- $this->assertTrue($result->success);
3341
- $transaction = $result->transaction;
3342
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
3343
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3344
-
3345
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '47.00');
3346
- $submitTransaction = $submitResult->transaction;
3347
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitTransaction->status);
3348
- }
3349
-
3350
- public function testSubmitForSettlement_withAmexRewardsSucceedsEvenIfCardIsIneligible()
3351
- {
3352
- $result = Braintree\Transaction::sale([
3353
- 'amount' => '47.00',
3354
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3355
- 'creditCard' => [
3356
- 'cardholderName' => 'The Cardholder',
3357
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['IneligibleCard'],
3358
- 'expirationDate' => '05/12'
3359
- ],
3360
- 'options' => [
3361
- 'amexRewards' => [
3362
- 'requestId' => 'ABC123',
3363
- 'points' => '100',
3364
- 'currencyAmount' => '1.00',
3365
- 'currencyIsoCode' => 'USD'
3366
- ]
3367
- ]
3368
- ]);
3369
-
3370
- $this->assertTrue($result->success);
3371
- $transaction = $result->transaction;
3372
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
3373
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3374
-
3375
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '47.00');
3376
- $submitTransaction = $submitResult->transaction;
3377
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitTransaction->status);
3378
- }
3379
-
3380
- public function testSubmitForSettlement_withAmexRewardsSucceedsEvenIfCardBalanceIsInsufficient()
3381
- {
3382
- $result = Braintree\Transaction::sale([
3383
- 'amount' => '47.00',
3384
- 'merchantAccountId' => Test\Helper::fakeAmexDirectMerchantAccountId(),
3385
- 'creditCard' => [
3386
- 'cardholderName' => 'The Cardholder',
3387
- 'number' => Braintree\Test\CreditCardNumbers::$amexPayWithPoints['InsufficientPoints'],
3388
- 'expirationDate' => '05/12'
3389
- ],
3390
- 'options' => [
3391
- 'amexRewards' => [
3392
- 'requestId' => 'ABC123',
3393
- 'points' => '100',
3394
- 'currencyAmount' => '1.00',
3395
- 'currencyIsoCode' => 'USD'
3396
- ]
3397
- ]
3398
- ]);
3399
-
3400
- $this->assertTrue($result->success);
3401
- $transaction = $result->transaction;
3402
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
3403
- $this->assertEquals(Braintree\Transaction::SALE, $transaction->type);
3404
-
3405
- $submitResult = Braintree\Transaction::submitForSettlement($transaction->id, '47.00');
3406
- $submitTransaction = $submitResult->transaction;
3407
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitTransaction->status);
3408
- }
3409
-
3410
- public function testSubmitForPartialSettlement()
3411
- {
3412
- $authorizedTransaction = Braintree\Transaction::saleNoValidate([
3413
- 'amount' => '100.00',
3414
- 'creditCard' => [
3415
- 'number' => '5105105105105100',
3416
- 'expirationDate' => '05/12'
3417
- ]
3418
- ]);
3419
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $authorizedTransaction->status);
3420
- $partialSettlementResult1 = Braintree\Transaction::submitForPartialSettlement($authorizedTransaction->id, '60.00');
3421
- $this->assertTrue($partialSettlementResult1->success);
3422
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $partialSettlementResult1->transaction->status);
3423
- $this->assertEquals('60.00', $partialSettlementResult1->transaction->amount);
3424
-
3425
- $partialSettlementResult2 = Braintree\Transaction::submitForPartialSettlement($authorizedTransaction->id, '40.00');
3426
- $this->assertTrue($partialSettlementResult2->success);
3427
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $partialSettlementResult2->transaction->status);
3428
- $this->assertEquals('40.00', $partialSettlementResult2->transaction->amount);
3429
-
3430
- $refreshedAuthorizedTransaction = Braintree\Transaction::find($authorizedTransaction->id);
3431
- $this->assertEquals(2, count($refreshedAuthorizedTransaction->partialSettlementTransactionIds));
3432
- }
3433
-
3434
- public function testSubmitForPartialSettlementUnsuccesful()
3435
- {
3436
- $authorizedTransaction = Braintree\Transaction::saleNoValidate([
3437
- 'amount' => '100.00',
3438
- 'creditCard' => [
3439
- 'number' => '5105105105105100',
3440
- 'expirationDate' => '05/12'
3441
- ]
3442
- ]);
3443
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $authorizedTransaction->status);
3444
- $partialSettlementResult1 = Braintree\Transaction::submitForPartialSettlement($authorizedTransaction->id, '60.00');
3445
- $this->assertTrue($partialSettlementResult1->success);
3446
-
3447
- $partialSettlementResult2 = Braintree\Transaction::submitForPartialSettlement($partialSettlementResult1->transaction->id, '10.00');
3448
- $this->assertFalse($partialSettlementResult2->success);
3449
- $baseErrors = $partialSettlementResult2->errors->forKey('transaction')->onAttribute('base');
3450
- $this->assertEquals(Braintree\Error\Codes::TRANSACTION_CANNOT_SUBMIT_FOR_PARTIAL_SETTLEMENT, $baseErrors[0]->code);
3451
- }
3452
-
3453
- public function testSubmitForPartialSettlement_withOrderId()
3454
- {
3455
- $transaction = Braintree\Transaction::saleNoValidate([
3456
- 'amount' => '100.00',
3457
- 'creditCard' => [
3458
- 'number' => '5105105105105100',
3459
- 'expirationDate' => '05/12'
3460
- ]
3461
- ]);
3462
-
3463
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
3464
- $submitResult = Braintree\Transaction::submitForPartialSettlement($transaction->id, '67.00', ['orderId' => 'ABC123']);
3465
- $this->assertEquals(true, $submitResult->success);
3466
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
3467
- $this->assertEquals('ABC123', $submitResult->transaction->orderId);
3468
- $this->assertEquals('67.00', $submitResult->transaction->amount);
3469
- }
3470
-
3471
- public function testSubmitForPartialSettlement_withDescriptor()
3472
- {
3473
- $transaction = Braintree\Transaction::saleNoValidate([
3474
- 'amount' => '100.00',
3475
- 'creditCard' => [
3476
- 'number' => '5105105105105100',
3477
- 'expirationDate' => '05/12'
3478
- ]
3479
- ]);
3480
-
3481
- $params = [
3482
- 'descriptor' => [
3483
- 'name' => '123*123456789012345678',
3484
- 'phone' => '3334445555',
3485
- 'url' => 'ebay.com'
3486
- ]
3487
- ];
3488
-
3489
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $transaction->status);
3490
- $submitResult = Braintree\Transaction::submitForPartialSettlement($transaction->id, '67.00', $params);
3491
- $this->assertEquals(true, $submitResult->success);
3492
- $this->assertEquals(Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT, $submitResult->transaction->status);
3493
- $this->assertEquals('123*123456789012345678', $submitResult->transaction->descriptor->name);
3494
- $this->assertEquals('3334445555', $submitResult->transaction->descriptor->phone);
3495
- $this->assertEquals('ebay.com', $submitResult->transaction->descriptor->url);
3496
- }
3497
-
3498
- public function testSubmitForPartialSettlement_withInvalidParams()
3499
- {
3500
- $transaction = Braintree\Transaction::saleNoValidate([
3501
- 'amount' => '100.00',
3502
- 'creditCard' => [
3503
- 'number' => '5105105105105100',
3504
- 'expirationDate' => '05/12'
3505
- ]
3506
- ]);
3507
-
3508
- $params = ['invalid' => 'invalid'];
3509
-
3510
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: invalid');
3511
- Braintree\Transaction::submitForPartialSettlement($transaction->id, '67.00', $params);
3512
- }
3513
-
3514
- public function testFacilitatorDetailsAreReturnedOnTransactionsCreatedViaNonceGranting()
3515
- {
3516
- $partnerMerchantGateway = new Braintree\Gateway([
3517
- 'environment' => 'development',
3518
- 'merchantId' => 'integration_merchant_public_id',
3519
- 'publicKey' => 'oauth_app_partner_user_public_key',
3520
- 'privateKey' => 'oauth_app_partner_user_private_key'
3521
- ]);
3522
-
3523
- $customer = $partnerMerchantGateway->customer()->create([
3524
- 'firstName' => 'Joe',
3525
- 'lastName' => 'Brown'
3526
- ])->customer;
3527
- $creditCard = $partnerMerchantGateway->creditCard()->create([
3528
- 'customerId' => $customer->id,
3529
- 'cardholderName' => 'Adam Davis',
3530
- 'number' => '4111111111111111',
3531
- 'expirationDate' => '05/2009'
3532
- ])->creditCard;
3533
-
3534
- $oauthAppGateway = new Braintree\Gateway([
3535
- 'clientId' => 'client_id$development$integration_client_id',
3536
- 'clientSecret' => 'client_secret$development$integration_client_secret'
3537
- ]);
3538
-
3539
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
3540
- 'merchant_public_id' => 'integration_merchant_id',
3541
- 'scope' => 'grant_payment_method'
3542
- ]);
3543
-
3544
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
3545
- 'code' => $code,
3546
- ]);
3547
-
3548
- $grantingGateway = new Braintree\Gateway([
3549
- 'accessToken' => $credentials->accessToken
3550
- ]);
3551
-
3552
- $grantResult = $grantingGateway->paymentMethod()->grant($creditCard->token, false);
3553
-
3554
- $result = Braintree\Transaction::sale([
3555
- 'amount' => '100.00',
3556
- 'paymentMethodNonce' => $grantResult->paymentMethodNonce->nonce
3557
- ]);
3558
-
3559
- $this->assertEquals(
3560
- $result->transaction->facilitatorDetails->oauthApplicationClientId,
3561
- "client_id\$development\$integration_client_id"
3562
- );
3563
- $this->assertEquals(
3564
- $result->transaction->facilitatorDetails->oauthApplicationName,
3565
- "PseudoShop"
3566
- );
3567
- }
3568
-
3569
- public function testTransactionsCanBeCreatedWithSharedParams()
3570
- {
3571
- $partnerMerchantGateway = new Braintree\Gateway([
3572
- 'environment' => 'development',
3573
- 'merchantId' => 'integration_merchant_public_id',
3574
- 'publicKey' => 'oauth_app_partner_user_public_key',
3575
- 'privateKey' => 'oauth_app_partner_user_private_key'
3576
- ]);
3577
-
3578
- $customer = $partnerMerchantGateway->customer()->create([
3579
- 'firstName' => 'Joe',
3580
- 'lastName' => 'Brown'
3581
- ])->customer;
3582
- $address = $partnerMerchantGateway->address()->create([
3583
- 'customerId' => $customer->id,
3584
- 'firstName' => 'Dan',
3585
- 'lastName' => 'Smith',
3586
- ])->address;
3587
- $creditCard = $partnerMerchantGateway->creditCard()->create([
3588
- 'customerId' => $customer->id,
3589
- 'cardholderName' => 'Adam Davis',
3590
- 'number' => '4111111111111111',
3591
- 'expirationDate' => '05/2009'
3592
- ])->creditCard;
3593
-
3594
- $oauthAppGateway = new Braintree\Gateway([
3595
- 'clientId' => 'client_id$development$integration_client_id',
3596
- 'clientSecret' => 'client_secret$development$integration_client_secret'
3597
- ]);
3598
-
3599
- $code = Test\Braintree\OAuthTestHelper::createGrant($oauthAppGateway, [
3600
- 'merchant_public_id' => 'integration_merchant_id',
3601
- 'scope' => 'read_write,shared_vault_transactions'
3602
- ]);
3603
-
3604
- $credentials = $oauthAppGateway->oauth()->createTokenFromCode([
3605
- 'code' => $code,
3606
- ]);
3607
-
3608
- $oauthAccesTokenGateway = new Braintree\Gateway([
3609
- 'accessToken' => $credentials->accessToken
3610
- ]);
3611
-
3612
- $result = $oauthAccesTokenGateway->transaction()->sale([
3613
- 'amount' => '100.00',
3614
- 'sharedPaymentMethodToken' => $creditCard->token,
3615
- 'sharedCustomerId' => $customer->id,
3616
- 'sharedShippingAddressId' => $address->id,
3617
- 'sharedBillingAddressId' => $address->id
3618
- ]);
3619
-
3620
- $this->assertEquals(
3621
- $result->transaction->shippingDetails->firstName,
3622
- $address->firstName
3623
- );
3624
- $this->assertEquals(
3625
- $result->transaction->billingDetails->firstName,
3626
- $address->firstName
3627
- );
3628
- }
3629
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/integration/TransparentRedirectTest.php DELETED
@@ -1,354 +0,0 @@
1
- <?php
2
- namespace Test\Integration;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class TransparentRedirectTest extends Setup
11
- {
12
- public function testRedirectUrl()
13
- {
14
- Test\Helper::suppressDeprecationWarnings();
15
- $trData = Braintree\TransparentRedirect::createCustomerData(
16
- ["redirectUrl" => "http://www.example.com?foo=bar"]
17
- );
18
- $config = Braintree\Configuration::$global;
19
- $queryString = Test\Helper::submitTrRequest(
20
- $config->baseUrl() . $config->merchantPath() . '/test/maintenance',
21
- [],
22
- $trData
23
- );
24
- $this->setExpectedException('Braintree\Exception\DownForMaintenance');
25
- Braintree\Customer::createFromTransparentRedirect($queryString);
26
- }
27
-
28
- public function testParseAndValidateQueryString_throwsDownForMaintenanceErrorIfDownForMaintenance()
29
- {
30
- Test\Helper::suppressDeprecationWarnings();
31
- $trData = Braintree\TransparentRedirect::createCustomerData(
32
- ["redirectUrl" => "http://www.example.com"]
33
- );
34
- $config = Braintree\Configuration::$global;
35
- $queryString = Test\Helper::submitTrRequest(
36
- $config->baseUrl() . $config->merchantPath() . '/test/maintenance',
37
- [],
38
- $trData
39
- );
40
- $this->setExpectedException('Braintree\Exception\DownForMaintenance');
41
- Braintree\Customer::createFromTransparentRedirect($queryString);
42
- }
43
-
44
- public function testParseAndValidateQueryString_throwsAuthenticationErrorIfBadCredentials()
45
- {
46
- Test\Helper::suppressDeprecationWarnings();
47
- $privateKey = Braintree\Configuration::privateKey();
48
- Braintree\Configuration::privateKey('incorrect');
49
- try {
50
- $trData = Braintree\TransparentRedirect::createCustomerData(
51
- ["redirectUrl" => "http://www.example.com"]
52
- );
53
- $queryString = Test\Helper::submitTrRequest(
54
- Braintree\Customer::createCustomerUrl(),
55
- [],
56
- $trData
57
- );
58
- $this->setExpectedException('Braintree\Exception\Authentication');
59
- Braintree\Customer::createFromTransparentRedirect($queryString);
60
- } catch (Braintree\Exception $e) {
61
- }
62
- $privateKey = Braintree\Configuration::privateKey($privateKey);
63
- if (isset($e)) throw $e;
64
- }
65
-
66
- public function testCreateTransactionFromTransparentRedirect()
67
- {
68
- $params = [
69
- 'transaction' => [
70
- 'customer' => [
71
- 'first_name' => 'First'
72
- ],
73
- 'credit_card' => [
74
- 'number' => '5105105105105100',
75
- 'expiration_date' => '05/12'
76
- ]
77
- ]
78
- ];
79
- $trParams = [
80
- 'transaction' => [
81
- 'type' => Braintree\Transaction::SALE,
82
- 'amount' => '100.00'
83
- ]
84
- ];
85
-
86
- $trData = Braintree\TransparentRedirect::transactionData(
87
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
88
- );
89
-
90
- $queryString = Test\Helper::submitTrRequest(
91
- Braintree\TransparentRedirect::url(),
92
- $params,
93
- $trData
94
- );
95
-
96
- $result = Braintree\TransparentRedirect::confirm($queryString);
97
- $this->assertTrue($result->success);
98
- $this->assertEquals('100.00', $result->transaction->amount);
99
- $this->assertEquals(Braintree\Transaction::SALE, $result->transaction->type);
100
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $result->transaction->status);
101
- $creditCard = $result->transaction->creditCardDetails;
102
- $this->assertEquals('510510', $creditCard->bin);
103
- $this->assertEquals('5100', $creditCard->last4);
104
- $this->assertEquals('US', $creditCard->customerLocation);
105
- $this->assertEquals('MasterCard', $creditCard->cardType);
106
- $this->assertEquals('05/2012', $creditCard->expirationDate);
107
- $this->assertEquals('510510******5100', $creditCard->maskedNumber);
108
- $customer = $result->transaction->customerDetails;
109
- $this->assertequals('First', $customer->firstName);
110
- }
111
-
112
- public function testGatewayCreateTransactionFromTransparentRedirect()
113
- {
114
- $params = [
115
- 'transaction' => [
116
- 'customer' => [
117
- 'first_name' => 'First'
118
- ],
119
- 'credit_card' => [
120
- 'number' => '5105105105105100',
121
- 'expiration_date' => '05/12'
122
- ]
123
- ]
124
- ];
125
- $trParams = [
126
- 'transaction' => [
127
- 'type' => Braintree\Transaction::SALE,
128
- 'amount' => '100.00'
129
- ]
130
- ];
131
-
132
- $gateway = new Braintree\Gateway([
133
- 'environment' => 'development',
134
- 'merchantId' => 'integration_merchant_id',
135
- 'publicKey' => 'integration_public_key',
136
- 'privateKey' => 'integration_private_key'
137
- ]);
138
- $trData = $gateway->transparentRedirect()->transactionData(
139
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
140
- );
141
-
142
- $queryString = Test\Helper::submitTrRequest(
143
- $gateway->transparentRedirect()->url(),
144
- $params,
145
- $trData
146
- );
147
-
148
- $result = $gateway->transparentRedirect()->confirm($queryString);
149
- $this->assertTrue($result->success);
150
- $this->assertEquals('100.00', $result->transaction->amount);
151
- $this->assertEquals(Braintree\Transaction::SALE, $result->transaction->type);
152
- $this->assertEquals(Braintree\Transaction::AUTHORIZED, $result->transaction->status);
153
- $creditCard = $result->transaction->creditCardDetails;
154
- $this->assertEquals('US', $creditCard->customerLocation);
155
- $this->assertEquals('05/2012', $creditCard->expirationDate);
156
- $this->assertEquals('510510******5100', $creditCard->maskedNumber);
157
- $customer = $result->transaction->customerDetails;
158
- $this->assertequals('First', $customer->firstName);
159
- }
160
-
161
- public function testCreateTransactionWithServiceFeesFromTransparentRedirect()
162
- {
163
- $params = [
164
- 'transaction' => [
165
- 'customer' => [
166
- 'first_name' => 'First'
167
- ],
168
- 'credit_card' => [
169
- 'number' => '5105105105105100',
170
- 'expiration_date' => '05/12'
171
- ],
172
- 'service_fee_amount' => '1.00',
173
- 'merchant_account_id' => Test\Helper::nonDefaultSubMerchantAccountId(),
174
- ]
175
- ];
176
- $trParams = [
177
- 'transaction' => [
178
- 'type' => Braintree\Transaction::SALE,
179
- 'amount' => '100.00'
180
- ]
181
- ];
182
-
183
- $trData = Braintree\TransparentRedirect::transactionData(
184
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
185
- );
186
-
187
- $queryString = Test\Helper::submitTrRequest(
188
- Braintree\TransparentRedirect::url(),
189
- $params,
190
- $trData
191
- );
192
-
193
- $result = Braintree\TransparentRedirect::confirm($queryString);
194
- $this->assertTrue($result->success);
195
- $this->assertEquals('1.00', $result->transaction->serviceFeeAmount);
196
- }
197
-
198
- public function testCreateCustomerFromTransparentRedirect()
199
- {
200
- $params = [
201
- 'customer' => [
202
- 'first_name' => 'Second'
203
- ]
204
- ];
205
- $trParams = [
206
- 'customer' => [
207
- 'lastName' => 'Penultimate'
208
- ]
209
- ];
210
-
211
- $trData = Braintree\TransparentRedirect::createCustomerData(
212
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
213
- );
214
-
215
- $queryString = Test\Helper::submitTrRequest(
216
- Braintree\TransparentRedirect::url(),
217
- $params,
218
- $trData
219
- );
220
-
221
- $result = Braintree\TransparentRedirect::confirm($queryString);
222
- $this->assertTrue($result->success);
223
-
224
- $customer = $result->customer;
225
- $this->assertequals('Second', $customer->firstName);
226
- $this->assertequals('Penultimate', $customer->lastName);
227
- }
228
-
229
- public function testUpdateCustomerFromTransparentRedirect()
230
- {
231
- $customer = Braintree\Customer::create([
232
- 'firstName' => 'Mike',
233
- 'lastName' => 'Jonez'
234
- ])->customer;
235
- $params = [
236
- 'customer' => [
237
- 'first_name' => 'Second'
238
- ]
239
- ];
240
- $trParams = [
241
- 'customerId' => $customer->id,
242
- 'customer' => [
243
- 'lastName' => 'Penultimate'
244
- ]
245
- ];
246
-
247
- $trData = Braintree\TransparentRedirect::updateCustomerData(
248
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
249
- );
250
-
251
- $queryString = Test\Helper::submitTrRequest(
252
- Braintree\TransparentRedirect::url(),
253
- $params,
254
- $trData
255
- );
256
-
257
- $result = Braintree\TransparentRedirect::confirm($queryString);
258
- $this->assertTrue($result->success);
259
-
260
- $customer = $result->customer;
261
- $this->assertequals('Second', $customer->firstName);
262
- $this->assertequals('Penultimate', $customer->lastName);
263
- }
264
-
265
- public function testCreateCreditCardFromTransparentRedirect()
266
- {
267
- $customer = Braintree\Customer::create([
268
- 'firstName' => 'Mike',
269
- 'lastName' => 'Jonez'
270
- ])->customer;
271
-
272
- $params = [
273
- 'credit_card' => [
274
- 'number' => Braintree\Test\CreditCardNumbers::$visa
275
- ]
276
- ];
277
- $trParams = [
278
- 'creditCard' => [
279
- 'customerId' => $customer->id,
280
- 'expirationMonth' => '01',
281
- 'expirationYear' => '10'
282
- ]
283
- ];
284
-
285
- $trData = Braintree\TransparentRedirect::createCreditCardData(
286
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
287
- );
288
-
289
- $queryString = Test\Helper::submitTrRequest(
290
- Braintree\TransparentRedirect::url(),
291
- $params,
292
- $trData
293
- );
294
-
295
- $result = Braintree\TransparentRedirect::confirm($queryString);
296
- $this->assertTrue($result->success);
297
-
298
- $creditCard = $result->creditCard;
299
- $this->assertequals('401288', $creditCard->bin);
300
- $this->assertequals('1881', $creditCard->last4);
301
- $this->assertequals('01/2010', $creditCard->expirationDate);
302
- }
303
-
304
- public function testUpdateCreditCardFromTransparentRedirect()
305
- {
306
- $customer = Braintree\Customer::create([
307
- 'firstName' => 'Mike',
308
- 'lastName' => 'Jonez'
309
- ])->customer;
310
- $creditCard = Braintree\CreditCard::create([
311
- 'customerId' => $customer->id,
312
- 'number' => Braintree\Test\CreditCardNumbers::$masterCard,
313
- 'expirationMonth' => '10',
314
- 'expirationYear' => '10'
315
- ])->creditCard;
316
-
317
- $params = [
318
- 'credit_card' => [
319
- 'number' => Braintree\Test\CreditCardNumbers::$visa,
320
- ]
321
- ];
322
- $trParams = [
323
- 'paymentMethodToken' => $creditCard->token,
324
- 'creditCard' => [
325
- 'expirationMonth' => '11',
326
- 'expirationYear' => '11'
327
- ]
328
- ];
329
-
330
- $trData = Braintree\TransparentRedirect::updateCreditCardData(
331
- array_merge($trParams, ["redirectUrl" => "http://www.example.com"])
332
- );
333
-
334
- $queryString = Test\Helper::submitTrRequest(
335
- Braintree\TransparentRedirect::url(),
336
- $params,
337
- $trData
338
- );
339
-
340
- Braintree\TransparentRedirect::confirm($queryString);
341
-
342
- $creditCard = Braintree\CreditCard::find($creditCard->token);
343
- $this->assertequals('401288', $creditCard->bin);
344
- $this->assertequals('1881', $creditCard->last4);
345
- $this->assertequals('11/2011', $creditCard->expirationDate);
346
- }
347
-
348
- public function testUrl()
349
- {
350
- $url = Braintree\TransparentRedirect::url();
351
- $developmentPort = getenv("GATEWAY_PORT") ? getenv("GATEWAY_PORT") : 3000;
352
- $this->assertEquals("http://localhost:" . $developmentPort . "/merchants/integration_merchant_id/transparent_redirect_requests", $url);
353
- }
354
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/AddOnTest.php DELETED
@@ -1,34 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class AddOnTest extends Setup
10
- {
11
- public function testFactory()
12
- {
13
- $addOn = Braintree\AddOn::factory([]);
14
-
15
- $this->assertInstanceOf('Braintree\AddOn', $addOn);
16
- }
17
-
18
- public function testToString()
19
- {
20
- $addOnParams = [
21
- "amount" => "100.00",
22
- "description" => "some description",
23
- "id" => "1",
24
- "kind" => "add_on",
25
- "name" => "php_add_on",
26
- "neverExpires" => "false",
27
- "numberOfBillingCycles" => "1"
28
- ];
29
-
30
- $addOn = Braintree\AddOn::factory($addOnParams);
31
-
32
- $this->assertEquals("Braintree\AddOn[amount=100.00, description=some description, id=1, kind=add_on, name=php_add_on, neverExpires=false, numberOfBillingCycles=1]", (string) $addOn);
33
- }
34
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/AddressTest.php DELETED
@@ -1,79 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class AddressTest extends Setup
10
- {
11
- public function testGet_givesErrorIfInvalidProperty()
12
- {
13
- $this->setExpectedException('PHPUnit_Framework_Error', 'Undefined property on Braintree\Address: foo');
14
- $a = Braintree\Address::factory([]);
15
- $a->foo;
16
- }
17
-
18
- public function testIsEqual()
19
- {
20
- $first = Braintree\Address::factory(
21
- ['customerId' => 'c1', 'id' => 'a1']
22
- );
23
- $second = Braintree\Address::factory(
24
- ['customerId' => 'c1', 'id' => 'a1']
25
- );
26
-
27
- $this->assertTrue($first->isEqual($second));
28
- $this->assertTrue($second->isEqual($first));
29
-
30
- }
31
- public function testIsNotEqual() {
32
- $first = Braintree\Address::factory(
33
- ['customerId' => 'c1', 'id' => 'a1']
34
- );
35
- $second = Braintree\Address::factory(
36
- ['customerId' => 'c1', 'id' => 'not a1']
37
- );
38
-
39
- $this->assertFalse($first->isEqual($second));
40
- $this->assertFalse($second->isEqual($first));
41
- }
42
-
43
- public function testCustomerIdNotEqual()
44
- {
45
- $first = Braintree\Address::factory(
46
- ['customerId' => 'c1', 'id' => 'a1']
47
- );
48
- $second = Braintree\Address::factory(
49
- ['customerId' => 'not c1', 'id' => 'a1']
50
- );
51
-
52
- $this->assertFalse($first->isEqual($second));
53
- $this->assertFalse($second->isEqual($first));
54
- }
55
-
56
- public function testFindErrorsOnBlankCustomerId()
57
- {
58
- $this->setExpectedException('InvalidArgumentException');
59
- Braintree\Address::find('', '123');
60
- }
61
-
62
- public function testFindErrorsOnBlankAddressId()
63
- {
64
- $this->setExpectedException('InvalidArgumentException');
65
- Braintree\Address::find('123', '');
66
- }
67
-
68
- public function testFindErrorsOnWhitespaceOnlyId()
69
- {
70
- $this->setExpectedException('InvalidArgumentException');
71
- Braintree\Address::find('123', ' ');
72
- }
73
-
74
- public function testFindErrorsOnWhitespaceOnlyCustomerId()
75
- {
76
- $this->setExpectedException('InvalidArgumentException');
77
- Braintree\Address::find(' ', '123');
78
- }
79
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/BraintreeTest.php DELETED
@@ -1,25 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class BraintreeTest extends Setup
10
- {
11
- public function testIsset()
12
- {
13
- $t = Braintree\Transaction::factory([
14
- 'creditCard' => ['expirationMonth' => '05', 'expirationYear' => '2010', 'bin' => '510510', 'last4' => '5100'],
15
- 'customer' => [],
16
- 'billing' => [],
17
- 'descriptor' => [],
18
- 'shipping' => [],
19
- 'subscription' => ['billingPeriodStartDate' => '1983-07-12'],
20
- 'statusHistory' => [],
21
- ]);
22
- $this->assertTrue(isset($t->creditCard));
23
- $this->assertFalse(empty($t->creditCard));
24
- }
25
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/ClientApi/ClientTokenTest.php DELETED
@@ -1,22 +0,0 @@
1
- <?php
2
- namespace Test\Unit\ClientApi;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ClientTokenTest extends Setup
10
- {
11
- public function testErrorsWhenCreditCardOptionsGivenWithoutCustomerId()
12
- {
13
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: options[makeDefault]');
14
- Braintree\ClientToken::generate(["options" => ["makeDefault" => true]]);
15
- }
16
-
17
- public function testErrorsWhenInvalidArgumentIsSupplied()
18
- {
19
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: customrId');
20
- Braintree\ClientToken::generate(["customrId" => "1234"]);
21
- }
22
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/ConfigurationTest.php DELETED
@@ -1,417 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ConfigurationTest extends Setup
10
- {
11
- public function setup()
12
- {
13
- Braintree\Configuration::reset();
14
- $this->config = new Braintree\Configuration();
15
- }
16
-
17
- public function teardown()
18
- {
19
- Braintree\Configuration::environment('development');
20
- Braintree\Configuration::merchantId('integration_merchant_id');
21
- Braintree\Configuration::publicKey('integration_public_key');
22
- Braintree\Configuration::privateKey('integration_private_key');
23
- }
24
-
25
- public function testAssertGlobalHasAccessTokenOrKeys()
26
- {
27
- Braintree\Configuration::environment('development');
28
- Braintree\Configuration::merchantId('integration_merchant_id');
29
- Braintree\Configuration::publicKey('integration_public_key');
30
- Braintree\Configuration::privateKey('integration_private_key');
31
-
32
- try {
33
- Braintree\Configuration::assertGlobalHasAccessTokenOrKeys();
34
- } catch (Exception $notExpected) {
35
- $this->fail();
36
- }
37
-
38
- $this->assertTrue(TRUE);
39
- }
40
-
41
- /**
42
- * @expectedException Braintree\Exception\Configuration
43
- * @expectedExceptionMessage Configuration::publicKey needs to be set
44
- */
45
- public function testAssertGlobalHasAccessTokenOrKeysWithoutPublicKey()
46
- {
47
- Braintree\Configuration::environment('development');
48
- Braintree\Configuration::merchantId('integration_merchant_id');
49
- Braintree\Configuration::publicKey('');
50
- Braintree\Configuration::privateKey('integration_private_key');
51
-
52
- Braintree\Configuration::assertGlobalHasAccessTokenOrKeys();
53
- }
54
-
55
- public function testConstructWithArrayOfCredentials()
56
- {
57
- $config = new Braintree\Configuration([
58
- 'environment' => 'sandbox',
59
- 'merchantId' => 'sandbox_merchant_id',
60
- 'publicKey' => 'sandbox_public_key',
61
- 'privateKey' => 'sandbox_private_key',
62
- ]);
63
-
64
- $this->assertEquals('sandbox', $config->getEnvironment());
65
- $this->assertEquals('sandbox_merchant_id', $config->getMerchantId());
66
- }
67
-
68
- public function testSetValidEnvironment()
69
- {
70
- Braintree\Configuration::environment('sandbox');
71
- $this->assertEquals('sandbox', Braintree\Configuration::environment());
72
- Braintree\Configuration::reset();
73
- }
74
-
75
- /**
76
- * @expectedException Braintree\Exception\Configuration
77
- * @expectedExceptionMessage "invalid" is not a valid environment.
78
- */
79
- public function testSetInvalidEnvironment()
80
- {
81
- Braintree\Configuration::environment('invalid');
82
- Braintree\Configuration::reset();
83
- }
84
-
85
- public function testMerchantPath()
86
- {
87
- $this->config->setMerchantId('abc123');
88
- $mp = $this->config->merchantPath();
89
- $this->assertEquals('/merchants/abc123', $mp);
90
- }
91
-
92
- public function testCaFile()
93
- {
94
- $this->config->setEnvironment('development');
95
- $this->setExpectedException('Braintree\Exception\SSLCaFileNotFound');
96
- $this->config->caFile('/does/not/exist/');
97
- }
98
-
99
- public function testSSLOn()
100
- {
101
- $this->config->setEnvironment('development');
102
- $on = $this->config->sslOn();
103
- $this->assertFalse($on);
104
-
105
- $this->config->setEnvironment('sandbox');
106
- $on = $this->config->sslOn();
107
- $this->assertTrue($on);
108
-
109
- $this->config->setEnvironment('production');
110
- $on = $this->config->sslOn();
111
- $this->assertTrue($on);
112
- }
113
-
114
- public function testPortNumber()
115
- {
116
- $this->config->setEnvironment('development');
117
- $pn = $this->config->portNumber();
118
- $this->assertEquals(getenv("GATEWAY_PORT") ? getenv("GATEWAY_PORT") : 3000, $pn);
119
-
120
- $this->config->setEnvironment('sandbox');
121
- $pn = $this->config->portNumber();
122
- $this->assertEquals(443, $pn);
123
-
124
- $this->config->setEnvironment('production');
125
- $pn = $this->config->portNumber();
126
- $this->assertEquals(443, $pn);
127
- }
128
-
129
-
130
- public function testProtocol()
131
- {
132
- $this->config->setEnvironment('development');
133
- $p = $this->config->protocol();
134
- $this->assertEquals('http', $p);
135
-
136
- $this->config->setEnvironment('sandbox');
137
- $p = $this->config->protocol();
138
- $this->assertEquals('https', $p);
139
-
140
- $this->config->setEnvironment('production');
141
- $p = $this->config->protocol();
142
- $this->assertEquals('https', $p);
143
- }
144
-
145
- public function testServerName()
146
- {
147
- $this->config->setEnvironment('development');
148
- $sn = $this->config->serverName();
149
- $this->assertEquals('localhost', $sn);
150
-
151
- $this->config->setEnvironment('sandbox');
152
- $sn = $this->config->serverName();
153
- $this->assertEquals('api.sandbox.braintreegateway.com', $sn);
154
-
155
- $this->config->setEnvironment('production');
156
- $sn = $this->config->serverName();
157
- $this->assertEquals('api.braintreegateway.com', $sn);
158
- }
159
-
160
- public function testAuthUrl()
161
- {
162
- $this->config->setEnvironment('development');
163
- $authUrl = $this->config->authUrl();
164
- $this->assertEquals('http://auth.venmo.dev:9292', $authUrl);
165
-
166
- $this->config->setEnvironment('qa');
167
- $authUrl = $this->config->authUrl();
168
- $this->assertEquals('https://auth.qa.venmo.com', $authUrl);
169
-
170
- $this->config->setEnvironment('sandbox');
171
- $authUrl = $this->config->authUrl();
172
- $this->assertEquals('https://auth.sandbox.venmo.com', $authUrl);
173
-
174
- $this->config->setEnvironment('production');
175
- $authUrl = $this->config->authUrl();
176
- $this->assertEquals('https://auth.venmo.com', $authUrl);
177
- }
178
-
179
- public function testBaseUrl()
180
- {
181
- $this->config->setEnvironment('development');
182
- $bu = $this->config->baseUrl();
183
- $this->assertEquals('http://localhost:' . $this->config->portNumber(), $bu);
184
-
185
- $this->config->setEnvironment('qa');
186
- $bu = $this->config->baseUrl();
187
- $this->assertEquals('https://gateway.qa.braintreepayments.com:443', $bu);
188
-
189
- $this->config->setEnvironment('sandbox');
190
- $bu = $this->config->baseUrl();
191
- $this->assertEquals('https://api.sandbox.braintreegateway.com:443', $bu);
192
-
193
- $this->config->setEnvironment('production');
194
- $bu = $this->config->baseUrl();
195
- $this->assertEquals('https://api.braintreegateway.com:443', $bu);
196
- }
197
-
198
- function testProxyHost()
199
- {
200
- $this->config->proxyHost('example.com');
201
- $this->assertEquals('example.com', $this->config->proxyHost());
202
- }
203
-
204
- function testProxyPort()
205
- {
206
- $this->config->proxyPort('1234');
207
- $this->assertEquals('1234', $this->config->proxyPort());
208
- }
209
-
210
- function testProxyType()
211
- {
212
- $this->config->proxyType('MY_PROXY');
213
- $this->assertEquals('MY_PROXY', $this->config->proxyType());
214
- }
215
-
216
- function testProxyIsConfigured()
217
- {
218
- $this->config->proxyHost('example.com');
219
- $this->config->proxyPort('1234');
220
-
221
- $this->assertTrue($this->config->isUsingProxy());
222
- }
223
-
224
- /**
225
- * @expectedException Braintree\Exception\Configuration
226
- * @expectedExceptionMessage environment needs to be set
227
- */
228
- public function testValidateEmptyEnvironment()
229
- {
230
- //Braintree\Configuration::environment('development');
231
- Braintree\Configuration::merchantId('integration_merchant_id');
232
- Braintree\Configuration::publicKey('integration_public_key');
233
- Braintree\Configuration::privateKey('integration_private_key');
234
-
235
- Braintree\Configuration::$global->assertHasAccessTokenOrKeys();
236
- }
237
- /**
238
- * @expectedException Braintree\Exception\Configuration
239
- * @expectedExceptionMessage merchantId needs to be set
240
- */
241
- public function testMerchantId()
242
- {
243
- Braintree\Configuration::environment('development');
244
- //Braintree\Configuration::merchantId('integration_merchant_id');
245
- Braintree\Configuration::publicKey('integration_public_key');
246
- Braintree\Configuration::privateKey('integration_private_key');
247
-
248
- Braintree\Configuration::$global->assertHasAccessTokenOrKeys();
249
- }
250
- /**
251
- * @expectedException Braintree\Exception\Configuration
252
- * @expectedExceptionMessage publicKey needs to be set
253
- */
254
- public function testPublicKey()
255
- {
256
- Braintree\Configuration::environment('development');
257
- Braintree\Configuration::merchantId('integration_merchant_id');
258
- //Braintree\Configuration::publicKey('integration_public_key');
259
- Braintree\Configuration::privateKey('integration_private_key');
260
-
261
- Braintree\Configuration::$global->assertHasAccessTokenOrKeys();
262
- }
263
- /**
264
- * @expectedException Braintree\Exception\Configuration
265
- * @expectedExceptionMessage privateKey needs to be set
266
- */
267
- public function testPrivateKey()
268
- {
269
- Braintree\Configuration::environment('development');
270
- Braintree\Configuration::merchantId('integration_merchant_id');
271
- Braintree\Configuration::publicKey('integration_public_key');
272
- //Braintree\Configuration::privateKey('integration_private_key');
273
-
274
- Braintree\Configuration::$global->assertHasAccessTokenOrKeys();
275
- }
276
-
277
- public function testValidWithOAuthClientCredentials()
278
- {
279
- $config = new Braintree\Configuration([
280
- 'clientId' => 'client_id$development$integration_client_id',
281
- 'clientSecret' => 'client_secret$development$integration_client_secret'
282
- ]);
283
-
284
- $config->assertHasClientCredentials();
285
- }
286
-
287
- /**
288
- * @expectedException Braintree\Exception\Configuration
289
- * @expectedExceptionMessage clientSecret needs to be passed
290
- */
291
- public function testInvalidWithOAuthClientCredentials()
292
- {
293
- $config = new Braintree\Configuration([
294
- 'clientId' => 'client_id$development$integration_client_id'
295
- ]);
296
-
297
- $config->assertHasClientCredentials();
298
- }
299
-
300
- public function testDetectEnvironmentFromClientId()
301
- {
302
- $config = new Braintree\Configuration([
303
- 'clientId' => 'client_id$development$integration_client_id',
304
- 'clientSecret' => 'client_secret$development$integration_client_secret'
305
- ]);
306
-
307
- $this->assertEquals('development', $config->getEnvironment());
308
- }
309
-
310
- /**
311
- * @expectedException Braintree\Exception\Configuration
312
- * @expectedExceptionMessage Mismatched credential environments: clientId environment is sandbox and clientSecret environment is development
313
- */
314
- public function testDetectEnvironmentFromClientIdFail()
315
- {
316
- $config = new Braintree\Configuration([
317
- 'clientId' => 'client_id$sandbox$integration_client_id',
318
- 'clientSecret' => 'client_secret$development$integration_client_secret'
319
- ]);
320
- }
321
-
322
- /**
323
- * @expectedException Braintree\Exception\Configuration
324
- * @expectedExceptionMessage Value passed for clientId is not a clientId
325
- */
326
- public function testClientIdTypeFail()
327
- {
328
- $config = new Braintree\Configuration([
329
- 'clientId' => 'client_secret$development$integration_client_id',
330
- 'clientSecret' => 'client_secret$development$integration_client_secret'
331
- ]);
332
- }
333
-
334
- public function testValidWithAccessToken()
335
- {
336
- $config = new Braintree\Configuration([
337
- 'accessToken' => 'access_token$development$integration_merchant_id$integration_access_token',
338
- ]);
339
-
340
- $config->assertHasAccessTokenOrKeys();
341
- }
342
-
343
- /**
344
- * @expectedException Braintree\Exception\Configuration
345
- * @expectedExceptionMessage Value passed for accessToken is not an accessToken
346
- */
347
- public function testInvalidAccessTokenType()
348
- {
349
- $config = new Braintree\Configuration([
350
- 'accessToken' => 'client_id$development$integration_merchant_id$integration_access_token',
351
- ]);
352
- }
353
-
354
- /**
355
- * @expectedException Braintree\Exception\Configuration
356
- * @expectedExceptionMessage Incorrect accessToken syntax. Expected: type$environment$merchant_id$token
357
- */
358
- public function testInvalidAccessTokenSyntax()
359
- {
360
- $config = new Braintree\Configuration([
361
- 'accessToken' => 'client_id$development$integration_client_id',
362
- ]);
363
- }
364
-
365
- /**
366
- * @expectedException Braintree\Exception\Configuration
367
- * @expectedExceptionMessage "invalid" is not a valid environment.
368
- */
369
- public function testInvalidAccessTokenEnvironment()
370
- {
371
- $config = new Braintree\Configuration([
372
- 'accessToken' => 'access_token$invalid$integration_merchant_id$integration_access_token',
373
- ]);
374
- }
375
-
376
-
377
- public function testValidWithOAuthClientCredentialsAndAccessToken()
378
- {
379
- $config = new Braintree\Configuration([
380
- 'clientId' => 'client_id$development$integration_client_id',
381
- 'clientSecret' => 'client_secret$development$integration_client_secret',
382
- 'accessToken' => 'access_token$development$integration_merchant_id$integration_access_token',
383
- ]);
384
-
385
- $config->assertHasClientCredentials();
386
- $config->assertHasAccessTokenOrKeys();
387
- }
388
-
389
- /**
390
- * @expectedException Braintree\Exception\Configuration
391
- * @expectedExceptionMessage Mismatched credential environments: clientId environment is development and accessToken environment is sandbox
392
- */
393
- public function testInvalidEnvironmentWithOAuthClientCredentialsAndAccessToken()
394
- {
395
- $config = new Braintree\Configuration([
396
- 'clientId' => 'client_id$development$integration_client_id',
397
- 'clientSecret' => 'client_secret$development$integration_client_secret',
398
- 'accessToken' => 'access_token$sandbox$integration_merchant_id$integration_access_token',
399
- ]);
400
- }
401
-
402
- /**
403
- * @expectedException Braintree\Exception\Configuration
404
- * @expectedExceptionMessage Cannot mix OAuth credentials (clientId, clientSecret, accessToken) with key credentials (publicKey, privateKey, environment, merchantId)
405
- */
406
- public function testCannotMixKeysWithOAuthCredentials()
407
- {
408
- $config = new Braintree\Configuration([
409
- 'clientId' => 'client_id$development$integration_client_id',
410
- 'clientSecret' => 'client_secret$development$integration_client_secret',
411
- 'environment' => 'development',
412
- 'merchantId' => 'integration_merchant_id',
413
- 'publicKey' => 'integration_public_key',
414
- 'privateKey' => 'integration_private_key'
415
- ]);
416
- }
417
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/CreditCardTest.php DELETED
@@ -1,141 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class CreditCardTest extends Setup
11
- {
12
- public function testGet_givesErrorIfInvalidProperty()
13
- {
14
- $this->setExpectedException('PHPUnit_Framework_Error', 'Undefined property on Braintree\CreditCard: foo');
15
- $cc = Braintree\CreditCard::factory([]);
16
- $cc->foo;
17
- }
18
-
19
- public function testCreate_throwsIfInvalidKey()
20
- {
21
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: invalidKey');
22
- Braintree\CreditCard::create(['invalidKey' => 'foo']);
23
- }
24
-
25
- public function testIsDefault()
26
- {
27
- $creditCard = Braintree\CreditCard::factory(['default' => true]);
28
- $this->assertTrue($creditCard->isDefault());
29
-
30
- $creditCard = Braintree\CreditCard::factory(['default' => false]);
31
- $this->assertFalse($creditCard->isDefault());
32
- }
33
-
34
- public function testMaskedNumber()
35
- {
36
- $creditCard = Braintree\CreditCard::factory(['bin' => '123456', 'last4' => '7890']);
37
- $this->assertEquals('123456******7890', $creditCard->maskedNumber);
38
- }
39
-
40
- public function testCreateSignature()
41
- {
42
- $expected = [
43
- 'billingAddressId', 'cardholderName', 'cvv', 'number', 'deviceSessionId',
44
- 'expirationDate', 'expirationMonth', 'expirationYear', 'token', 'venmoSdkPaymentMethodCode',
45
- 'deviceData', 'fraudMerchantId', 'paymentMethodNonce',
46
- ['options' => ['makeDefault', 'verificationMerchantAccountId', 'verifyCard', 'verificationAmount', 'venmoSdkSession', 'failOnDuplicatePaymentMethod']],
47
- [
48
- 'billingAddress' => [
49
- 'firstName',
50
- 'lastName',
51
- 'company',
52
- 'countryCodeAlpha2',
53
- 'countryCodeAlpha3',
54
- 'countryCodeNumeric',
55
- 'countryName',
56
- 'extendedAddress',
57
- 'locality',
58
- 'region',
59
- 'postalCode',
60
- 'streetAddress',
61
- ],
62
- ],
63
- 'customerId'
64
- ];
65
- $this->assertEquals($expected, Braintree\CreditCardGateway::createSignature());
66
- }
67
-
68
- public function testUpdateSignature()
69
- {
70
- $expected = [
71
- 'billingAddressId', 'cardholderName', 'cvv', 'number', 'deviceSessionId',
72
- 'expirationDate', 'expirationMonth', 'expirationYear', 'token', 'venmoSdkPaymentMethodCode',
73
- 'deviceData', 'fraudMerchantId', 'paymentMethodNonce',
74
- ['options' => ['makeDefault', 'verificationMerchantAccountId', 'verifyCard', 'verificationAmount', 'venmoSdkSession']],
75
- [
76
- 'billingAddress' => [
77
- 'firstName',
78
- 'lastName',
79
- 'company',
80
- 'countryCodeAlpha2',
81
- 'countryCodeAlpha3',
82
- 'countryCodeNumeric',
83
- 'countryName',
84
- 'extendedAddress',
85
- 'locality',
86
- 'region',
87
- 'postalCode',
88
- 'streetAddress',
89
- [
90
- 'options' => [
91
- 'updateExisting'
92
- ]
93
- ]
94
- ],
95
- ],
96
- ];
97
- $this->assertEquals($expected, Braintree\CreditCardGateway::updateSignature());
98
- }
99
-
100
- public function testErrorsOnFindWithBlankArgument()
101
- {
102
- $this->setExpectedException('InvalidArgumentException');
103
- Braintree\CreditCard::find('');
104
- }
105
-
106
- public function testErrorsOnFindWithWhitespaceArgument()
107
- {
108
- $this->setExpectedException('InvalidArgumentException');
109
- Braintree\CreditCard::find(' ');
110
- }
111
-
112
- public function testErrorsOnFindWithWhitespaceCharacterArgument()
113
- {
114
- $this->setExpectedException('InvalidArgumentException');
115
- Braintree\CreditCard::find('\t');
116
- }
117
-
118
- public function testVerificationIsLatestVerification()
119
- {
120
- $creditCard = Braintree\CreditCard::factory(
121
- [
122
- 'verifications' => [
123
- [
124
- 'id' => '123',
125
- 'createdAt' => DateTime::createFromFormat('Ymd', '20121212')
126
- ],
127
- [
128
- 'id' => '932',
129
- 'createdAt' => DateTime::createFromFormat('Ymd', '20121215')
130
- ],
131
- [
132
- 'id' => '456',
133
- 'createdAt' => DateTime::createFromFormat('Ymd', '20121213')
134
- ]
135
- ]
136
- ]
137
- );
138
-
139
- $this->assertEquals('932', $creditCard->verification->id);
140
- }
141
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/CreditCardVerificationTest.php DELETED
@@ -1,22 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class CreditCardVerificationTest extends Setup
10
- {
11
- public function test_createWithInvalidArguments()
12
- {
13
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: invalidProperty');
14
- Braintree\CreditCardVerification::create(['options' => ['amount' => '123.45'], 'invalidProperty' => 'foo']);
15
- }
16
-
17
- public function test_createWithPaymentMethodArguments()
18
- {
19
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: creditCard[venmoSdkPaymentMethodCode]');
20
- Braintree\CreditCardVerification::create(['options' => ['amount' => '123.45'], 'creditCard' => ['venmoSdkPaymentMethodCode' => 'foo']]);
21
- }
22
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/CustomerTest.php DELETED
@@ -1,59 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class CustomerTest extends Setup
10
- {
11
- public function testGet_givesErrorIfInvalidProperty()
12
- {
13
- $this->setExpectedException('PHPUnit_Framework_Error', 'Undefined property on Braintree\Customer: foo');
14
- $c = Braintree\Customer::factory([]);
15
- $c->foo;
16
- }
17
-
18
- public function testUpdateSignature_doesNotAlterOptionsInCreditCardUpdateSignature()
19
- {
20
- Braintree\CustomerGateway::updateSignature();
21
- foreach (Braintree\CreditCardGateway::updateSignature() as $key => $value) {
22
- if(is_array($value) and array_key_exists('options', $value)) {
23
- $this->assertEquals([
24
- 'makeDefault',
25
- 'verificationMerchantAccountId',
26
- 'verifyCard',
27
- 'verificationAmount',
28
- 'venmoSdkSession'
29
- ], $value['options']);
30
- }
31
- }
32
- }
33
-
34
- public function testCreateSignature_doesNotIncludeCustomerIdOnCreditCard()
35
- {
36
- $signature = Braintree\CustomerGateway::createSignature();
37
- $creditCardSignatures = array_filter($signature, 'Test\Unit\CustomerTest::findCreditCardArray');
38
- $creditCardSignature = array_shift($creditCardSignatures)['creditCard'];
39
-
40
- $this->assertNotContains('customerId', $creditCardSignature);
41
- }
42
-
43
- public function findCreditCardArray($el)
44
- {
45
- return is_array($el) && array_key_exists('creditCard', $el);
46
- }
47
-
48
- public function testFindErrorsOnBlankId()
49
- {
50
- $this->setExpectedException('InvalidArgumentException');
51
- Braintree\Customer::find('');
52
- }
53
-
54
- public function testFindErrorsOnWhitespaceId()
55
- {
56
- $this->setExpectedException('InvalidArgumentException');
57
- Braintree\Customer::find('\t');
58
- }
59
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/DigestTest.php DELETED
@@ -1,97 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class DigestTest extends Setup
10
- {
11
- public function testSecureCompareReturnsTrueForMatches()
12
- {
13
- $this->assertTrue(Braintree\Digest::secureCompare("a_string", "a_string"));
14
- }
15
-
16
- public function testSecureCompareReturnsFalseForDifferentLengths()
17
- {
18
- $this->assertFalse(Braintree\Digest::secureCompare("a_string", "a_string_that_is_longer"));
19
- }
20
-
21
- public function testSecureCompareReturnsFalseForNonmatchingSameLengthStrings()
22
- {
23
- $this->assertFalse(Braintree\Digest::secureCompare("a_string", "a_strong"));
24
- }
25
-
26
- public function testHexDigestSha1()
27
- {
28
- $key = str_repeat(chr(0xaa),80);
29
- $message = 'Test Using Larger Than Block-Size Key - Hash Key First';
30
- $d = Braintree\Digest::hexDigestSha1($key, $message);
31
-
32
- $this->assertEquals('aa4ae5e15272d00e95705637ce8a3b55ed402112', $d);
33
- }
34
-
35
- public function testHexDigestSha1_again()
36
- {
37
- $key = str_repeat(chr(0xaa),80);
38
- $message = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
39
- $d = Braintree\Digest::hexDigestSha1($key, $message);
40
-
41
- $this->assertEquals('e8e99d0f45237d786d6bbaa7965c7808bbff1a91', $d);
42
- }
43
-
44
- public function testHexDigestSha256()
45
- {
46
- $key = str_repeat(chr(0xaa),80);
47
- $message = 'Test Using Larger Than Block-Size Key - Hash Key First';
48
- $d = Braintree\Digest::hexDigestSha256($key, $message);
49
-
50
- $this->assertEquals('6953025ed96f0c09f80a96f78e6538dbe2e7b820e3dd970e7ddd39091b32352f', $d);
51
- }
52
-
53
- public function testHexDigestSha256_again()
54
- {
55
- $key = str_repeat(chr(0xaa),80);
56
- $message = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
57
- $d = Braintree\Digest::hexDigestSha256($key, $message);
58
-
59
- $this->assertEquals('6355ac22e890d0a3c8481a5ca4825bc884d3e7a1ff98a2fc2ac7d8e064c3b2e6', $d);
60
- }
61
-
62
- public function testBuiltInHmacSha1()
63
- {
64
- Braintree\Configuration::privateKey(str_repeat(chr(0xaa),80));
65
- $message = 'Test Using Larger Than Block-Size Key - Hash Key First';
66
- $d = Braintree\Digest::_builtInHmacSha1($message, Braintree\Configuration::privateKey());
67
-
68
- $this->assertEquals('aa4ae5e15272d00e95705637ce8a3b55ed402112', $d);
69
- }
70
-
71
- public function testBuiltInHmacSha1_again()
72
- {
73
- Braintree\Configuration::privateKey(str_repeat(chr(0xaa),80));
74
- $message = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
75
- $d = Braintree\Digest::_builtInHmacSha1($message, Braintree\Configuration::privateKey());
76
-
77
- $this->assertEquals('e8e99d0f45237d786d6bbaa7965c7808bbff1a91', $d);
78
- }
79
-
80
- public function testHmacSha1()
81
- {
82
- Braintree\Configuration::privateKey(str_repeat(chr(0xaa),80));
83
- $message = 'Test Using Larger Than Block-Size Key - Hash Key First';
84
- $d = Braintree\Digest::_hmacSha1($message, Braintree\Configuration::privateKey());
85
-
86
- $this->assertEquals('aa4ae5e15272d00e95705637ce8a3b55ed402112', $d);
87
- }
88
-
89
- public function testHmacSha1_again()
90
- {
91
- Braintree\Configuration::privateKey(str_repeat(chr(0xaa),80));
92
- $message = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
93
- $d = Braintree\Digest::_hmacSha1($message, Braintree\Configuration::privateKey());
94
-
95
- $this->assertEquals('e8e99d0f45237d786d6bbaa7965c7808bbff1a91', $d);
96
- }
97
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/DisbursementDetailsTest.php DELETED
@@ -1,29 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class DisbursementDetailsTest extends Setup
11
- {
12
- public function testIsValidReturnsTrue()
13
- {
14
- $details = new Braintree\DisbursementDetails([
15
- "disbursementDate" => new DateTime("2013-04-10")
16
- ]);
17
-
18
- $this->assertTrue($details->isValid());
19
- }
20
-
21
- public function testIsValidReturnsFalse()
22
- {
23
- $details = new Braintree\DisbursementDetails([
24
- "disbursementDate" => null
25
- ]);
26
-
27
- $this->assertFalse($details->isValid());
28
- }
29
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/DisbursementTest.php DELETED
@@ -1,35 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class DisbursementTest extends Setup
11
- {
12
- public function testToString()
13
- {
14
- $disbursement = Braintree\Disbursement::factory([
15
- "id" => "123456",
16
- "merchantAccount" => [
17
- "id" => "sandbox_sub_merchant_account",
18
- "masterMerchantAccount" => [
19
- "id" => "sandbox_master_merchant_account",
20
- "status" => "active"
21
- ],
22
- "status" => "active"
23
- ],
24
- "transactionIds" => ["sub_merchant_transaction"],
25
- "exceptionMessage" => "invalid_account_number",
26
- "amount" => "100.00",
27
- "disbursementDate" => new DateTime("2013-04-10"),
28
- "followUpAction" => "update",
29
- "retry" => false,
30
- "success" => false
31
- ]);
32
-
33
- $this->assertEquals((string) $disbursement, 'Braintree\Disbursement[id=123456, merchantAccountDetails=id=sandbox_sub_merchant_account, masterMerchantAccount=id=sandbox_master_merchant_account, status=active, status=active, exceptionMessage=invalid_account_number, amount=100.00, disbursementDate=Wednesday, 10-Apr-13 00:00:00 UTC, followUpAction=update, retry=, success=, transactionIds=0=sub_merchant_transaction]');
34
- }
35
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/DiscountTest.php DELETED
@@ -1,34 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class DiscountTest extends Setup
10
- {
11
- public function testFactory()
12
- {
13
- $discount = Braintree\Discount::factory([]);
14
-
15
- $this->assertInstanceOf('Braintree\Discount', $discount);
16
- }
17
-
18
- public function testToString()
19
- {
20
- $discountParams = [
21
- "amount" => "100.00",
22
- "description" => "some description",
23
- "id" => "1",
24
- "kind" => "discount",
25
- "name" => "php_discount",
26
- "neverExpires" => "false",
27
- "numberOfBillingCycles" => "1"
28
- ];
29
-
30
- $discount = Braintree\Discount::factory($discountParams);
31
-
32
- $this->assertEquals("Braintree\Discount[amount=100.00, description=some description, id=1, kind=discount, name=php_discount, neverExpires=false, numberOfBillingCycles=1]", (string) $discount);
33
- }
34
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/GatewayTest.php DELETED
@@ -1,51 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class GatewayTest extends Setup
10
- {
11
- public function setup()
12
- {
13
- Braintree\Configuration::reset();
14
- }
15
-
16
- public function teardown()
17
- {
18
- Braintree\Configuration::environment('development');
19
- Braintree\Configuration::merchantId('integration_merchant_id');
20
- Braintree\Configuration::publicKey('integration_public_key');
21
- Braintree\Configuration::privateKey('integration_private_key');
22
- }
23
-
24
- /**
25
- * @expectedException Braintree\Exception\Configuration
26
- * @expectedExceptionMessage needs to be set (or accessToken needs to be passed to Braintree\Gateway).
27
- */
28
- public function testConfigGetsAssertedValid()
29
- {
30
- Braintree\Configuration::environment('development');
31
- //Braintree\Configuration::merchantId('integration_merchant_id');
32
- Braintree\Configuration::publicKey('integration_public_key');
33
- Braintree\Configuration::privateKey('integration_private_key');
34
-
35
- $gateway = new Braintree\Gateway(Braintree\Configuration::$global);
36
- $gateway->addOn();
37
- }
38
-
39
- public function testConstructWithArrayOfCredentials()
40
- {
41
- $gateway = new Braintree\Gateway([
42
- 'environment' => 'sandbox',
43
- 'merchantId' => 'sandbox_merchant_id',
44
- 'publicKey' => 'sandbox_public_key',
45
- 'privateKey' => 'sandbox_private_key'
46
- ]);
47
-
48
- $this->assertEquals('sandbox', $gateway->config->getEnvironment());
49
- $this->assertEquals('sandbox_merchant_id', $gateway->config->getMerchantId());
50
- }
51
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/InstanceTest.php DELETED
@@ -1,37 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class InstanceTest extends Setup
10
- {
11
- public function test__isset()
12
- {
13
- $transaction = Braintree\Transaction::factory([
14
- 'creditCard' => [
15
- 'expirationMonth' => '05',
16
- 'expirationYear' => '2010',
17
- 'bin' => '510510',
18
- 'last4' => '5100',
19
- 'cardType' => 'MasterCard',
20
- ],
21
- ]);
22
- $this->assertEquals('MasterCard', $transaction->creditCardDetails->cardType);
23
- $this->assertFalse(empty($transaction->creditCardDetails->cardType));
24
- $this->assertTrue(isset($transaction->creditCardDetails->cardType));
25
-
26
- $transaction = Braintree\Transaction::factory([
27
- 'creditCard' => [
28
- 'expirationMonth' => '05',
29
- 'expirationYear' => '2010',
30
- 'bin' => '510510',
31
- 'last4' => '5100',
32
- ],
33
- ]);
34
- $this->assertTrue(empty($transaction->creditCardDetails->cardType));
35
- $this->assertFalse(isset($transaction->creditCardDetails->cardType));
36
- }
37
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/MerchantAccountTest.php DELETED
@@ -1,68 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class MerchantAccountTest extends Setup
10
- {
11
- public function testCreateMerchantAccountWithAllParams()
12
- {
13
- $params = [
14
- "id" => "sub_merchant_account",
15
- "status" => "active",
16
- "masterMerchantAccount" => [
17
- "id" => "master_merchant_account",
18
- "status" => "active"
19
- ],
20
- "individual" => [
21
- "firstName" => "John",
22
- "lastName" => "Doe",
23
- "email" => "john.doe@example.com",
24
- "dateOfBirth" => "1970-01-01",
25
- "phone" => "3125551234",
26
- "ssnLast4" => "6789",
27
- "address" => [
28
- "streetAddress" => "123 Fake St",
29
- "locality" => "Chicago",
30
- "region" => "IL",
31
- "postalCode" => "60622",
32
- ]
33
- ],
34
- "business" => [
35
- "dbaName" => "James's Bloggs",
36
- "taxId" => "123456789",
37
- ],
38
- "funding" => [
39
- "accountNumberLast4" => "8798",
40
- "routingNumber" => "071000013",
41
- "descriptor" => "Joes Bloggs MI",
42
- ]
43
- ];
44
- $merchantAccount = Braintree\MerchantAccount::factory($params);
45
-
46
-
47
- $this->assertEquals($merchantAccount->status, "active");
48
- $this->assertEquals($merchantAccount->id, "sub_merchant_account");
49
- $this->assertEquals($merchantAccount->masterMerchantAccount->id, "master_merchant_account");
50
- $this->assertEquals($merchantAccount->masterMerchantAccount->status, "active");
51
- $this->assertEquals($merchantAccount->individualDetails->firstName, "John");
52
- $this->assertEquals($merchantAccount->individualDetails->lastName, "Doe");
53
- $this->assertEquals($merchantAccount->individualDetails->email, "john.doe@example.com");
54
- $this->assertEquals($merchantAccount->individualDetails->dateOfBirth, "1970-01-01");
55
- $this->assertEquals($merchantAccount->individualDetails->phone, "3125551234");
56
- $this->assertEquals($merchantAccount->individualDetails->ssnLast4, "6789");
57
- $this->assertEquals($merchantAccount->individualDetails->addressDetails->streetAddress, "123 Fake St");
58
- $this->assertEquals($merchantAccount->individualDetails->addressDetails->locality, "Chicago");
59
- $this->assertEquals($merchantAccount->individualDetails->addressDetails->region, "IL");
60
- $this->assertEquals($merchantAccount->individualDetails->addressDetails->postalCode, "60622");
61
- $this->assertEquals($merchantAccount->businessDetails->dbaName, "James's Bloggs");
62
- $this->assertEquals($merchantAccount->businessDetails->taxId, "123456789");
63
- $this->assertEquals($merchantAccount->fundingDetails->accountNumberLast4, "8798");
64
- $this->assertEquals($merchantAccount->fundingDetails->routingNumber, "071000013");
65
- $this->assertEquals($merchantAccount->fundingDetails->descriptor, "Joes Bloggs MI");
66
- }
67
- }
68
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/MultipleValueNodeTest.php DELETED
@@ -1,24 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class MultipleValueNodeTest extends Setup
10
- {
11
- public function testIs()
12
- {
13
- $node = new Braintree\MultipleValueNode('field');
14
- $node->is('value');
15
- $this->assertEquals(['value'], $node->toParam());
16
- }
17
-
18
- public function testIn()
19
- {
20
- $node = new Braintree\MultipleValueNode('field');
21
- $node->in(['firstValue', 'secondValue']);
22
- $this->assertEquals(['firstValue', 'secondValue'], $node->toParam());
23
- }
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/MultipleValueOrTextNodeTest.php DELETED
@@ -1,52 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class MultipleValueOrTextNodeTest extends Setup
10
- {
11
- public function testIn()
12
- {
13
- $node = new Braintree\MultipleValueOrTextNode('field');
14
- $node->in(['firstValue', 'secondValue']);
15
- $this->assertEquals(['firstValue', 'secondValue'], $node->toParam());
16
- }
17
-
18
- public function testIs()
19
- {
20
- $node = new Braintree\MultipleValueOrTextNode('field');
21
- $node->is('value');
22
- $this->assertEquals(['is' => 'value'], $node->toParam());
23
- }
24
-
25
- public function testIsNot()
26
- {
27
- $node = new Braintree\MultipleValueOrTextNode('field');
28
- $node->isNot('value');
29
- $this->assertEquals(['is_not' => 'value'], $node->toParam());
30
- }
31
-
32
- public function testStartsWith()
33
- {
34
- $node = new Braintree\MultipleValueOrTextNode('field');
35
- $node->startsWith('beginning');
36
- $this->assertEquals(['starts_with' => 'beginning'], $node->toParam());
37
- }
38
-
39
- public function testEndsWith()
40
- {
41
- $node = new Braintree\MultipleValueOrTextNode('field');
42
- $node->endsWith('end');
43
- $this->assertEquals(['ends_with' => 'end'], $node->toParam());
44
- }
45
-
46
- public function testContains()
47
- {
48
- $node = new Braintree\MultipleValueOrTextNode('field');
49
- $node->contains('middle');
50
- $this->assertEquals(['contains' => 'middle'], $node->toParam());
51
- }
52
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/OAuthTest.php DELETED
@@ -1,71 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class OAuthTest extends Setup
10
- {
11
- protected $gateway;
12
-
13
- public function setUp()
14
- {
15
- $this->gateway = new Braintree\Gateway([
16
- 'clientId' => 'client_id$development$integration_client_id',
17
- 'clientSecret' => 'client_secret$development$integration_client_secret'
18
- ]);
19
- }
20
-
21
- public function testMapInvalidGrantCodeToOldError()
22
- {
23
- $result = $this->_buildResult([
24
- 'code' => '93801',
25
- 'message' => 'Invalid grant: code not found'
26
- ]);
27
-
28
- $this->gateway->oauth()->_mapError($result);
29
-
30
- $this->assertEquals($result->error, 'invalid_grant');
31
- $this->assertEquals($result->errorDescription, 'code not found');
32
- }
33
-
34
- public function testMapInvalidCredentialsCodeToOldError()
35
- {
36
- $result = $this->_buildResult([
37
- 'code' => '93802',
38
- 'message' => 'Invalid credentials: wrong client id or secret'
39
- ]);
40
-
41
- $this->gateway->oauth()->_mapError($result);
42
-
43
- $this->assertEquals($result->error, 'invalid_credentials');
44
- $this->assertEquals($result->errorDescription, 'wrong client id or secret');
45
- }
46
-
47
- public function testMapInvalidScopeCodeToOldError()
48
- {
49
- $result = $this->_buildResult([
50
- 'code' => '93803',
51
- 'message' => 'Invalid scope: scope is invalid'
52
- ]);
53
-
54
- $this->gateway->oauth()->_mapError($result);
55
-
56
- $this->assertEquals($result->error, 'invalid_scope');
57
- $this->assertEquals($result->errorDescription, 'scope is invalid');
58
- }
59
-
60
- protected function _buildResult($error)
61
- {
62
- return new Braintree\Result\Error([
63
- 'errors' => [
64
- 'errors' => [],
65
- 'credentials' => [
66
- 'errors' => [$error]
67
- ]
68
- ]
69
- ]);
70
- }
71
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/PayPalAccountTest.php DELETED
@@ -1,44 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class PayPalAccountTest extends Setup
10
- {
11
- public function testGet_givesErrorIfInvalidProperty()
12
- {
13
- $this->setExpectedException('PHPUnit_Framework_Error', 'Undefined property on Braintree\PayPalAccount: foo');
14
- $paypalAccount = Braintree\PayPalAccount::factory([]);
15
- $paypalAccount->foo;
16
- }
17
-
18
- public function testIsDefault()
19
- {
20
- $paypalAccount = Braintree\PayPalAccount::factory(['default' => true]);
21
- $this->assertTrue($paypalAccount->isDefault());
22
-
23
- $paypalAccount = Braintree\PayPalAccount::factory(['default' => false]);
24
- $this->assertFalse($paypalAccount->isDefault());
25
- }
26
-
27
- public function testErrorsOnFindWithBlankArgument()
28
- {
29
- $this->setExpectedException('InvalidArgumentException');
30
- Braintree\PayPalAccount::find('');
31
- }
32
-
33
- public function testErrorsOnFindWithWhitespaceArgument()
34
- {
35
- $this->setExpectedException('InvalidArgumentException');
36
- Braintree\PayPalAccount::find(' ');
37
- }
38
-
39
- public function testErrorsOnFindWithWhitespaceCharacterArgument()
40
- {
41
- $this->setExpectedException('InvalidArgumentException');
42
- Braintree\PayPalAccount::find('\t');
43
- }
44
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/PaymentMethodTest.php DELETED
@@ -1,60 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class PaymentMethodTest extends Setup
10
- {
11
- public function testCreate_throwsIfInvalidKey()
12
- {
13
- $this->setExpectedException('InvalidArgumentException', 'invalid keys: invalidKey');
14
- Braintree\PaymentMethod::create(['invalidKey' => 'foo']);
15
- }
16
-
17
- public function testCreateSignature()
18
- {
19
- $expected = [
20
- 'billingAddressId',
21
- 'cardholderName',
22
- 'cvv',
23
- 'deviceData',
24
- 'expirationDate',
25
- 'expirationMonth',
26
- 'expirationYear',
27
- 'number',
28
- 'paymentMethodNonce',
29
- 'token',
30
- ['options' => [
31
- 'failOnDuplicatePaymentMethod',
32
- 'makeDefault',
33
- 'verificationMerchantAccountId',
34
- 'verifyCard',
35
- 'verificationAmount',
36
- ]],
37
- ['billingAddress' => Braintree\AddressGateway::createSignature()],
38
- 'customerId'
39
- ];
40
- $this->assertEquals($expected, Braintree\PaymentMethodGateway::createSignature());
41
- }
42
-
43
- public function testErrorsOnFindWithBlankArgument()
44
- {
45
- $this->setExpectedException('InvalidArgumentException');
46
- Braintree\PaymentMethod::find('');
47
- }
48
-
49
- public function testErrorsOnFindWithWhitespaceArgument()
50
- {
51
- $this->setExpectedException('InvalidArgumentException');
52
- Braintree\PaymentMethod::find(' ');
53
- }
54
-
55
- public function testErrorsOnFindWithWhitespaceCharacterArgument()
56
- {
57
- $this->setExpectedException('InvalidArgumentException');
58
- Braintree\PaymentMethod::find('\t');
59
- }
60
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/RangeNodeTest.php DELETED
@@ -1,38 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class RangeNodeTest extends Setup
10
- {
11
- public function testGreaterThanOrEqualTo()
12
- {
13
- $node = new Braintree\RangeNode('field');
14
- $node->greaterThanOrEqualTo('smallest');
15
- $this->assertEquals(['min' => 'smallest'], $node->toParam());
16
- }
17
-
18
- public function testLessThanOrEqualTo()
19
- {
20
- $node = new Braintree\RangeNode('field');
21
- $node->lessThanOrEqualTo('biggest');
22
- $this->assertEquals(['max' => 'biggest'], $node->toParam());
23
- }
24
-
25
- public function testBetween()
26
- {
27
- $node = new Braintree\RangeNode('field');
28
- $node->between('alpha', 'omega');
29
- $this->assertEquals(['min' => 'alpha', 'max' => 'omega'], $node->toParam());
30
- }
31
-
32
- public function testIs()
33
- {
34
- $node = new Braintree\RangeNode('field');
35
- $node->is('something');
36
- $this->assertEquals(['is' => 'something'], $node->toParam());
37
- }
38
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/ResourceCollectionTest.php DELETED
@@ -1,88 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class TestResource
10
- {
11
- public function lookup($id) {
12
- return ResourceCollectionTest::$values[intval($id)];
13
- }
14
-
15
- public function fetch($ids)
16
- {
17
-
18
- return array_map(__NAMESPACE__ . '\TestResource::lookup', $ids);
19
- }
20
- }
21
-
22
- class ResourceCollectionTest extends Setup
23
- {
24
- public static $values = ["a", "b", "c", "d", "e"];
25
-
26
- public function testIterateOverResults()
27
- {
28
-
29
- $response = [
30
- 'searchResults' => [
31
- 'pageSize' => 2,
32
- 'ids' => ['0', '1', '2', '3', '4']
33
- ]
34
- ];
35
-
36
- $object = new TestResource();
37
- $pager = [
38
- 'object' => $object,
39
- 'method' => 'fetch',
40
- 'methodArgs' => []
41
- ];
42
-
43
- $collection = new Braintree\ResourceCollection($response, $pager);
44
-
45
- $count = 0;
46
- $index = 0;
47
- foreach ($collection as $value)
48
- {
49
- $this->assertEquals(self::$values[$index], $value);
50
- $index += 1;
51
- $count += 1;
52
- }
53
-
54
- $this->assertEquals(5, $count);
55
- }
56
-
57
- public function testDoesntIterateWhenNoResults()
58
- {
59
-
60
- $response = [
61
- 'searchResults' => [
62
- 'pageSize' => 2,
63
- 'ids' => []
64
- ]
65
- ];
66
-
67
- $object = new TestResource();
68
- $pager = [
69
- 'object' => $object,
70
- 'method' => 'fetch',
71
- 'methodArgs' => []
72
- ];
73
-
74
- $collection = new Braintree\ResourceCollection($response, $pager);
75
-
76
- $count = 0;
77
- $index = 0;
78
- foreach ($collection as $value)
79
- {
80
- $index += 1;
81
- $count += 1;
82
- break;
83
- }
84
-
85
- $this->assertEquals(0, $count);
86
- $this->assertEquals(0, $index);
87
- }
88
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/Result/ErrorTest.php DELETED
@@ -1,16 +0,0 @@
1
- <?php
2
- namespace Test\Unit\Result;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class ErrorTest extends Setup
10
- {
11
- public function testCallingNonExsitingFieldReturnsNull()
12
- {
13
- $result = new Braintree\Result\Error(['errors' => [], 'params' => [], 'message' => 'briefly describe']);
14
- $this->assertNull($result->transaction);
15
- }
16
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/Result/SuccessfulTest.php DELETED
@@ -1,21 +0,0 @@
1
- <?php
2
- namespace Test\Unit\Result;
3
-
4
- require_once dirname(dirname(__DIR__)) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class SuccessfulTest extends Setup
10
- {
11
- /**
12
- * @expectedException PHPUnit_Framework_Error_Notice
13
- * @expectedExceptionMessage Undefined property on Braintree\Result\Successful: notAProperty
14
- */
15
- public function testCallingNonExsitingFieldReturnsNull()
16
- {
17
- $result = new Braintree\Result\Successful(1, 'transaction');
18
- $this->assertNotNull($result->transaction);
19
- $this->assertNull($result->notAProperty);
20
- }
21
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/SanityTest.php DELETED
@@ -1,19 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
-
8
- class SanityTest extends Setup
9
- {
10
- public function testCodeFiles_allOmitPHPCloseTag()
11
- {
12
- $codeFiles = explode("\n", shell_exec("find ./lib -name \*.php"));
13
- foreach ($codeFiles as $codeFile) {
14
- if ($codeFile == "") continue;
15
- $code = file_get_contents($codeFile);
16
- $this->assertNotContains("?>", $code, "$codeFile should not contain a PHP close tag");
17
- }
18
- }
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/SubscriptionSearchTest.php DELETED
@@ -1,64 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class SubscriptionSearchTest extends Setup
10
- {
11
- public function testSearch_billingCyclesRemaining_isRangeNode()
12
- {
13
- $node = Braintree\SubscriptionSearch::billingCyclesRemaining();
14
- $this->assertInstanceOf('Braintree\RangeNode', $node);
15
- }
16
-
17
- public function testSearch_price_isRangeNode()
18
- {
19
- $node = Braintree\SubscriptionSearch::price();
20
- $this->assertInstanceOf('Braintree\RangeNode', $node);
21
- }
22
-
23
- public function testSearch_daysPastDue_isRangeNode()
24
- {
25
- $node = Braintree\SubscriptionSearch::daysPastDue();
26
- $this->assertInstanceOf('Braintree\RangeNode', $node);
27
- }
28
-
29
- public function testSearch_id_isTextNode()
30
- {
31
- $node = Braintree\SubscriptionSearch::id();
32
- $this->assertInstanceOf('Braintree\TextNode', $node);
33
- }
34
-
35
- public function testSearch_ids_isMultipleValueNode()
36
- {
37
- $node = Braintree\SubscriptionSearch::ids();
38
- $this->assertInstanceOf('Braintree\MultipleValueNode', $node);
39
- }
40
-
41
- public function testSearch_inTrialPeriod_isMultipleValueNode()
42
- {
43
- $node = Braintree\SubscriptionSearch::inTrialPeriod();
44
- $this->assertInstanceOf('Braintree\MultipleValueNode', $node);
45
- }
46
-
47
- public function testSearch_merchantAccountId_isMultipleValueNode()
48
- {
49
- $node = Braintree\SubscriptionSearch::merchantAccountId();
50
- $this->assertInstanceOf('Braintree\MultipleValueNode', $node);
51
- }
52
-
53
- public function testSearch_planId_isMultipleValueOrTextNode()
54
- {
55
- $node = Braintree\SubscriptionSearch::planId();
56
- $this->assertInstanceOf('Braintree\MultipleValueOrTextNode', $node);
57
- }
58
-
59
- public function testSearch_status_isMultipleValueNode()
60
- {
61
- $node = Braintree\SubscriptionSearch::status();
62
- $this->assertInstanceOf('Braintree\MultipleValueNode', $node);
63
- }
64
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/SubscriptionTest.php DELETED
@@ -1,22 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class SubscriptionTest extends Setup
10
- {
11
- public function testErrorsOnFindWithBlankArgument()
12
- {
13
- $this->setExpectedException('InvalidArgumentException');
14
- Braintree\Subscription::find('');
15
- }
16
-
17
- public function testErrorsOnFindWithWhitespaceArgument()
18
- {
19
- $this->setExpectedException('InvalidArgumentException');
20
- Braintree\Subscription::find('\t');
21
- }
22
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/TextNodeTest.php DELETED
@@ -1,45 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class TextNodeTest extends Setup
10
- {
11
- public function testIs()
12
- {
13
- $node = new Braintree\TextNode('field');
14
- $node->is('value');
15
- $this->assertEquals(['is' => 'value'], $node->toParam());
16
- }
17
-
18
- public function testIsNot()
19
- {
20
- $node = new Braintree\TextNode('field');
21
- $node->isNot('value');
22
- $this->assertEquals(['is_not' => 'value'], $node->toParam());
23
- }
24
-
25
- public function testStartsWith()
26
- {
27
- $node = new Braintree\TextNode('field');
28
- $node->startsWith('beginning');
29
- $this->assertEquals(['starts_with' => 'beginning'], $node->toParam());
30
- }
31
-
32
- public function testEndsWith()
33
- {
34
- $node = new Braintree\TextNode('field');
35
- $node->endsWith('end');
36
- $this->assertEquals(['ends_with' => 'end'], $node->toParam());
37
- }
38
-
39
- public function testContains()
40
- {
41
- $node = new Braintree\TextNode('field');
42
- $node->contains('middle');
43
- $this->assertEquals(['contains' => 'middle'], $node->toParam());
44
- }
45
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/TransactionTest.php DELETED
@@ -1,50 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class TransactionTest extends Setup
10
- {
11
- public function testGet_givesErrorIfInvalidProperty()
12
- {
13
- $t = Braintree\Transaction::factory([
14
- 'creditCard' => ['expirationMonth' => '05', 'expirationYear' => '2010', 'bin' => '510510', 'last4' => '5100'],
15
- 'customer' => [],
16
- 'billing' => [],
17
- 'descriptor' => [],
18
- 'shipping' => [],
19
- 'subscription' => ['billingPeriodStartDate' => '1983-07-12'],
20
- 'statusHistory' => []
21
- ]);
22
- $this->setExpectedException('PHPUnit_Framework_Error', 'Undefined property on Braintree\Transaction: foo');
23
- $t->foo;
24
- }
25
-
26
- public function testCloneTransaction_RaisesErrorOnInvalidProperty()
27
- {
28
- $this->setExpectedException('InvalidArgumentException');
29
- Braintree\Transaction::cloneTransaction('an id', ['amount' => '123.45', 'invalidProperty' => 'foo']);
30
- }
31
-
32
- public function testErrorsWhenFindWithBlankString()
33
- {
34
- $this->setExpectedException('InvalidArgumentException');
35
- Braintree\Transaction::find('');
36
- }
37
-
38
- public function testErrorsWhenFindWithWhitespaceString()
39
- {
40
- $this->setExpectedException('InvalidArgumentException');
41
- Braintree\Transaction::find('\t');
42
- }
43
-
44
- public function testInitializationWithoutArguments()
45
- {
46
- $transaction = Braintree\Transaction::factory([]);
47
-
48
- $this->assertTrue($transaction instanceof Braintree\Transaction);
49
- }
50
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/TransparentRedirectTest.php DELETED
@@ -1,31 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class TransparentRedirectTest extends Setup
10
- {
11
- public function testData_specifiesArgSeparatorAsAmpersand()
12
- {
13
- $originalSeparator = ini_get("arg_separator.output");
14
- ini_set("arg_separator.output", "&amp;");
15
- $trData = Braintree\TransparentRedirect::createCustomerData(['redirectUrl' => 'http://www.example.com']);
16
- ini_set("arg_separator.output", $originalSeparator);
17
- $this->assertFalse(strpos($trData, "&amp;"));
18
- }
19
-
20
- public function testData_doesNotClobberDefaultTimezone()
21
- {
22
- $originalZone = date_default_timezone_get();
23
- date_default_timezone_set('Europe/London');
24
-
25
- $trData = Braintree\TransparentRedirect::createCustomerData(['redirectUrl' => 'http://www.example.com']);
26
- $zoneAfterCall = date_default_timezone_get();
27
- date_default_timezone_set($originalZone);
28
-
29
- $this->assertEquals('Europe/London', $zoneAfterCall);
30
- }
31
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/UnknownPaymentMethodTest.php DELETED
@@ -1,25 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class UnknownPaymentMethodTest extends Setup
10
- {
11
- public function testHandlesUnknownPaymentMethodResponses()
12
- {
13
- $response = [
14
- 'unkownPaymentMethod' => [
15
- 'token' => 'SOME_TOKEN',
16
- 'default' => true
17
- ]
18
- ];
19
- $unknownPaymentMethodObject = Braintree\UnknownPaymentMethod::factory($response);
20
- $this->assertEquals('SOME_TOKEN', $unknownPaymentMethodObject->token);
21
- $this->assertTrue($unknownPaymentMethodObject->isDefault());
22
- $this->assertEquals('https://assets.braintreegateway.com/payment_method_logo/unknown.png', $unknownPaymentMethodObject->imageUrl);
23
- }
24
- }
25
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/UtilTest.php DELETED
@@ -1,261 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use stdClass;
7
- use DateTime;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class UtilTest extends Setup
12
- {
13
- /**
14
- * @expectedException Braintree\Exception\Authentication
15
- */
16
- public function testThrow401Exception()
17
- {
18
- Braintree\Util::throwStatusCodeException(401);
19
- }
20
-
21
- /**
22
- * @expectedException Braintree\Exception\Authorization
23
- */
24
- public function testThrow403Exception()
25
- {
26
- Braintree\Util::throwStatusCodeException(403);
27
- }
28
-
29
- /**
30
- * @expectedException Braintree\Exception\NotFound
31
- */
32
- public function testThrow404Exception()
33
- {
34
- Braintree\Util::throwStatusCodeException(404);
35
- }
36
-
37
- /**
38
- * @expectedException Braintree\Exception\UpgradeRequired
39
- */
40
- public function testThrow426Exception()
41
- {
42
- Braintree\Util::throwStatusCodeException(426);
43
- }
44
-
45
- /**
46
- * @expectedException Braintree\Exception\ServerError
47
- */
48
- public function testThrow500Exception()
49
- {
50
- Braintree\Util::throwStatusCodeException(500);
51
- }
52
-
53
- /**
54
- * @expectedException Braintree\Exception\DownForMaintenance
55
- */
56
- public function testThrow503Exception()
57
- {
58
- Braintree\Util::throwStatusCodeException(503);
59
- }
60
-
61
- /**
62
- * @expectedException Braintree\Exception\Unexpected
63
- */
64
- public function testThrowUnknownException()
65
- {
66
- Braintree\Util::throwStatusCodeException(999);
67
- }
68
-
69
- public function testExtractAttributeAsArrayReturnsEmptyArray()
70
- {
71
- $attributes = [];
72
- $this->assertEquals([], Braintree\Util::extractAttributeAsArray($attributes, "foo"));
73
- }
74
-
75
- public function testExtractAttributeAsArrayReturnsSingleElementArray()
76
- {
77
- $attributes = ['verification' => 'val1'];
78
- $this->assertEquals(['val1'], Braintree\Util::extractAttributeAsArray($attributes, "verification"));
79
- }
80
-
81
- public function testExtractAttributeAsArrayReturnsArrayOfObjects()
82
- {
83
- $attributes = ['verification' => [['status' => 'val1']]];
84
- $expected = new Braintree\CreditCardVerification(['status' => 'val1']);
85
- $this->assertEquals([$expected], Braintree\Util::extractAttributeAsArray($attributes, "verification"));
86
- }
87
-
88
- public function testDelimeterToUnderscore()
89
- {
90
- $this->assertEquals("a_b_c", Braintree\Util::delimiterToUnderscore("a-b-c"));
91
- }
92
-
93
- public function testCleanClassName()
94
- {
95
- $cn = Braintree\Util::cleanClassName('Braintree\Transaction');
96
- $this->assertEquals('transaction', $cn);
97
- }
98
-
99
- public function testBuildClassName()
100
- {
101
- $cn = Braintree\Util::buildClassName('creditCard');
102
- $this->assertEquals('Braintree\CreditCard', $cn);
103
- }
104
-
105
- public function testimplodeAssociativeArray()
106
- {
107
- $array = [
108
- 'test1' => 'val1',
109
- 'test2' => 'val2',
110
- 'test3' => new DateTime('2015-05-15 17:21:00'),
111
- ];
112
- $string = Braintree\Util::implodeAssociativeArray($array);
113
- $this->assertEquals('test1=val1, test2=val2, test3=Fri, 15 May 2015 17:21:00 +0000', $string);
114
- }
115
-
116
- public function testVerifyKeys_withThreeLevels()
117
- {
118
- $signature = [
119
- 'firstName',
120
- ['creditCard' => ['number', ['billingAddress' => ['streetAddress']]]]
121
- ];
122
- $data = [
123
- 'firstName' => 'Dan',
124
- 'creditCard' => [
125
- 'number' => '5100',
126
- 'billingAddress' => [
127
- 'streetAddress' => '1 E Main St'
128
- ]
129
- ]
130
- ];
131
- Braintree\Util::verifyKeys($signature, $data);
132
- }
133
-
134
- public function testVerifyKeys_withArrayOfArrays()
135
- {
136
- $signature = [
137
- ['addOns' => [['update' => ['amount', 'existingId']]]]
138
- ];
139
-
140
- $goodData = [
141
- 'addOns' => [
142
- 'update' => [
143
- [
144
- 'amount' => '50.00',
145
- 'existingId' => 'increase_10',
146
- ],
147
- [
148
- 'amount' => '60.00',
149
- 'existingId' => 'increase_20',
150
- ]
151
- ]
152
- ]
153
- ];
154
-
155
- Braintree\Util::verifyKeys($signature, $goodData);
156
-
157
- $badData = [
158
- 'addOns' => [
159
- 'update' => [
160
- [
161
- 'invalid' => '50.00',
162
- ]
163
- ]
164
- ]
165
- ];
166
-
167
- $this->setExpectedException('InvalidArgumentException');
168
- Braintree\Util::verifyKeys($signature, $badData);
169
- }
170
-
171
- public function testVerifyKeys_arrayAsValue()
172
- {
173
- $signature = ['key'];
174
- $data = ['key' => ['value']];
175
- $this->setExpectedException('InvalidArgumentException');
176
- Braintree\Util::verifyKeys($signature, $data);
177
- }
178
-
179
- public function testVerifyKeys()
180
- {
181
- $signature = [
182
- 'amount', 'customerId', 'orderId', 'channel', 'paymentMethodToken', 'type',
183
-
184
- ['creditCard' =>
185
- ['token', 'cvv', 'expirationDate', 'number'],
186
- ],
187
- ['customer' =>
188
- [
189
- 'id', 'company', 'email', 'fax', 'firstName',
190
- 'lastName', 'phone', 'website'],
191
- ],
192
- ['billing' =>
193
- [
194
- 'firstName', 'lastName', 'company', 'countryName',
195
- 'extendedAddress', 'locality', 'postalCode', 'region',
196
- 'streetAddress'],
197
- ],
198
- ['shipping' =>
199
- [
200
- 'firstName', 'lastName', 'company', 'countryName',
201
- 'extendedAddress', 'locality', 'postalCode', 'region',
202
- 'streetAddress'],
203
- ],
204
- ['options' =>
205
- [
206
- 'storeInVault', 'submitForSettlement',
207
- 'addBillingAddressToPaymentMethod'],
208
- ],
209
- ['customFields' => ['_anyKey_']
210
- ],
211
- ];
212
-
213
- // test valid
214
- $userKeys = [
215
- 'amount' => '100.00',
216
- 'customFields' => ['HEY' => 'HO',
217
- 'WAY' => 'NO'],
218
- 'creditCard' => [
219
- 'number' => '5105105105105100',
220
- 'expirationDate' => '05/12',
221
- ],
222
- ];
223
-
224
- $n = Braintree\Util::verifyKeys($signature, $userKeys);
225
- $this->assertNull($n);
226
-
227
- $userKeys = [
228
- 'amount' => '100.00',
229
- 'customFields' => ['HEY' => 'HO',
230
- 'WAY' => 'NO'],
231
- 'bogus' => 'FAKE',
232
- 'totallyFake' => 'boom',
233
- 'creditCard' => [
234
- 'number' => '5105105105105100',
235
- 'expirationDate' => '05/12',
236
- ],
237
- ];
238
-
239
- // test invalid
240
- $this->setExpectedException('InvalidArgumentException');
241
-
242
- Braintree\Util::verifyKeys($signature, $userKeys);
243
- }
244
-
245
- /**
246
- * @expectedException Braintree\Exception\ValidationsFailed
247
- */
248
- public function testReturnException()
249
- {
250
- $this->success = false;
251
- Braintree\Util::returnObjectOrThrowException('Braintree\Transaction', $this);
252
- }
253
-
254
- public function testReturnObject()
255
- {
256
- $this->success = true;
257
- $this->transaction = new stdClass();
258
- $t = Braintree\Util::returnObjectOrThrowException('Braintree\Transaction', $this);
259
- $this->assertInternalType('object', $t);
260
- }
261
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/WebhookNotificationTest.php DELETED
@@ -1,457 +0,0 @@
1
- <?php
2
- namespace Test\Unit;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use Test\Setup;
8
- use Braintree;
9
-
10
- class WebhookNotificationTest extends Setup
11
- {
12
- public function setup()
13
- {
14
- self::integrationMerchantConfig();
15
- }
16
-
17
- public function testVerify()
18
- {
19
- $verificationString = Braintree\WebhookNotification::verify('20f9f8ed05f77439fe955c977e4c8a53');
20
- $this->assertEquals('integration_public_key|d9b899556c966b3f06945ec21311865d35df3ce4', $verificationString);
21
- }
22
-
23
- /**
24
- * @expectedException Braintree\Exception\InvalidChallenge
25
- * @expectedExceptionMessage challenge contains non-hex characters
26
- */
27
- public function testVerifyRaisesErrorWithInvalidChallenge()
28
- {
29
- $this->setExpectedException('Braintree\Exception\InvalidChallenge', 'challenge contains non-hex characters');
30
-
31
- Braintree\WebhookNotification::verify('bad challenge');
32
- }
33
-
34
- /**
35
- * @expectedException Braintree\Exception\Configuration
36
- * @expectedExceptionMessage Braintree\Configuration::merchantId needs to be set (or accessToken needs to be passed to Braintree\Gateway)
37
- */
38
- public function testVerifyRaisesErrorWhenEnvironmentNotSet()
39
- {
40
- Braintree\Configuration::reset();
41
-
42
- Braintree\WebhookNotification::verify('20f9f8ed05f77439fe955c977e4c8a53');
43
- }
44
-
45
- public function testSampleNotificationReturnsAParsableNotification()
46
- {
47
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
48
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
49
- 'my_id'
50
- );
51
-
52
- $webhookNotification = Braintree\WebhookNotification::parse(
53
- $sampleNotification['bt_signature'],
54
- $sampleNotification['bt_payload']
55
- );
56
-
57
- $this->assertEquals(Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE, $webhookNotification->kind);
58
- $this->assertNotNull($webhookNotification->timestamp);
59
- $this->assertEquals("my_id", $webhookNotification->subscription->id);
60
- }
61
-
62
- public function testParsingModifiedSignatureRaisesError()
63
- {
64
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
65
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
66
- 'my_id'
67
- );
68
-
69
- $this->setExpectedException('Braintree\Exception\InvalidSignature', 'signature does not match payload - one has been modified');
70
-
71
- $webhookNotification = Braintree\WebhookNotification::parse(
72
- $sampleNotification['bt_signature'] . "bad",
73
- $sampleNotification['bt_payload']
74
- );
75
- }
76
-
77
- /**
78
- * @expectedException Braintree\Exception\Configuration
79
- * @expectedExceptionMessage Braintree\Configuration::merchantId needs to be set (or accessToken needs to be passed to Braintree\Gateway)
80
- */
81
- public function testParsingWithNoKeysRaisesError()
82
- {
83
- Braintree\Configuration::reset();
84
-
85
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
86
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
87
- 'my_id'
88
- );
89
-
90
- $webhookNotification = Braintree\WebhookNotification::parse(
91
- $sampleNotification['bt_signature'],
92
- $sampleNotification['bt_payload']
93
- );
94
- }
95
-
96
- public function testParsingWebhookWithWrongKeysRaisesError()
97
- {
98
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
99
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
100
- 'my_id'
101
- );
102
-
103
- Braintree\Configuration::environment('development');
104
- Braintree\Configuration::merchantId('integration_merchant_id');
105
- Braintree\Configuration::publicKey('wrong_public_key');
106
- Braintree\Configuration::privateKey('wrong_private_key');
107
-
108
- $this->setExpectedException('Braintree\Exception\InvalidSignature', 'no matching public key');
109
-
110
- $webhookNotification = Braintree\WebhookNotification::parse(
111
- $sampleNotification['bt_signature'],
112
- "bad" . $sampleNotification['bt_payload']
113
- );
114
- }
115
-
116
- public function testParsingModifiedPayloadRaisesError()
117
- {
118
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
119
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
120
- 'my_id'
121
- );
122
-
123
- $this->setExpectedException('Braintree\Exception\InvalidSignature');
124
-
125
- $webhookNotification = Braintree\WebhookNotification::parse(
126
- $sampleNotification['bt_signature'],
127
- "bad" . $sampleNotification['bt_payload']
128
- );
129
- }
130
-
131
- public function testParsingUnknownPublicKeyRaisesError()
132
- {
133
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
134
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
135
- 'my_id'
136
- );
137
-
138
- $this->setExpectedException('Braintree\Exception\InvalidSignature');
139
-
140
- $webhookNotification = Braintree\WebhookNotification::parse(
141
- "bad" . $sampleNotification['bt_signature'],
142
- $sampleNotification['bt_payload']
143
- );
144
- }
145
-
146
- public function testParsingInvalidSignatureRaisesError()
147
- {
148
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
149
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
150
- 'my_id'
151
- );
152
-
153
- $this->setExpectedException('Braintree\Exception\InvalidSignature');
154
-
155
- $webhookNotification = Braintree\WebhookNotification::parse(
156
- "bad_signature",
157
- $sampleNotification['bt_payload']
158
- );
159
- }
160
-
161
- public function testParsingInvalidCharactersRaisesError()
162
- {
163
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
164
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
165
- 'my_id'
166
- );
167
-
168
- $this->setExpectedException('Braintree\Exception\InvalidSignature', 'payload contains illegal characters');
169
-
170
- $webhookNotification = Braintree\WebhookNotification::parse(
171
- $sampleNotification['bt_signature'],
172
- "~*~*invalid*~*~"
173
- );
174
- }
175
-
176
- public function testParsingAllowsAllValidCharacters()
177
- {
178
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
179
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
180
- 'my_id'
181
- );
182
-
183
- $this->setExpectedException('Braintree\Exception\InvalidSignature', 'signature does not match payload - one has been modified');
184
-
185
- $webhookNotification = Braintree\WebhookNotification::parse(
186
- $sampleNotification['bt_signature'],
187
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n"
188
- );
189
- }
190
-
191
- public function testParsingRetriesPayloadWithANewline()
192
- {
193
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
194
- Braintree\WebhookNotification::SUBSCRIPTION_WENT_PAST_DUE,
195
- 'my_id'
196
- );
197
-
198
- $webhookNotification = Braintree\WebhookNotification::parse(
199
- $sampleNotification['bt_signature'],
200
- rtrim($sampleNotification['bt_payload'])
201
- );
202
- }
203
-
204
- public function testBuildsASampleNotificationForASubscriptionChargedSuccessfullyWebhook()
205
- {
206
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
207
- Braintree\WebhookNotification::SUBSCRIPTION_CHARGED_SUCCESSFULLY,
208
- "my_id"
209
- );
210
-
211
- $webhookNotification = Braintree\WebhookNotification::parse(
212
- $sampleNotification['bt_signature'],
213
- $sampleNotification['bt_payload']
214
- );
215
-
216
- $this->assertEquals(Braintree\WebhookNotification::SUBSCRIPTION_CHARGED_SUCCESSFULLY, $webhookNotification->kind);
217
- $this->assertEquals("my_id", $webhookNotification->subscription->id);
218
- $this->assertEquals(1, count($webhookNotification->subscription->transactions));
219
-
220
- $transaction = $webhookNotification->subscription->transactions[0];
221
- $this->assertEquals('submitted_for_settlement', $transaction->status);
222
- $this->assertEquals('49.99', $transaction->amount);
223
- }
224
-
225
- public function testBuildsASampleNotificationForAMerchantAccountApprovedWebhook()
226
- {
227
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
228
- Braintree\WebhookNotification::SUB_MERCHANT_ACCOUNT_APPROVED,
229
- "my_id"
230
- );
231
-
232
- $webhookNotification = Braintree\WebhookNotification::parse(
233
- $sampleNotification['bt_signature'],
234
- $sampleNotification['bt_payload']
235
- );
236
-
237
- $this->assertEquals(Braintree\WebhookNotification::SUB_MERCHANT_ACCOUNT_APPROVED, $webhookNotification->kind);
238
- $this->assertEquals("my_id", $webhookNotification->merchantAccount->id);
239
- $this->assertEquals(Braintree\MerchantAccount::STATUS_ACTIVE, $webhookNotification->merchantAccount->status);
240
- $this->assertEquals("master_ma_for_my_id", $webhookNotification->merchantAccount->masterMerchantAccount->id);
241
- $this->assertEquals(Braintree\MerchantAccount::STATUS_ACTIVE, $webhookNotification->merchantAccount->masterMerchantAccount->status);
242
- }
243
-
244
- public function testBuildsASampleNotificationForAMerchantAccountDeclinedWebhook()
245
- {
246
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
247
- Braintree\WebhookNotification::SUB_MERCHANT_ACCOUNT_DECLINED,
248
- "my_id"
249
- );
250
-
251
- $webhookNotification = Braintree\WebhookNotification::parse(
252
- $sampleNotification['bt_signature'],
253
- $sampleNotification['bt_payload']
254
- );
255
-
256
- $this->assertEquals(Braintree\WebhookNotification::SUB_MERCHANT_ACCOUNT_DECLINED, $webhookNotification->kind);
257
- $this->assertEquals("my_id", $webhookNotification->merchantAccount->id);
258
- $this->assertEquals(Braintree\MerchantAccount::STATUS_SUSPENDED, $webhookNotification->merchantAccount->status);
259
- $this->assertEquals("master_ma_for_my_id", $webhookNotification->merchantAccount->masterMerchantAccount->id);
260
- $this->assertEquals(Braintree\MerchantAccount::STATUS_SUSPENDED, $webhookNotification->merchantAccount->masterMerchantAccount->status);
261
- $this->assertEquals("Credit score is too low", $webhookNotification->message);
262
- $errors = $webhookNotification->errors->forKey('merchantAccount')->onAttribute('base');
263
- $this->assertEquals(Braintree\Error\Codes::MERCHANT_ACCOUNT_DECLINED_OFAC, $errors[0]->code);
264
- }
265
-
266
- public function testBuildsASampleNotificationForATransactionDisbursedWebhook()
267
- {
268
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
269
- Braintree\WebhookNotification::TRANSACTION_DISBURSED,
270
- "my_id"
271
- );
272
-
273
- $webhookNotification = Braintree\WebhookNotification::parse(
274
- $sampleNotification['bt_signature'],
275
- $sampleNotification['bt_payload']
276
- );
277
-
278
- $this->assertEquals(Braintree\WebhookNotification::TRANSACTION_DISBURSED, $webhookNotification->kind);
279
- $this->assertEquals("my_id", $webhookNotification->transaction->id);
280
- $this->assertEquals(100, $webhookNotification->transaction->amount);
281
- $this->assertNotNull($webhookNotification->transaction->disbursementDetails->disbursementDate);
282
- }
283
-
284
- public function testBuildsASampleNotificationForADisputeOpenedWebhook()
285
- {
286
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
287
- Braintree\WebhookNotification::DISPUTE_OPENED,
288
- "my_id"
289
- );
290
-
291
- $webhookNotification = Braintree\WebhookNotification::parse(
292
- $sampleNotification['bt_signature'],
293
- $sampleNotification['bt_payload']
294
- );
295
-
296
- $this->assertEquals(Braintree\WebhookNotification::DISPUTE_OPENED, $webhookNotification->kind);
297
- $this->assertEquals("my_id", $webhookNotification->dispute->id);
298
- $this->assertEquals(Braintree\Dispute::OPEN, $webhookNotification->dispute->status);
299
- $this->assertEquals(Braintree\Dispute::CHARGEBACK, $webhookNotification->dispute->kind);
300
- $this->assertEquals(new DateTime('2014-03-21'), $webhookNotification->dispute->dateOpened);
301
- }
302
-
303
- public function testBuildsASampleNotificationForADisputeLostWebhook()
304
- {
305
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
306
- Braintree\WebhookNotification::DISPUTE_LOST,
307
- "my_id"
308
- );
309
-
310
- $webhookNotification = Braintree\WebhookNotification::parse(
311
- $sampleNotification['bt_signature'],
312
- $sampleNotification['bt_payload']
313
- );
314
-
315
- $this->assertEquals(Braintree\WebhookNotification::DISPUTE_LOST, $webhookNotification->kind);
316
- $this->assertEquals("my_id", $webhookNotification->dispute->id);
317
- $this->assertEquals(Braintree\Dispute::LOST, $webhookNotification->dispute->status);
318
- $this->assertEquals(Braintree\Dispute::CHARGEBACK, $webhookNotification->dispute->kind);
319
- $this->assertEquals(new DateTime('2014-03-21'), $webhookNotification->dispute->dateOpened);
320
- }
321
-
322
- public function testBuildsASampleNotificationForADisputeWonWebhook()
323
- {
324
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
325
- Braintree\WebhookNotification::DISPUTE_WON,
326
- "my_id"
327
- );
328
-
329
- $webhookNotification = Braintree\WebhookNotification::parse(
330
- $sampleNotification['bt_signature'],
331
- $sampleNotification['bt_payload']
332
- );
333
-
334
- $this->assertEquals(Braintree\WebhookNotification::DISPUTE_WON, $webhookNotification->kind);
335
- $this->assertEquals("my_id", $webhookNotification->dispute->id);
336
- $this->assertEquals(Braintree\Dispute::WON, $webhookNotification->dispute->status);
337
- $this->assertEquals(Braintree\Dispute::CHARGEBACK, $webhookNotification->dispute->kind);
338
- $this->assertEquals(new DateTime('2014-03-21'), $webhookNotification->dispute->dateOpened);
339
- $this->assertEquals(new DateTime('2014-03-22'), $webhookNotification->dispute->dateWon);
340
- }
341
-
342
- public function testBuildsASampleNotificationForADisbursementExceptionWebhook()
343
- {
344
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
345
- Braintree\WebhookNotification::DISBURSEMENT_EXCEPTION,
346
- "my_id"
347
- );
348
-
349
- $webhookNotification = Braintree\WebhookNotification::parse(
350
- $sampleNotification['bt_signature'],
351
- $sampleNotification['bt_payload']
352
- );
353
-
354
-
355
- $this->assertEquals(Braintree\WebhookNotification::DISBURSEMENT_EXCEPTION, $webhookNotification->kind);
356
- $this->assertEquals("my_id", $webhookNotification->disbursement->id);
357
- $this->assertEquals(false, $webhookNotification->disbursement->retry);
358
- $this->assertEquals(false, $webhookNotification->disbursement->success);
359
- $this->assertEquals("bank_rejected", $webhookNotification->disbursement->exceptionMessage);
360
- $this->assertEquals(100.00, $webhookNotification->disbursement->amount);
361
- $this->assertEquals("update_funding_information", $webhookNotification->disbursement->followUpAction);
362
- $this->assertEquals("merchant_account_token", $webhookNotification->disbursement->merchantAccount->id);
363
- $this->assertEquals(new DateTime("2014-02-10"), $webhookNotification->disbursement->disbursementDate);
364
- $this->assertEquals(["asdfg", "qwert"], $webhookNotification->disbursement->transactionIds);
365
- }
366
-
367
- public function testBuildsASampleNotificationForADisbursementWebhook()
368
- {
369
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
370
- Braintree\WebhookNotification::DISBURSEMENT,
371
- "my_id"
372
- );
373
-
374
- $webhookNotification = Braintree\WebhookNotification::parse(
375
- $sampleNotification['bt_signature'],
376
- $sampleNotification['bt_payload']
377
- );
378
-
379
-
380
- $this->assertEquals(Braintree\WebhookNotification::DISBURSEMENT, $webhookNotification->kind);
381
- $this->assertEquals("my_id", $webhookNotification->disbursement->id);
382
- $this->assertEquals(false, $webhookNotification->disbursement->retry);
383
- $this->assertEquals(true, $webhookNotification->disbursement->success);
384
- $this->assertEquals(NULL, $webhookNotification->disbursement->exceptionMessage);
385
- $this->assertEquals(100.00, $webhookNotification->disbursement->amount);
386
- $this->assertEquals(NULL, $webhookNotification->disbursement->followUpAction);
387
- $this->assertEquals("merchant_account_token", $webhookNotification->disbursement->merchantAccount->id);
388
- $this->assertEquals(new DateTime("2014-02-10"), $webhookNotification->disbursement->disbursementDate);
389
- $this->assertEquals(["asdfg", "qwert"], $webhookNotification->disbursement->transactionIds);
390
- }
391
- public function testBuildsASampleNotificationForAPartnerMerchantConnectedWebhook()
392
- {
393
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
394
- Braintree\WebhookNotification::PARTNER_MERCHANT_CONNECTED,
395
- "my_id"
396
- );
397
-
398
- $webhookNotification = Braintree\WebhookNotification::parse(
399
- $sampleNotification['bt_signature'],
400
- $sampleNotification['bt_payload']
401
- );
402
-
403
- $this->assertEquals(Braintree\WebhookNotification::PARTNER_MERCHANT_CONNECTED, $webhookNotification->kind);
404
- $this->assertEquals("public_id", $webhookNotification->partnerMerchant->merchantPublicId);
405
- $this->assertEquals("public_key", $webhookNotification->partnerMerchant->publicKey);
406
- $this->assertEquals("private_key", $webhookNotification->partnerMerchant->privateKey);
407
- $this->assertEquals("abc123", $webhookNotification->partnerMerchant->partnerMerchantId);
408
- $this->assertEquals("cse_key", $webhookNotification->partnerMerchant->clientSideEncryptionKey);
409
- }
410
-
411
- public function testBuildsASampleNotificationForAPartnerMerchantDisconnectedWebhook()
412
- {
413
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
414
- Braintree\WebhookNotification::PARTNER_MERCHANT_DISCONNECTED,
415
- "my_id"
416
- );
417
-
418
- $webhookNotification = Braintree\WebhookNotification::parse(
419
- $sampleNotification['bt_signature'],
420
- $sampleNotification['bt_payload']
421
- );
422
-
423
- $this->assertEquals(Braintree\WebhookNotification::PARTNER_MERCHANT_DISCONNECTED, $webhookNotification->kind);
424
- $this->assertEquals("abc123", $webhookNotification->partnerMerchant->partnerMerchantId);
425
- }
426
-
427
- public function testBuildsASampleNotificationForAPartnerMerchantDeclinedWebhook()
428
- {
429
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
430
- Braintree\WebhookNotification::PARTNER_MERCHANT_DECLINED,
431
- "my_id"
432
- );
433
-
434
- $webhookNotification = Braintree\WebhookNotification::parse(
435
- $sampleNotification['bt_signature'],
436
- $sampleNotification['bt_payload']
437
- );
438
-
439
- $this->assertEquals(Braintree\WebhookNotification::PARTNER_MERCHANT_DECLINED, $webhookNotification->kind);
440
- $this->assertEquals("abc123", $webhookNotification->partnerMerchant->partnerMerchantId);
441
- }
442
-
443
- public function testBuildsASampleNotificationForACheckWebhook()
444
- {
445
- $sampleNotification = Braintree\WebhookTesting::sampleNotification(
446
- Braintree\WebhookNotification::CHECK,
447
- ""
448
- );
449
-
450
- $webhookNotification = Braintree\WebhookNotification::parse(
451
- $sampleNotification["bt_signature"],
452
- $sampleNotification["bt_payload"]
453
- );
454
-
455
- $this->assertEquals(Braintree\WebhookNotification::CHECK, $webhookNotification->kind);
456
- }
457
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/Xml_GeneratorTest.php DELETED
@@ -1,110 +0,0 @@
1
- <?php
2
- namespace Test\Unit\Xml;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use Test\Setup;
7
- use Braintree;
8
-
9
- class GeneratorTest extends Setup
10
- {
11
- public function testSetsTypeAttributeForBooleans()
12
- {
13
- $expected = <<<XML
14
- <?xml version="1.0" encoding="UTF-8"?>
15
- <root>
16
- <yes type="boolean">true</yes>
17
- <no type="boolean">false</no>
18
- </root>
19
-
20
- XML;
21
- $xml = Braintree\Xml::buildXmlFromArray([
22
- 'root' => ['yes' => true, 'no' => false]
23
- ]);
24
- $this->assertEquals($expected, $xml);
25
- }
26
-
27
- public function testCreatesArrays()
28
- {
29
- $expected = <<<XML
30
- <?xml version="1.0" encoding="UTF-8"?>
31
- <root>
32
- <stuff type="array">
33
- <item>foo</item>
34
- <item>bar</item>
35
- </stuff>
36
- </root>
37
-
38
- XML;
39
- $xml = Braintree\Xml::buildXmlFromArray([
40
- 'root' => ['stuff' => ['foo', 'bar']]
41
- ]);
42
- $this->assertEquals($expected, $xml);
43
- }
44
-
45
- public function testCreatesWithDashes()
46
- {
47
- $expected = <<<XML
48
- <?xml version="1.0" encoding="UTF-8"?>
49
- <root>
50
- <some-stuff>
51
- <inner-foo type="integer">42</inner-foo>
52
- <bar-bar-bar type="integer">3</bar-bar-bar>
53
- </some-stuff>
54
- </root>
55
-
56
- XML;
57
- $xml = Braintree\Xml::buildXmlFromArray([
58
- 'root' => ['someStuff' => ['innerFoo' => 42, 'barBarBar' => 3]]
59
- ]);
60
- $this->assertEquals($expected, $xml);
61
- }
62
-
63
- public function testCreatesArraysWithBooleans()
64
- {
65
- $expected = <<<XML
66
- <?xml version="1.0" encoding="UTF-8"?>
67
- <root>
68
- <stuff type="array">
69
- <item>true</item>
70
- <item>false</item>
71
- </stuff>
72
- </root>
73
-
74
- XML;
75
- $xml = Braintree\Xml::buildXmlFromArray([
76
- 'root' => ['stuff' => [true, false]]
77
- ]);
78
- $this->assertEquals($expected, $xml);
79
- }
80
-
81
- public function testHandlesEmptyArrays()
82
- {
83
- $expected = <<<XML
84
- <?xml version="1.0" encoding="UTF-8"?>
85
- <root>
86
- <stuff type="array"/>
87
- </root>
88
-
89
- XML;
90
- $xml = Braintree\Xml::buildXmlFromArray([
91
- 'root' => ['stuff' => []]
92
- ]);
93
- $this->assertEquals($expected, $xml);
94
- }
95
-
96
- public function testEscapingSpecialChars()
97
- {
98
- $expected = <<<XML
99
- <?xml version="1.0" encoding="UTF-8"?>
100
- <root>
101
- <stuff>&lt;&gt;&amp;'&quot;</stuff>
102
- </root>
103
-
104
- XML;
105
- $xml = Braintree\Xml::buildXmlFromArray([
106
- 'root' => ['stuff' => '<>&\'"']
107
- ]);
108
- $this->assertEquals($expected, $xml);
109
- }
110
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
braintree_sdk/tests/unit/Xml_ParserTest.php DELETED
@@ -1,542 +0,0 @@
1
- <?php
2
- namespace Test\Unit\Xml;
3
-
4
- require_once dirname(__DIR__) . '/Setup.php';
5
-
6
- use DateTime;
7
- use DateTimeZone;
8
- use Test\Setup;
9
- use Braintree;
10
-
11
- class ParserTest extends Setup
12
- {
13
- public function testTypeCastIntegers()
14
- {
15
- $array = Braintree\Xml::buildArrayFromXml('<root><foo type="integer">123</foo></root>');
16
- $this->assertEquals($array, ['root' => ['foo' => 123]]);
17
-
18
- }
19
-
20
- public function testDashesUnderscores()
21
- {
22
- $xml =<<<XML
23
- <root>
24
- <dash-es />
25
- <under_scores />
26
- </root>
27
- XML;
28
-
29
- $array = Braintree\Xml::buildArrayFromXml($xml);
30
- $this->assertEquals(['root' =>
31
- ['dashEs' => '', 'underScores' => '']], $array);
32
- }
33
-
34
- public function testCustomFieldsUnderscore()
35
- {
36
- $xml =<<<XML
37
- <root>
38
- <custom-fields>
39
- <with-dashes>convert to underscore</with-dashes>
40
- </custom-fields>
41
- </root>
42
- XML;
43
-
44
- $array = Braintree\Xml::buildArrayFromXml($xml);
45
- $this->assertEquals(['root' =>
46
- ['customFields' => ['with_dashes' => 'convert to underscore']]], $array);
47
- }
48
-
49
- public function testNullOrEmptyString()
50
- {
51
- $xml = <<<XML
52
- <root>
53
- <a_nil_value nil="true"></a_nil_value>
54
- <an_empty_string></an_empty_string>
55
- </root>
56
- XML;
57
- $array = Braintree\Xml::buildArrayFromXml($xml);
58
- $this->assertEquals(['root' =>
59
- ['aNilValue' => null, 'anEmptyString' => '']], $array);
60
- }
61
-
62
- public function testTypeCastsDatetimes()
63
- {
64
- $xml = <<<XML
65
- <root>
66
- <created-at type="datetime">2009-10-28T10:19:49Z</created-at>
67
- </root>
68
- XML;
69
- $array = Braintree\Xml::buildArrayFromXml($xml);
70
- date_default_timezone_set('UTC');
71
- $dateTime = new DateTime('2009-10-28T10:19:49', new DateTimeZone('UTC'));
72
- $this->assertEquals(['root' => ['createdAt' => $dateTime]], $array);
73
- $this->assertInstanceOf('DateTime', $array['root']['createdAt']);
74
- }
75
-
76
- public function testTypeCastsDates()
77
- {
78
- $xml = <<<XML
79
- <root>
80
- <some-date type="date">2009-10-28</some-date>
81
- </root>
82
- XML;
83
- $array = Braintree\Xml::buildArrayFromXml($xml);
84
- date_default_timezone_set('UTC');
85
- $dateTime = new DateTime('2009-10-28', new DateTimeZone('UTC'));
86
- $this->assertEquals(['root' => ['someDate' => $dateTime]], $array);
87
- }
88
-
89
- public function testBuildsArray()
90
- {
91
- $xml = <<<XML
92
- <root>
93
- <customers type="array">
94
- <customer><name>Adam</name></customer>
95
- <customer><name>Ben</name></customer>
96
- </customers>
97
- </root>
98
- XML;
99
- $array = Braintree\Xml::buildArrayFromXml($xml);
100
- $this->assertEquals(['root' =>
101
- ['customers' =>
102
- [['name' => 'Adam'],
103
- ['name' => 'Ben']]
104
- ]
105
- ], $array
106
- );
107
-
108
- }
109
-
110
- public function testReturnsBoolean()
111
- {
112
- $xml = <<<XML
113
- <root>
114
- <casted-true type="boolean">true</casted-true>
115
- <casted-one type="boolean">1</casted-one>
116
- <casted-false type="boolean">false</casted-false>
117
- <casted-anything type="boolean">anything</casted-anything>
118
- <uncasted-true>true</uncasted-true>
119
- </root>
120
- XML;
121
- $array = Braintree\Xml::buildArrayFromXml($xml);
122
- $this->assertEquals(
123
- ['root' =>
124
- ['castedTrue' => true,
125
- 'castedOne' => true,
126
- 'castedFalse' => false,
127
- 'castedAnything' => false,
128
- 'uncastedTrue' => 'true']
129
- ], $array);
130
-
131
- }
132
-
133
- public function testEmptyArrayAndNestedElements()
134
- {
135
- $xml = <<<XML
136
- <root>
137
- <nested-values>
138
- <value>1</value>
139
- </nested-values>
140
- <no-values type="array"/>
141
- </root>
142
- XML;
143
-
144
- $array = Braintree\Xml::buildArrayFromXml($xml);
145
- $this->assertEquals(
146
- ['root' => [
147
- 'noValues' => [],
148
- 'nestedValues' => [
149
- 'value' => 1
150
- ]
151
- ]
152
- ], $array);
153
- }
154
-
155
- public function testParsingNilEqualsTrueAfterArray()
156
- {
157
- $xml = <<<XML
158
- <root>
159
- <customer>
160
- <first-name>Dan</first-name>
161
- </customer>
162
- <blank nil="true" />
163
- </root>
164
- XML;
165
- $array = Braintree\Xml::buildArrayFromXml($xml);
166
- $this->assertEquals(null, $array['root']['blank']);
167
-
168
- }
169
-
170
- public function testTransactionParsingNil()
171
- {
172
- $xml = <<<XML
173
- <transaction>
174
- <id>8ysndw</id>
175
- <status>settled</status>
176
- <type>sale</type>
177
- <currency>USD</currency>
178
- <amount>1.00</amount>
179
- <merchant-account-id>default</merchant-account-id>
180
- <order-id nil="true"></order-id>
181
- <channel nil="true"></channel>
182
- <created-at type="datetime">2010-04-01T19:32:23Z</created-at>
183
- <updated-at type="datetime">2010-04-02T08:05:35Z</updated-at>
184
- <customer>
185
- <id nil="true"></id>
186
- <first-name>First</first-name>
187
- <last-name>Last</last-name>
188
- <company nil="true"></company>
189
- <email></email>
190
- <website nil="true"></website>
191
- <phone nil="true"></phone>
192
- <fax nil="true"></fax>
193
- </customer>
194
- <billing>
195
- <id nil="true"></id>
196
- <first-name nil="true"></first-name>
197
- <last-name nil="true"></last-name>
198
- <company>Widgets Inc</company>
199
- <street-address>1234 My Street</street-address>
200
- <extended-address>Apt 1</extended-address>
201
- <locality>Ottawa</locality>
202
- <region>ON</region>
203
- <postal-code>K1C2N6</postal-code>
204
- <country-name>Canada</country-name>
205
- </billing>
206
- <refund-id nil="true"></refund-id>
207
- <shipping>
208
- <id nil="true"></id>
209
- <first-name nil="true"></first-name>
210
- <last-name nil="true"></last-name>
211
- <company nil="true"></company>
212
- <street-address nil="true"></street-address>
213
- <extended-address nil="true"></extended-address>
214
- <locality nil="true"></locality>
215
- <region nil="true"></region>
216
- <postal-code nil="true"></postal-code>
217
- <country-name nil="true"></country-name>
218
- </shipping>
219
- <custom-fields>
220
- </custom-fields>
221
- <avs-error-response-code nil="true"></avs-error-response-code>
222
- <avs-postal-code-response-code>M</avs-postal-code-response-code>
223
- <avs-street-address-response-code>M</avs-street-address-response-code>
224
- <cvv-response-code>M</cvv-response-code>
225
- <processor-authorization-code>13390</processor-authorization-code>
226
- <processor-response-code>1000</processor-response-code>
227
- <processor-response-text>Approved</processor-response-text>
228
- <credit-card>
229
- <token nil="true"></token>
230
- <bin>510510</bin>
231
- <last-4>5100</last-4>
232
- <card-type>MasterCard</card-type>
233
- <expiration-month>09</expiration-month>
234
- <expiration-year>2011</expiration-year>
235
- <customer-location>US</customer-location>
236
- <cardholder-name nil="true"></cardholder-name>
237
- </credit-card>
238
- <status-history type="array">
239
- <status-event>
240
- <timestamp type="datetime">2010-04-01T19:32:24Z</timestamp>
241
- <status>authorized</status>
242
- <amount>1.00</amount>
243
- <user>dmanges-am</user>
244
- <transaction-source>API</transaction-source>
245
- </status-event>
246
- <status-event>
247
- <timestamp type="datetime">2010-04-01T19:32:25Z</timestamp>
248
- <status>submitted_for_settlement</status>
249
- <amount>1.00</amount>
250
- <user>dmanges-am</user>
251
- <transaction-source>API</transaction-source>
252
- </status-event>
253
- <status-event>
254
- <timestamp type="datetime">2010-04-02T08:05:36Z</timestamp>
255
- <status>settled</status>
256
- <amount>1.00</amount>
257
- <user nil="true"></user>
258
- <transaction-source></transaction-source>
259
- </status-event>
260
- </status-history>
261
- </transaction>
262
- XML;
263
- $array = Braintree\Xml::buildArrayFromXml($xml);
264
- $this->assertEquals(null, $array['transaction']['avsErrorResponseCode']);
265
- $this->assertEquals(null, $array['transaction']['refundId']);
266
- $this->assertEquals(null, $array['transaction']['orderId']);
267
- $this->assertEquals(null, $array['transaction']['channel']);
268
- $this->assertEquals(null, $array['transaction']['customer']['fax']);
269
- $this->assertEquals(null, $array['transaction']['creditCard']['token']);
270
- $this->assertEquals(null, $array['transaction']['creditCard']['cardholderName']);
271
- $this->assertEquals('First', $array['transaction']['customer']['firstName']);
272
- $this->assertEquals('Approved', $array['transaction']['processorResponseText']);
273
-
274
- }
275
-
276
- public function testParsingWithNodeHavingSameNameAsNodesDirectlyUnderCollection()
277
- {
278
- $xml = <<<END
279
- <foos type="collection">
280
- <page-size>50</page-size>
281
- <bar>
282
- <baz>one</baz>
283
- </bar>
284
- <bar>
285
- <baz>two</baz>
286
- <bar>bug was here</bar>
287
- </bar>
288
- </foos>
289
- END;
290
- $array = Braintree\Xml::buildArrayFromXml($xml);
291
- $this->assertEquals(['baz' => 'two', 'bar' => 'bug was here'], $array['foos']['bar'][1]);
292
- }
293
-
294
- public function testParsingCreditCardSearchResults()
295
- {
296
- $xml = <<<END
297
- <payment-methods type="collection">
298
- <current-page-number type="integer">1</current-page-number>
299
- <page-size type="integer">50</page-size>
300
- <total-items type="integer">8</total-items>
301
- <credit-card>
302
- <bin>411111</bin>
303
- <cardholder-name>John Doe</cardholder-name>
304
- <card-type>Visa</card-type>
305
- <created-at type="datetime">2010-07-02T15:50:51Z</created-at>
306
- <customer-id>589636</customer-id>
307
- <default type="boolean">true</default>
308
- <expiration-month>05</expiration-month>
309
- <expiration-year>2009</expiration-year>
310
- <expired type="boolean">true</expired>
311
- <customer-location>US</customer-location>
312
- <last-4>1111</last-4>
313
- <subscriptions type="array"/>
314
- <token>22pb</token>
315
- <updated-at type="datetime">2010-07-02T15:50:51Z</updated-at>
316
- </credit-card>
317
- <credit-card>
318
- <bin>411111</bin>
319
- <cardholder-name></cardholder-name>
320
- <card-type>Visa</card-type>
321
- <created-at type="datetime">2010-07-02T15:52:09Z</created-at>
322
- <customer-id>613603</customer-id>
323
- <default type="boolean">false</default>
324
- <expiration-month>05</expiration-month>
325
- <expiration-year>2009</expiration-year>
326
- <expired type="boolean">true</expired>
327
- <customer-location>US</customer-location>
328
- <last-4>1111</last-4>
329
- <subscriptions type="array">
330
- <subscription>
331
- <id>hzjh8b</id>
332
- <price>54.32</price>
333
- <plan-id>integration_trialless_plan</plan-id>
334
- <first-billing-date type="date">2010-07-02</first-billing-date>
335
- <next-billing-date type="date">2010-08-02</next-billing-date>
336
- <billing-period-start-date type="date">2010-07-02</billing-period-start-date>
337
- <billing-period-end-date type="date">2010-08-01</billing-period-end-date>
338
- <merchant-account-id>sandbox_credit_card</merchant-account-id>
339
- <trial-period type="boolean">false</trial-period>
340
- <status>Active</status>
341
- <failure-count type="integer">0</failure-count>
342
- <payment-method-token>3wx6</payment-method-token>
343
- <trial-duration nil="true"></trial-duration>
344
- <trial-duration-unit nil="true"></trial-duration-unit>
345
- <transactions type="array">
346
- <transaction>
347
- <id>2dpk76</id>
348
- <status>submitted_for_settlement</status>
349
- <type>sale</type>
350
- <currency-iso-code>USD</currency-iso-code>
351
- <amount>54.32</amount>
352
- <merchant-account-id>sandbox_credit_card</merchant-account-id>
353
- <order-id nil="true"></order-id>
354
- <channel nil="true"></channel>
355
- <created-at type="datetime">2010-07-02T15:52:09Z</created-at>
356
- <updated-at type="datetime">2010-07-02T15:52:09Z</updated-at>
357
- <customer>
358
- <id>613603</id>
359
- <first-name>Mike</first-name>
360
- <last-name>Jones</last-name>
361
- <company nil="true"></company>
362
- <email nil="true"></email>
363
- <website nil="true"></website>
364
- <phone nil="true"></phone>
365
- <fax nil="true"></fax>
366
- </customer>
367
- <billing>
368
- <id nil="true"></id>
369
- <first-name nil="true"></first-name>
370
- <last-name nil="true"></last-name>
371
- <company nil="true"></company>
372
- <street-address nil="true"></street-address>
373
- <extended-address nil="true"></extended-address>
374
- <locality nil="true"></locality>
375
- <region nil="true"></region>
376
- <postal-code nil="true"></postal-code>
377
- <country-name nil="true"></country-name>
378
- <country-code-alpha2 nil="true"></country-code-alpha2>
379
- <country-code-alpha3 nil="true"></country-code-alpha3>
380
- <country-code-numeric nil="true"></country-code-numeric>
381
- </billing>
382
- <refund-id nil="true"></refund-id>
383
- <refunded-transaction-id nil="true"></refunded-transaction-id>
384
- <shipping>
385
- <id nil="true"></id>
386
- <first-name nil="true"></first-name>
387
- <last-name nil="true"></last-name>
388
- <company nil="true"></company>
389
- <street-address nil="true"></street-address>
390
- <extended-address nil="true"></extended-address>
391
- <locality nil="true"></locality>
392
- <region nil="true"></region>
393
- <postal-code nil="true"></postal-code>
394
- <country-name nil="true"></country-name>
395
- <country-code-alpha2 nil="true"></country-code-alpha2>
396
- <country-code-alpha3 nil="true"></country-code-alpha3>
397
- <country-code-numeric nil="true"></country-code-numeric>
398
- </shipping>
399
- <custom-fields>
400
- </custom-fields>
401
- <avs-error-response-code nil="true"></avs-error-response-code>
402
- <avs-postal-code-response-code>I</avs-postal-code-response-code>
403
- <avs-street-address-response-code>I</avs-street-address-response-code>
404
- <cvv-response-code>I</cvv-response-code>
405
- <gateway-rejection-reason nil="true"></gateway-rejection-reason>
406
- <processor-authorization-code>9ZR5QB</processor-authorization-code>
407
- <processor-response-code>1000</processor-response-code>
408
- <processor-response-text>Approved</processor-response-text>
409
- <credit-card>
410
- <token>sb8w</token>
411
- <bin>411111</bin>
412
- <last-4>1111</last-4>
413
- <card-type>Visa</card-type>
414
- <expiration-month>05</expiration-month>
415
- <expiration-year>2010</expiration-year>
416
- <customer-location>US</customer-location>
417
- <cardholder-name></cardholder-name>
418
- </credit-card>
419
- <status-history type="array">
420
- <status-event>
421
- <timestamp type="datetime">2010-07-02T15:52:09Z</timestamp>
422
- <status>authorized</status>
423
- <amount>54.32</amount>
424
- <user>merchant</user>
425
- <transaction-source>Recurring</transaction-source>
426
- </status-event>
427
- <status-event>
428
- <timestamp type="datetime">2010-07-02T15:52:09Z</timestamp>
429
- <status>submitted_for_settlement</status>
430
- <amount>54.32</amount>
431
- <user>merchant</user>
432
- <transaction-source>Recurring</transaction-source>
433
- </status-event>
434
- </status-history>
435
- <subscription-id>hzjh8b</subscription-id>
436
- </transaction>
437
- </transactions>
438
- </subscription>
439
- </subscriptions>
440
- <token>3wx6</token>
441
- <updated-at type="datetime">2010-07-02T15:52:09Z</updated-at>
442
- </credit-card>
443
- </payment-methods>
444
- END;
445
- $array = Braintree\Xml::buildArrayFromXml($xml);
446
- $creditCards = $array['paymentMethods']['creditCard'];
447
- $creditCardWithSubscription = $creditCards[1];
448
- $transaction = $creditCardWithSubscription['subscriptions'][0]['transactions'][0];
449
- $this->assertEquals('411111', $transaction['creditCard']['bin']);
450
- $this->assertEquals('1111', $transaction['creditCard']['last4']);
451
- $this->assertEquals('Visa', $transaction['creditCard']['cardType']);
452
- }
453
-
454
- public function xmlAndBack($array)
455
- {
456
- $xml = Braintree\Xml::buildXmlFromArray($array);
457
- return Braintree\Xml::buildArrayFromXml($xml);
458
-
459
- }
460
-
461
- public function testSimpleCaseRoundtrip()
462
- {
463
- $array = ['root' => [
464
- 'foo' => 'fooValue',
465
- 'bar' => 'barValue']
466
- ];
467
-
468
- $array2 = $this->xmlAndBack($array);
469
- $this->assertEquals($array, $array2);
470
- }
471
-
472
- public function testArrayRoundtrip()
473
- {
474
- $array = ['root' => [
475
- 'items' => [
476
- ['name' => 'first'],
477
- ['name' => 'second'],
478
- ]
479
- ]];
480
- $array2 = $this->xmlAndBack($array);
481
- $this->assertEquals($array, $array2);
482
- }
483
-
484
- public function testBooleanRoundtrip()
485
- {
486
- $array = ['root' => [
487
- 'stringTrue' => true,
488
- 'boolTrue' => true,
489
- 'stringFalse' => false,
490
- 'boolFalse' => false,
491
- ]];
492
- $array2 = $this->xmlAndBack($array);
493
- $this->assertEquals($array, $array2);
494
-
495
- }
496
- public function testTimestampRoundtrip()
497
- {
498
- date_default_timezone_set('UTC');
499
- $array = ['root' => [
500
- 'aTimestamp' => date('D M d H:i:s e Y', mktime(1, 2, 3, 10, 28, 2009)),
501
- ]];
502
- $array2 = $this->xmlAndBack($array);
503
- $this->assertEquals($array, $array2);
504
-
505
- }
506
-
507
- public function testNullvsEmptyStringToXml()
508
- {
509
- $array = ['root' => [
510
- 'anEmptyString' => '',
511
- 'aNullValue' => null,
512
- ]];
513
- $xml = Braintree\Xml::buildXmlFromArray($array);
514
- $xml2 =<<<XML
515
- <?xml version="1.0" encoding="UTF-8"?>
516
- <root>
517
- <an-empty-string></an-empty-string>
518
- <a-null-value nil="true"></a-null-value>
519
- </root>
520
-
521
- XML;
522
-
523
- $this->assertEquals($xml, $xml2);
524
- }
525
-
526
- public function testIncludesTheEncodingRoundtrip()
527
- {
528
- $array = ['root' => [
529
- 'root' => 'bar',
530
- ]];
531
- $xml = Braintree\Xml::buildXmlFromArray($array);
532
- $this->assertRegExp('<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>', $xml);
533
-
534
- }
535
-
536
- public function testRootNodeAndStringRoundtrip()
537
- {
538
- $array = ['id' => '123'];
539
- $array2 = $this->xmlAndBack($array);
540
- $this->assertEquals($array, $array2);
541
- }
542
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
class-wc-braintree.php ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ // if WooCommerce is inactive, render a notice and bail
30
+ if ( ! WC_Braintree::is_woocommerce_active() ) {
31
+
32
+ add_action( 'admin_notices', function() {
33
+
34
+ echo '<div class="error"><p>';
35
+ esc_html_e( 'WooCommerce PayPal Powered by Braintree is inactive because WooCommerce is not installed.', 'woocommerce-gateway-paypal-powered-by-braintree' );
36
+ echo '</p></div>';
37
+
38
+ } );
39
+
40
+ return;
41
+ }
42
+
43
+
44
+ /**
45
+ * # WooCommerce Gateway Braintree Main Plugin Class
46
+ *
47
+ * ## Plugin Overview
48
+ *
49
+ * This plugin adds Braintree as a payment gateway. Braintree's javascript library is used to encrypt the credit card
50
+ * fields prior to form submission, so it acts like a direct gateway but without the burden of heavy PCI compliance. Logged
51
+ * in customers' credit cards are saved to the braintree vault by default. Subscriptions and Pre-Orders are supported via
52
+ * the Add-Ons class.
53
+ *
54
+ * ## Admin Considerations
55
+ *
56
+ * A user view/edit field is added for the Braintree customer ID so it can easily be changed by the admin.
57
+ *
58
+ * ## Frontend Considerations
59
+ *
60
+ * Both the payment fields on checkout (and checkout->pay) and the My cards section on the My Account page are template
61
+ * files for easy customization.
62
+ *
63
+ * ## Database
64
+ *
65
+ * ### Global Settings
66
+ *
67
+ * + `woocommerce_braintree_settings` - the serialized braintree settings array
68
+ *
69
+ * ### Options table
70
+ *
71
+ * + `wc_braintree_version` - the current plugin version, set on install/upgrade
72
+ *
73
+ * ### Order Meta
74
+ *
75
+ * + `_wc_braintree_trans_id` - the braintree transaction ID
76
+ * + `_wc_braintree_trans_mode` - the environment the braintree transaction was created in
77
+ * + `_wc_braintree_card_type` - the card type used for the order
78
+ * + `_wc_braintree_card_last_four` - the last four digits of the card used for the order
79
+ * + `_wc_braintree_card_exp_date` - the expiration date of the card used for the order
80
+ * + `_wc_braintree_customer_id` - the braintree customer ID for the order, set only if the customer is logged in/creating an account
81
+ * + `_wc_braintree_cc_token` - the braintree token for the credit card used for the order, set only if the customer is logged in/creating an account
82
+ *
83
+ * ### User Meta
84
+ * + `_wc_braintree_customer_id` - the braintree customer ID for the user
85
+ *
86
+ */
87
+ class WC_Braintree extends WC_Braintree_Framework\SV_WC_Payment_Gateway_Plugin {
88
+
89
+
90
+ /** plugin version number */
91
+ const VERSION = '2.0.0';
92
+
93
+ /** @var WC_Braintree single instance of this plugin */
94
+ protected static $instance;
95
+
96
+ /** plugin id */
97
+ const PLUGIN_ID = 'braintree';
98
+
99
+ /** credit card gateway class name */
100
+ const CREDIT_CARD_GATEWAY_CLASS_NAME = 'WC_Gateway_Braintree_Credit_Card';
101
+
102
+ /** credit card gateway ID */
103
+ const CREDIT_CARD_GATEWAY_ID = 'braintree_credit_card';
104
+
105
+ /** PayPal gateway class name */
106
+ const PAYPAL_GATEWAY_CLASS_NAME = 'WC_Gateway_Braintree_PayPal';
107
+
108
+ /** PayPal gateway ID */
109
+ const PAYPAL_GATEWAY_ID = 'braintree_paypal';
110
+
111
+ /** @var \WC_Braintree_PayPal_Cart the PayPal cart handler instance */
112
+ protected $paypal_cart;
113
+
114
+ /** @var \WC_Braintree_Frontend the frontend instance */
115
+ protected $frontend;
116
+
117
+
118
+ /**
119
+ * Initializes the plugin
120
+ *
121
+ * @since 2.0
122
+ */
123
+ public function __construct() {
124
+
125
+ parent::__construct(
126
+ self::PLUGIN_ID,
127
+ self::VERSION,
128
+ array(
129
+ 'text_domain' => 'woocommerce-gateway-paypal-powered-by-braintree',
130
+ 'gateways' => array(
131
+ self::CREDIT_CARD_GATEWAY_ID => self::CREDIT_CARD_GATEWAY_CLASS_NAME,
132
+ self::PAYPAL_GATEWAY_ID => self::PAYPAL_GATEWAY_CLASS_NAME,
133
+ ),
134
+ 'require_ssl' => false,
135
+ 'supports' => array(
136
+ self::FEATURE_CAPTURE_CHARGE,
137
+ self::FEATURE_MY_PAYMENT_METHODS,
138
+ self::FEATURE_CUSTOMER_ID,
139
+ ),
140
+ 'dependencies' => array( 'curl', 'dom', 'hash', 'openssl', 'SimpleXML', 'xmlwriter' ),
141
+ )
142
+ );
143
+
144
+ // include required files
145
+ $this->includes();
146
+
147
+ // handle Braintree Auth connect/disconnect
148
+ add_action( 'admin_init', array( $this, 'handle_auth_connect' ) );
149
+ add_action( 'admin_init', array( $this, 'handle_auth_disconnect' ) );
150
+
151
+ // maybe initialize the PayPal cart handler on the cart page
152
+ add_action( 'init', array( $this, 'maybe_init_paypal_cart' ) );
153
+ }
154
+
155
+
156
+ /**
157
+ * Include required files
158
+ *
159
+ * @since 2.0
160
+ */
161
+ public function includes() {
162
+
163
+ // frontend instance
164
+ if ( ! is_admin() && ! is_ajax() ) {
165
+ $this->frontend = $this->load_class( '/includes/class-wc-braintree-frontend.php', 'WC_Braintree_Frontend' );
166
+ }
167
+
168
+ // gateways
169
+ require_once( $this->get_plugin_path() . '/includes/class-wc-gateway-braintree.php' );
170
+ require_once( $this->get_plugin_path() . '/includes/class-wc-gateway-braintree-credit-card.php' );
171
+ require_once( $this->get_plugin_path() . '/includes/class-wc-gateway-braintree-paypal.php' );
172
+
173
+ // payment method
174
+ require_once( $this->get_plugin_path() . '/includes/class-wc-braintree-payment-method-handler.php' );
175
+ require_once( $this->get_plugin_path() . '/includes/class-wc-braintree-payment-method.php' );
176
+
177
+ // payment forms
178
+ require_once( $this->get_plugin_path() . '/includes/payment-forms/abstract-wc-braintree-payment-form.php' );
179
+ require_once( $this->get_plugin_path() . '/includes/payment-forms/class-wc-braintree-hosted-fields-payment-form.php' );
180
+ require_once( $this->get_plugin_path() . '/includes/payment-forms/class-wc-braintree-paypal-payment-form.php' );
181
+
182
+ require_once( $this->get_plugin_path() . '/includes/class-wc-braintree-paypal-cart.php' );
183
+ }
184
+
185
+
186
+ /**
187
+ * Gets the deprecated hooks and their replacements, if any.
188
+ *
189
+ * @since 2.0.0
190
+ * @return array
191
+ */
192
+ protected function get_deprecated_hooks() {
193
+
194
+ $hooks = array(
195
+ 'wc_gateway_paypal_braintree_card_icons_image_url' => array(
196
+ 'version' => '2.0.0',
197
+ 'removed' => true,
198
+ 'replacement' => 'wc_braintree_credit_card_icon',
199
+ 'map' => true,
200
+ ),
201
+ 'wc_gateway_paypal_braintree_sale_args' => array(
202
+ 'version' => '2.0.0',
203
+ 'removed' => true,
204
+ 'replacement' => 'wc_braintree_transaction_data',
205
+ 'map' => true,
206
+ ),
207
+ 'wc_gateway_paypal_braintree_data' => array(
208
+ 'version' => '2.0.0',
209
+ 'removed' => true, // TODO: determine if anything can be mapped here
210
+ ),
211
+ );
212
+
213
+ return $hooks;
214
+ }
215
+
216
+
217
+ /**
218
+ * Handles the Braintree Auth connection response.
219
+ *
220
+ * @since 2.0.0
221
+ */
222
+ public function handle_auth_connect() {
223
+
224
+ // if this is not a gateway settings page, bail
225
+ if ( ! $this->is_plugin_settings() ) {
226
+ return;
227
+ }
228
+
229
+ // if there was already a successful disconnect, just display a notice
230
+ if ( $connected = WC_Braintree_Framework\SV_WC_Helper::get_request( 'wc_braintree_connected' ) ) {
231
+
232
+ if ( $connected ) {
233
+ $message = __( 'Connected successfully.', 'woocommerce-gateway-paypal-powered-by-braintree' );
234
+ $class = 'updated';
235
+ } else {
236
+ $message = __( 'There was an error connecting your Braintree account. Please try again.', 'woocommerce-gateway-paypal-powered-by-braintree' );
237
+ $class = 'error';
238
+ }
239
+
240
+ $this->get_admin_notice_handler()->add_admin_notice(
241
+ $message,
242
+ 'connection-notice',
243
+ array(
244
+ 'dismissible' => true,
245
+ 'notice_class' => $class,
246
+ )
247
+ );
248
+
249
+ return;
250
+ }
251
+
252
+ $nonce = WC_Braintree_Framework\SV_WC_Helper::get_request( 'wc_paypal_braintree_admin_nonce' );
253
+
254
+ // if no nonce is present, then this probably wasn't a connection response
255
+ if ( ! $nonce ) {
256
+ return;
257
+ }
258
+
259
+ // if there is already a stored access token, bail
260
+ if ( $this->get_gateway()->get_auth_access_token() ) {
261
+ return;
262
+ }
263
+
264
+ // verify the nonce
265
+ if ( ! wp_verify_nonce( $nonce, 'connect_paypal_braintree' ) ) {
266
+ wp_die( __( 'Invalid connection request', 'woocommerce-gateway-paypal-powered-by-braintree' ) );
267
+ }
268
+
269
+ if ( $access_token = sanitize_text_field( urldecode( WC_Braintree_Framework\SV_WC_Helper::get_request( 'braintree_access_token' ) ) ) ) {
270
+
271
+ update_option( 'wc_braintree_auth_access_token', $access_token );
272
+
273
+ list( $token_key, $environment, $merchant_id, $raw_token ) = explode( '$', $access_token );
274
+
275
+ update_option( 'wc_braintree_auth_environment', $environment );
276
+ update_option( 'wc_braintree_auth_merchant_id', $merchant_id );
277
+
278
+ $connected = true;
279
+
280
+ } else {
281
+
282
+ $this->log( 'Could not connect to Braintree. Invalid access token', $this->get_gateway()->get_id() );
283
+
284
+ $connected = false;
285
+ }
286
+
287
+ wp_safe_redirect( add_query_arg( 'wc_braintree_connected', $connected, $this->get_settings_url() ) );
288
+ exit;
289
+ }
290
+
291
+
292
+ /**
293
+ * Handles a Braintree Auth disconnect request.
294
+ *
295
+ * @since 2.0.0
296
+ */
297
+ public function handle_auth_disconnect() {
298
+
299
+ // if this is not a gateway settings page, bail
300
+ if ( ! $this->is_plugin_settings() ) {
301
+ return;
302
+ }
303
+
304
+ // if there was already a successful disconnect, just display a notice
305
+ if ( WC_Braintree_Framework\SV_WC_Helper::get_request( 'wc_braintree_disconnected' ) ) {
306
+
307
+ $this->get_admin_notice_handler()->add_admin_notice(
308
+ __( 'Disconnected successfully.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
309
+ 'disconnect-successful-notice',
310
+ array(
311
+ 'dismissible' => true,
312
+ 'notice_class' => 'updated',
313
+ )
314
+ );
315
+
316
+ return;
317
+ }
318
+
319
+ // if this is not a disconnect request, bail
320
+ if ( ! WC_Braintree_Framework\SV_WC_Helper::get_request( 'disconnect_paypal_braintree' ) ) {
321
+ return;
322
+ }
323
+
324
+ $nonce = WC_Braintree_Framework\SV_WC_Helper::get_request( 'wc_paypal_braintree_admin_nonce' );
325
+
326
+ // if no nonce is present, then this probably wasn't a disconnect request
327
+ if ( ! $nonce ) {
328
+ return;
329
+ }
330
+
331
+ // verify the nonce
332
+ if ( ! wp_verify_nonce( $nonce, 'disconnect_paypal_braintree' ) ) {
333
+ wp_die( __( 'Invalid disconnect request', 'woocommerce-gateway-paypal-powered-by-braintree' ) );
334
+ }
335
+
336
+ delete_option( 'wc_braintree_auth_access_token' );
337
+ delete_option( 'wc_braintree_auth_environment' );
338
+ delete_option( 'wc_braintree_auth_merchant_id' );
339
+
340
+ wp_safe_redirect( add_query_arg( 'wc_braintree_disconnected', true, $this->get_settings_url() ) );
341
+ exit;
342
+ }
343
+
344
+
345
+ /**
346
+ * Initializes the PayPal cart handler.
347
+ *
348
+ * @since 2.0.0
349
+ */
350
+ public function maybe_init_paypal_cart() {
351
+
352
+ $gateway = $this->get_gateway( self::PAYPAL_GATEWAY_ID );
353
+
354
+ if ( ! $gateway->is_available() ) {
355
+ return;
356
+ }
357
+
358
+ $this->paypal_cart = new WC_Braintree_PayPal_Cart( $gateway );
359
+ }
360
+
361
+
362
+ /**
363
+ * Gets the PayPal cart handler instance.
364
+ *
365
+ * @since 2.0.0
366
+ * @return \WC_Braintree_PayPal_Cart
367
+ */
368
+ public function get_paypal_cart_instance() {
369
+
370
+ return $this->paypal_cart;
371
+ }
372
+
373
+
374
+ /** Admin methods ******************************************************/
375
+
376
+
377
+ /**
378
+ * Render a notice for the user to select their desired export format
379
+ *
380
+ * @since 2.1.3
381
+ * @see SV_WC_Plugin::add_admin_notices()
382
+ */
383
+ public function add_admin_notices() {
384
+
385
+ // show any dependency notices
386
+ parent::add_admin_notices();
387
+
388
+ $credit_card_gateway = $this->get_gateway( self::CREDIT_CARD_GATEWAY_ID );
389
+
390
+ if ( $credit_card_gateway->is_advanced_fraud_tool_enabled() && ! $this->get_admin_notice_handler()->is_notice_dismissed( 'fraud-tool-notice' ) ) {
391
+
392
+ $this->get_admin_notice_handler()->add_admin_notice(
393
+ sprintf( __( 'Heads up! You\'ve enabled advanced fraud tools for Braintree. Please make sure that advanced fraud tools are also enabled in your Braintree account. Need help? See the %1$sdocumentation%2$s.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
394
+ '<a target="_blank" href="' . $this->get_documentation_url() . '">',
395
+ '</a>'
396
+ ), 'fraud-tool-notice', array( 'always_show_on_settings' => false, 'dismissible' => true, 'notice_class' => 'updated' )
397
+ );
398
+ }
399
+
400
+ $credit_card_settings = get_option( 'woocommerce_braintree_credit_card_settings' );
401
+ $paypal_settings = get_option( 'woocommerce_braintree_paypal_settings' );
402
+
403
+ // install notice
404
+ if ( ! $this->is_plugin_settings() ) {
405
+
406
+ if ( ( $credit_card_gateway->can_connect() && ! $credit_card_gateway->is_connected() ) && empty( $credit_card_settings ) && empty( $paypal_settings ) && ! $this->get_admin_notice_handler()->is_notice_dismissed( 'install-notice' ) ) {
407
+
408
+ $this->get_admin_notice_handler()->add_admin_notice(
409
+ sprintf(
410
+ /** translators: Placeholders: %1$s - <a> tag, %2$s - </a> tag */
411
+ __( 'PayPal powered by Braintree is almost ready. To get started, %1$sconnect your Braintree account%2$s.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
412
+ '<a href="' . esc_url( $this->get_settings_url() ) . '">', '</a>'
413
+ ), 'install-notice', array( 'notice_class' => 'updated' )
414
+ );
415
+
416
+ } elseif ( 'yes' === get_option( 'wc_braintree_legacy_migrated' ) ) {
417
+
418
+ delete_option( 'wc_braintree_legacy_migrated' );
419
+
420
+ $this->get_admin_notice_handler()->add_admin_notice(
421
+ sprintf(
422
+ /** translators: Placeholders: %1$s - <a> tag, %2$s - </a> tag */
423
+ __( 'Upgrade successful! WooCommerce Braintree deactivated, and PayPal Powered by Braintree has been %1$sconfigured with your previous settings%2$s.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
424
+ '<a href="' . esc_url( $this->get_settings_url() ) . '">', '</a>'
425
+ ), 'install-notice', array( 'notice_class' => 'updated' )
426
+ );
427
+ }
428
+ }
429
+
430
+ // SSL check (only when PayPal is enabled in production mode)
431
+ if ( isset( $paypal_settings['enabled'] ) && 'yes' == $paypal_settings['enabled'] ) {
432
+ if ( isset( $paypal_settings['environment'] ) && 'production' == $paypal_settings['environment'] ) {
433
+
434
+ if ( 'no' === get_option( 'woocommerce_force_ssl_checkout' ) && ! $this->get_admin_notice_handler()->is_notice_dismissed( 'ssl-recommended-notice' ) ) {
435
+
436
+ $this->get_admin_notice_handler()->add_admin_notice( __( 'WooCommerce is not being forced over SSL -- Using PayPal with Braintree requires that checkout to be forced over SSL.', 'woocommerce-gateway-paypal-powered-by-braintree' ), 'ssl-recommended-notice' );
437
+ }
438
+ }
439
+ }
440
+ }
441
+
442
+
443
+ /** Helper methods ******************************************************/
444
+
445
+
446
+ /**
447
+ * Main Braintree Instance, ensures only one instance is/can be loaded
448
+ *
449
+ * @since 2.2.0
450
+ * @see wc_braintree()
451
+ * @return WC_Braintree
452
+ */
453
+ public static function instance() {
454
+ if ( is_null( self::$instance ) ) {
455
+ self::$instance = new self();
456
+ }
457
+ return self::$instance;
458
+ }
459
+
460
+
461
+ /**
462
+ * Gets the frontend class instance.
463
+ *
464
+ * @since 2.0.0
465
+ * @return \WC_Braintree_Frontend
466
+ */
467
+ public function get_frontend_instance() {
468
+ return $this->frontend;
469
+ }
470
+
471
+
472
+ /**
473
+ * Returns the plugin name, localized
474
+ *
475
+ * @since 2.1
476
+ * @see SV_WC_Plugin::get_plugin_name()
477
+ * @return string the plugin name
478
+ */
479
+ public function get_plugin_name() {
480
+ return __( 'WooCommerce PayPal Powered by Braintree Gateway', 'woocommerce-gateway-paypal-powered-by-braintree' );
481
+ }
482
+
483
+
484
+ /**
485
+ * Returns __FILE__
486
+ *
487
+ * @since 2.1
488
+ * @see SV_WC_Plugin::get_file()
489
+ * @return string the full path and filename of the plugin file
490
+ */
491
+ protected function get_file() {
492
+ return WC_PAYPAL_BRAINTREE_FILE;
493
+ }
494
+
495
+
496
+ /**
497
+ * Gets the plugin documentation url
498
+ *
499
+ * @since 2.1
500
+ * @see SV_WC_Plugin::get_documentation_url()
501
+ * @return string documentation URL
502
+ */
503
+ public function get_documentation_url() {
504
+ return 'http://docs.woocommerce.com/document/woocommerce-gateway-paypal-powered-by-braintree/';
505
+ }
506
+
507
+
508
+ /**
509
+ * Gets the plugin support URL
510
+ *
511
+ * @since 2.3.0
512
+ * @see SV_WC_Plugin::get_support_url()
513
+ * @return string
514
+ */
515
+ public function get_support_url() {
516
+ return 'https://wordpress.org/support/plugin/woocommerce-gateway-paypal-powered-by-braintree/';
517
+ }
518
+
519
+
520
+ /**
521
+ * Returns the "Configure Credit Card" or "Configure PayPal" plugin action
522
+ * links that go directly to the gateway settings page
523
+ *
524
+ * @since 3.0.0
525
+ * @see SV_WC_Payment_Gateway_Plugin::get_settings_url()
526
+ * @param string $gateway_id the gateway identifier
527
+ * @return string plugin configure link
528
+ */
529
+ public function get_settings_link( $gateway_id = null ) {
530
+
531
+ return sprintf( '<a href="%s">%s</a>',
532
+ $this->get_settings_url( $gateway_id ),
533
+ self::CREDIT_CARD_GATEWAY_ID === $gateway_id ? __( 'Configure Credit Card', 'woocommerce-gateway-paypal-powered-by-braintree' ) : __( 'Configure PayPal', 'woocommerce-gateway-paypal-powered-by-braintree' )
534
+ );
535
+ }
536
+
537
+
538
+ /** Lifecycle methods ******************************************************/
539
+
540
+
541
+ /**
542
+ * Handles installing or upgrading the plugin.
543
+ *
544
+ * @since 2.0.0
545
+ */
546
+ public function do_install() {
547
+
548
+ $installed_version = get_option( $this->get_plugin_version_name() );
549
+
550
+ // if installing from the retired WooCommerce Braintree plugin (higher version number)
551
+ if ( version_compare( $installed_version, $this->get_version(), '>' ) ) {
552
+
553
+ $this->migrate_from_sv();
554
+
555
+ // if upgrading from 1.x, which won't have a version number set
556
+ } elseif ( ! $installed_version && ( get_option( 'woocommerce_paypalbraintree_cards_settings' ) || get_option( 'wc_paypal_braintree_merchant_access_token' ) ) ) {
557
+
558
+ // set the version number
559
+ update_option( $this->get_plugin_version_name(), '1.2.7' );
560
+ }
561
+
562
+ parent::do_install();
563
+ }
564
+
565
+
566
+ /**
567
+ * Perform any version-related changes.
568
+ *
569
+ * @since 2.0
570
+ * @param int $installed_version the currently installed version of the plugin
571
+ */
572
+ protected function upgrade( $installed_version ) {
573
+
574
+ // upgrade to 2.0.0
575
+ if ( version_compare( $installed_version, '2.0.0', '<' ) ) {
576
+
577
+ global $wpdb;
578
+
579
+ $this->log( 'Starting upgrade to 2.0.0' );
580
+
581
+ $environment = ( 'sandbox' === get_option( 'wc_paypal_braintree_environment' ) ) ? WC_Gateway_Braintree::ENVIRONMENT_SANDBOX : WC_Gateway_Braintree::ENVIRONMENT_PRODUCTION;
582
+ $merchant_id = get_option( 'wc_paypal_braintree_merchant_id', '' );
583
+
584
+ // Begin settings upgrade
585
+ $this->log( 'Upgrading settings' );
586
+
587
+ // we need to parse args here because it's possible that the legacy
588
+ // gateway was connected & processing payments but the settings were
589
+ // never saved.
590
+ $legacy_settings = wp_parse_args( get_option( 'woocommerce_paypalbraintree_cards_settings', array() ), array(
591
+ 'enabled' => ( get_option( 'wc_paypal_braintree_merchant_access_token' ) ) ? 'yes' : 'no',
592
+ 'capture' => 'yes',
593
+ 'debug' => 'no',
594
+ 'title_cards' => 'Credit Card',
595
+ 'description_cards' => 'Pay securely using your credit card.',
596
+ 'title_paypal' => 'PayPal',
597
+ 'description_paypal' => 'Click the PayPal icon below to sign into your PayPal account and pay securely.',
598
+ ) );
599
+
600
+ $common_settings = array(
601
+ 'enabled' => $legacy_settings['enabled'],
602
+ 'transaction_type' => ( 'yes' === $legacy_settings['capture'] ) ? WC_Gateway_Braintree::TRANSACTION_TYPE_CHARGE : WC_Gateway_Braintree::TRANSACTION_TYPE_AUTHORIZATION,
603
+ 'tokenization' => 'yes',
604
+ 'environment' => $environment,
605
+ 'debug_mode' => ( 'yes' === $legacy_settings['debug'] ) ? WC_Gateway_Braintree::DEBUG_MODE_LOG : WC_Gateway_Braintree::DEBUG_MODE_OFF,
606
+ 'connect_manually' => 'no',
607
+ 'inherit_settings' => 'no',
608
+ );
609
+
610
+ if ( $environment === WC_Gateway_Braintree::ENVIRONMENT_PRODUCTION ) {
611
+ $common_settings['merchant_id'] = $merchant_id;
612
+ } else {
613
+ $common_settings[ $environment . '_merchant_id'] = $merchant_id;
614
+ }
615
+
616
+ $credit_card_settings = array(
617
+ 'title' => $legacy_settings['title_cards'],
618
+ 'description' => $legacy_settings['description_cards'],
619
+ 'card_types' => array( 'VISA', 'MC', 'AMEX', 'DISC', 'DINERS', 'JCB', ),
620
+ );
621
+
622
+ update_option( 'woocommerce_braintree_credit_card_settings', array_merge( $common_settings, $credit_card_settings ) );
623
+
624
+ $paypal_settings = array(
625
+ 'title' => $legacy_settings['title_paypal'],
626
+ 'description' => $legacy_settings['description_paypal'],
627
+ );
628
+
629
+ update_option( 'woocommerce_braintree_paypal_settings', array_merge( $common_settings, $paypal_settings ) );
630
+
631
+ // the Braintree Auth options
632
+ $wpdb->update( $wpdb->options, array( 'option_name' => 'wc_braintree_auth_access_token' ), array( 'option_name' => 'wc_paypal_braintree_merchant_access_token' ) );
633
+ $wpdb->update( $wpdb->options, array( 'option_name' => 'wc_braintree_auth_environment' ), array( 'option_name' => 'wc_paypal_braintree_environment' ) );
634
+ $wpdb->update( $wpdb->options, array( 'option_name' => 'wc_braintree_auth_merchant_id' ), array( 'option_name' => 'wc_paypal_braintree_merchant_id' ) );
635
+
636
+ $this->log( 'Settings upgraded' );
637
+
638
+ /** Update order/subscription meta data ***************************/
639
+
640
+ $order_meta = array(
641
+ '_wc_paypal_braintree_customer_id' => 'customer_id',
642
+ '_wc_paypal_braintree_payment_method_token' => 'payment_token',
643
+ '_pp_braintree_charge_captured' => 'charge_captured',
644
+ );
645
+
646
+ $count = 0;
647
+
648
+ foreach ( $order_meta as $legacy_key => $new_suffix ) {
649
+
650
+ // update for the credit card gateway
651
+ $rows = $wpdb->query(
652
+ $wpdb->prepare(
653
+ "
654
+ UPDATE {$wpdb->postmeta} meta1, {$wpdb->postmeta} meta2
655
+ SET meta1.meta_key = %s
656
+ WHERE meta1.meta_key = %s
657
+ AND meta2.meta_key = '_payment_method'
658
+ AND meta2.meta_value = 'paypalbraintree_cards'
659
+ AND meta1.post_id = meta2.post_id
660
+ ",
661
+ [
662
+ '_wc_braintree_credit_card_' . $new_suffix,
663
+ $legacy_key,
664
+ ]
665
+ )
666
+ );
667
+
668
+ $count += $rows;
669
+
670
+ // update for the paypal gateway
671
+ $rows = $wpdb->query(
672
+ $wpdb->prepare(
673
+ "
674
+ UPDATE {$wpdb->postmeta} meta1, {$wpdb->postmeta} meta2
675
+ SET meta1.meta_key = %s
676
+ WHERE meta1.meta_key = %s
677
+ AND meta2.meta_key = '_payment_method'
678
+ AND meta2.meta_value = 'paypalbraintree_paypal'
679
+ AND meta1.post_id = meta2.post_id
680
+ ",
681
+ [
682
+ '_wc_braintree_paypal_' . $new_suffix,
683
+ $legacy_key,
684
+ ]
685
+ )
686
+ );
687
+
688
+ $count += $rows;
689
+ }
690
+
691
+ if ( $rows = $wpdb->update( $wpdb->postmeta, array( 'meta_value' => 'braintree_credit_card' ), array( 'meta_key' => '_payment_method', 'meta_value' => 'paypalbraintree_cards' ) ) ) {
692
+ $count += $rows;
693
+ }
694
+ if ( $rows = $wpdb->update( $wpdb->postmeta, array( 'meta_value' => 'braintree_paypal' ), array( 'meta_key' => '_payment_method', 'meta_value' => 'paypalbraintree_paypal' ) ) ) {
695
+ $count += $rows;
696
+ }
697
+
698
+ if ( $count ) {
699
+ $this->log( sprintf( '%d rows of order meta data updated.', $count ) );
700
+ }
701
+
702
+ /** Update user meta data *****************************************/
703
+
704
+ $customer_id_meta_key = 'wc_braintree_customer_id';
705
+
706
+ if ( $environment !== WC_Gateway_Braintree::ENVIRONMENT_PRODUCTION ) {
707
+ $customer_id_meta_key .= '_' . $environment;
708
+ }
709
+
710
+ // Customer IDs
711
+ // old key: _wc_paypal_braintree_customer_id
712
+ // new key: wc_braintree_customer_id
713
+ if ( $rows = $wpdb->update( $wpdb->usermeta, array( 'meta_key' => $customer_id_meta_key ), array( 'meta_key' => '_wc_paypal_braintree_customer_id' ) ) ) {
714
+ $this->log( sprintf( '%d user customer IDs updated.', $rows ) );
715
+ }
716
+
717
+ wp_cache_flush();
718
+
719
+ $this->log( 'Completed upgrade for 2.0.0' );
720
+ }
721
+ }
722
+
723
+
724
+ /**
725
+ * Migrate the necessary settings from the retired plugin.
726
+ *
727
+ * @since 2.0.0
728
+ */
729
+ protected function migrate_from_sv() {
730
+
731
+ $this->log( 'Starting migration to ' . $this->get_plugin_name() );
732
+
733
+ // set the version number
734
+ update_option( $this->get_plugin_version_name(), $this->get_version() );
735
+
736
+ foreach ( $this->get_gateway_ids() as $gateway_id ) {
737
+
738
+ $settings = $this->get_gateway_settings( $gateway_id );
739
+
740
+ // if the API credentials have been previously configured
741
+ if ( 'yes' === $settings['inherit_settings'] || ( ! empty( $settings['public_key'] ) && ! empty( $settings['private_key'] ) && ! empty( $settings['merchant_id'] ) ) || ( ! empty( $settings['sandbox_public_key'] ) && ! empty( $settings['sandbox_private_key'] ) && ! empty( $settings['sandbox_merchant_id'] ) ) ) {
742
+
743
+ $settings['connect_manually'] = 'yes';
744
+
745
+ update_option( $this->get_gateway_settings_name( $gateway_id ), $settings );
746
+ }
747
+ }
748
+
749
+ update_option( 'wc_braintree_legacy_migrated', 'yes' );
750
+
751
+ $this->log( 'Completed migration to ' . $this->get_plugin_name() );
752
+ }
753
+
754
+
755
+ /**
756
+ * Determines if WooCommerce is active.
757
+ *
758
+ * @since 2.0.0
759
+ * @return bool
760
+ */
761
+ public static function is_woocommerce_active() {
762
+
763
+ $active_plugins = (array) get_option( 'active_plugins', array() );
764
+
765
+ if ( is_multisite() ) {
766
+ $active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
767
+ }
768
+
769
+ return in_array( 'woocommerce/woocommerce.php', $active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', $active_plugins );
770
+ }
771
+
772
+
773
+ } // end \WC_Braintree
774
+
775
+
776
+ /**
777
+ * Returns the One True Instance of Braintree
778
+ *
779
+ * @since 2.2.0
780
+ * @return WC_Braintree
781
+ */
782
+ function wc_braintree() {
783
+
784
+ return WC_Braintree::instance();
785
+ }
786
+
787
+
788
+ // fire it up!
789
+ wc_braintree();
classes/class-wc-gateway-paypal-braintree-pay-with-card-subscription.php DELETED
@@ -1,23 +0,0 @@
1
- <?php
2
- /**
3
- * WC_Gateway_Paypal_Braintree_Pay_With_Card_Subscription class.
4
- *
5
- * @extends WC_Gateway_Paypal_Braintree_Subscription
6
- */
7
-
8
- class WC_Gateway_Paypal_Braintree_Pay_With_Card_Subscription extends WC_Gateway_Paypal_Braintree_Subscription {
9
-
10
- public function __construct() {
11
-
12
- $this->id = 'paypalbraintree_cards';
13
-
14
- parent::__construct();
15
-
16
- $this->icon = plugins_url( '../assets/images/payments/payment-method-cards.png', __FILE__ );
17
- $this->checkout_template = 'checkout/paypal-braintree-pay-with-card.php';
18
- $this->title = $this->get_option( 'title_cards' );
19
- $this->description = $this->get_option( 'description_cards' );
20
-
21
- }
22
-
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/class-wc-gateway-paypal-braintree-pay-with-card.php DELETED
@@ -1,30 +0,0 @@
1
- <?php
2
- /**
3
- * WC_Gateway_Paypal_Braintree_Pay_With_Card class.
4
- *
5
- * @extends WC_Gateway_Paypal_Braintree
6
- */
7
-
8
- class WC_Gateway_Paypal_Braintree_Pay_With_Card extends WC_Gateway_Paypal_Braintree {
9
-
10
- /**
11
- * WC_Gateway_Paypal_Braintree_Pay_With_Card constructor.
12
- */
13
- public function __construct() {
14
-
15
- $this->id = 'paypalbraintree_cards';
16
-
17
- parent::__construct();
18
-
19
- /**
20
- * Filter the accepted credit card icons for Paypal Powered by Braintree.
21
- *
22
- * @param string $card_icons_url disployed on the checkout page.
23
- */
24
- $this->icon = apply_filters( 'wc_gateway_paypal_braintree_card_icons_image_url', plugins_url( '../assets/images/payments/payment-method-cards.png', __FILE__ ) );
25
- $this->checkout_template = 'checkout/paypal-braintree-pay-with-card.php';
26
- $this->title = $this->get_option( 'title_cards' );
27
- $this->description = $this->get_option( 'description_cards' );
28
-
29
- }
30
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/class-wc-gateway-paypal-braintree-pay-with-paypal-subscription.php DELETED
@@ -1,23 +0,0 @@
1
- <?php
2
- /**
3
- * WC_Gateway_Paypal_Braintree_Pay_With_PayPal class.
4
- *
5
- * @extends WC_Gateway_Paypal_Braintree_Subscription
6
- */
7
-
8
- class WC_Gateway_Paypal_Braintree_Pay_With_PayPal_Subscription extends WC_Gateway_Paypal_Braintree_Subscription {
9
-
10
- public function __construct() {
11
-
12
- $this->id = 'paypalbraintree_paypal';
13
-
14
- parent::__construct();
15
-
16
- $this->icon = plugins_url( '../assets/images/payments/PP_logo_h_100x26.png', __FILE__ );
17
- $this->checkout_template = 'checkout/paypal-braintree-pay-with-paypal.php';
18
- $this->title = $this->get_option( 'title_paypal' );
19
- $this->description = $this->get_option( 'description_paypal' );
20
-
21
- }
22
-
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/class-wc-gateway-paypal-braintree-pay-with-paypal.php DELETED
@@ -1,23 +0,0 @@
1
- <?php
2
- /**
3
- * WC_Gateway_Paypal_Braintree_Pay_With_PayPal class.
4
- *
5
- * @extends WC_Gateway_Paypal_Braintree
6
- */
7
-
8
- class WC_Gateway_Paypal_Braintree_Pay_With_PayPal extends WC_Gateway_Paypal_Braintree {
9
-
10
- public function __construct() {
11
-
12
- $this->id = 'paypalbraintree_paypal';
13
-
14
- parent::__construct();
15
-
16
- $this->icon = plugins_url( '../assets/images/payments/PP_logo_h_100x26.png', __FILE__ );
17
- $this->checkout_template = 'checkout/paypal-braintree-pay-with-paypal.php';
18
- $this->title = $this->get_option( 'title_paypal' );
19
- $this->description = $this->get_option( 'description_paypal' );
20
-
21
- }
22
-
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/class-wc-gateway-paypal-braintree-subscription.php DELETED
@@ -1,366 +0,0 @@
1
- <?php
2
- /**
3
- * WC_Gateway_Paypal_Braintree_Subscription class.
4
- *
5
- * @extends WC_Gateway_Paypal_Braintree
6
- */
7
- abstract class WC_Gateway_Paypal_Braintree_Subscription extends WC_Gateway_Paypal_Braintree {
8
-
9
- /**
10
- * Constructor
11
- */
12
- public function __construct() {
13
- parent::__construct();
14
-
15
- // Add subscription support
16
- $this->supports = array_merge( $this->supports, array(
17
- 'subscriptions',
18
- 'subscription_cancellation',
19
- 'subscription_suspension',
20
- 'subscription_reactivation',
21
- 'subscription_amount_changes',
22
- 'subscription_date_changes',
23
- 'multiple_subscriptions',
24
- 'subscription_payment_method_change_admin'
25
- // NOTE: PayPal Braintree does NOT support $0 transactions so we
26
- // must NOT enable subscription_payment_method_change_customer
27
- // because Subscriptions requires that the gateway allow zero amount
28
- // transactions for that to work
29
- )
30
- );
31
-
32
- // process renewals
33
- add_action( 'woocommerce_scheduled_subscription_payment_' . $this->id, array( $this, 'scheduled_subscription_payment' ), 10, 2 );
34
-
35
- // filter javascript options
36
- add_filter( 'wc_gateway_paypal_braintree_data', array( $this, 'filter_paypal_braintree_data' ), 10 );
37
- }
38
-
39
- /**
40
- * Check if order contains subscriptions, is renewal order, or subscription.
41
- *
42
- * @param int $order_id
43
- * @return bool
44
- */
45
- protected function order_contains_subscription( $order_id ) {
46
- if ( ! function_exists( 'wcs_order_contains_subscription' ) ) {
47
- return false;
48
- }
49
-
50
- return (
51
- wcs_order_contains_subscription( $order_id )
52
- || wcs_order_contains_renewal( $order_id )
53
- || wcs_is_subscription( $order_id )
54
- );
55
- }
56
-
57
- /**
58
- * process_payment
59
- *
60
- * Completes the initial payment on the subscription order
61
- *
62
- * Although PayPal Braintree supports subscription products (they call them plans),
63
- * they don't support the wide variety of intervals we do, nor multiple subscription
64
- * products in a single order.
65
- *
66
- * So, this extension does all the subscription work itself, storing a customer
67
- * in the vault on the first payment, and using those stored credentials for
68
- * renewal orders
69
- *
70
- * @param int $order_id
71
- * @return mixed
72
- */
73
- public function process_payment( $order_id ) {
74
-
75
- // If the order contains no subscriptions, just let the parent process it
76
- if ( ! $this->order_contains_subscription( $order_id ) ) {
77
- return parent::process_payment( $order_id );
78
- }
79
-
80
- $order = new WC_Order( $order_id );
81
- $this->log( __FUNCTION__, "Info: Beginning processing of payment for (subscription) order $order_id for the amount of {$order->order_total}" );
82
- $this->log( __FUNCTION__, "Info: Merchant ID = {$this->merchant_id}" );
83
-
84
- $paypal_braintree_nonce = self::get_posted_variable( 'paypalbraintree_nonce' );
85
- if ( empty( $paypal_braintree_nonce ) ) {
86
- $this->log( __FUNCTION__, 'Error: The paypal_braintree_nonce was unexpectedly empty' );
87
- wc_add_notice( __( 'Error: PayPal Powered by Braintree did not supply a payment nonce. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
88
- return false;
89
- }
90
-
91
- $user_id = $order->get_user_id();
92
- if ( ! is_user_logged_in() ) {
93
- $this->log( __FUNCTION__, 'Error: No user logged in / being created for the initial subscription payment' );
94
- wc_add_notice( __( 'Error: You must login or create an account before you can purchase a subscription.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
95
- return false;
96
- }
97
-
98
- // Create the gateway instance up front
99
- require_once( dirname( __FILE__ ) . '/../braintree_sdk/lib/Braintree.php' );
100
- $gateway = new Braintree_Gateway( array(
101
- 'accessToken' => $this->merchant_access_token,
102
- ) );
103
-
104
- // Check their user meta for a stored braintree customer id
105
- $braintree_customer_id = get_user_meta( $user_id, '_wc_paypal_braintree_customer_id', true );
106
- if ( empty( $braintree_customer_id ) ) {
107
-
108
- $this->log( __FUNCTION__, 'Info: Did not find braintree customer id on user meta. Need to create customer' );
109
-
110
- // Create a new customer id, passing the nonce so we can add the card to the vault
111
- // ref https://developers.braintreepayments.com/reference/request/customer/create/php
112
- $customer_args = array(
113
- 'firstName' => $order->billing_first_name,
114
- 'lastName' => $order->billing_last_name,
115
- 'company' => $order->billing_company,
116
- 'phone' => $order->billing_phone,
117
- 'email' => $order->billing_email,
118
- 'paymentMethodNonce' => $paypal_braintree_nonce,
119
- );
120
-
121
- try {
122
- $result = $gateway->customer()->create( $customer_args );
123
- } catch ( Exception $e ) {
124
- $this->log( __FUNCTION__, 'Error: Unable to create customer. Reason: ' . $e->getMessage() );
125
- wc_add_notice( __( 'Error: PayPal Powered by Braintree was unable to create a customer record for you. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
126
- return false;
127
- }
128
-
129
- if ( ! $result->success ) {
130
- $this->log( __FUNCTION__, "Error: Unable to create customer: {$result->message}" );
131
- wc_add_notice( __( 'Error: PayPal Powered by Braintree was unable to create a customer record for you. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
132
- return false;
133
- }
134
-
135
- $braintree_customer_id = $result->customer->id;
136
- update_user_meta( $user_id, '_wc_paypal_braintree_customer_id', $braintree_customer_id );
137
- $this->log( __FUNCTION__, "Info: Created customer successfully - braintree customer id = $braintree_customer_id" );
138
-
139
- $payment_methods = $result->customer->paymentMethods;
140
- $payment_method_token = '';
141
- foreach ( (array) $payment_methods as $payment_method ) {
142
- if ( $payment_method->default ) {
143
- $payment_method_token = $payment_method->token;
144
- }
145
- }
146
-
147
- $authentication = array(
148
- 'paymentMethodToken' => $payment_method_token, // can only use the nonce once :)
149
- );
150
-
151
- } else {
152
-
153
- // We found the braintree customer id in the customer's meta
154
- $this->log( __FUNCTION__, "Info: Found a braintree customer id in the users meta - customer id = $braintree_customer_id" );
155
- $authentication = array(
156
- 'paymentMethodNonce' => $paypal_braintree_nonce,
157
- );
158
-
159
- }
160
-
161
- $sale_args = $this->generate_sales_args( $order, $braintree_customer_id );
162
- $sale_args = array_merge( $sale_args, $authentication );
163
- $transaction_id = '';
164
-
165
- // Process trial periods and possible coupon discounts.
166
- if ( isset( $sale_args['amount'] ) && 0.00 === doubleval( $sale_args['amount'] ) ) {
167
-
168
- $user_id = $order->get_user_id();
169
- $this->log( __FUNCTION__, "Zero payment amount for trial or coupon. Order ID: $order_id, User ID: $user_id" );
170
- $customer = $gateway->customer()->find( $braintree_customer_id );
171
-
172
- $payment_method_token = '';
173
- foreach ( (array) $customer->paymentMethods as $payment_method ) {
174
- if ( $payment_method->default ) {
175
- $payment_method_token = $payment_method->token;
176
- }
177
- }
178
-
179
- } else { // charges more than zero should be sent away
180
-
181
- // We have a customer id now, so let's do the sale and store the payment method in the vault.
182
- $result = $gateway->transaction()->sale( $sale_args );
183
- if ( ! $result->success ) {
184
- $notice = sprintf( __( 'Error: PayPal Powered by Braintree was unable to complete the transaction. Please try again later or use another means of payment. Reason: %s', 'woocommerce-gateway-paypal-braintree' ), $result->message );
185
- wc_add_notice( $notice, 'error' );
186
- $this->log( __FUNCTION__, "Error: Unable to complete transaction. Reason: {$result->message}" );
187
- return false;
188
- }
189
-
190
- $transaction_id = $result->transaction->id;
191
- $this->log( __FUNCTION__, "Info: Successfully processed initial payment, transaction id = $transaction_id" );
192
- $credit_card_meta = $result->transaction->creditCard;
193
- $payment_method_token = $credit_card_meta['token'];
194
-
195
- if ( empty( $payment_method_token ) ) {
196
- $this->log( __FUNCTION__, 'Info: Customer used the paypal subflow' );
197
- $paypal_meta = $result->transaction->paypal;
198
- $payment_method_token = $paypal_meta['token'];
199
- } else {
200
- $this->log( __FUNCTION__, 'Info: Customer used the credit card subflow' );
201
- }
202
-
203
- $braintree_customer_id = $result->transaction->customer['id'];
204
- }
205
-
206
-
207
- if ( empty( $payment_method_token ) ) {
208
- $this->log( __FUNCTION__, 'Warning: Initial payment succeeded, but no token was provided by the gateway for recurring payments.' );
209
- }
210
-
211
- // Save the customer ID in each subscription for this order for later use during renewal
212
- if ( empty( $braintree_customer_id ) ) {
213
- $this->log( __FUNCTION__, 'Warning: Initial payment succeeded, but no braintree customer ID was provided by the gateway for recurring payments.' );
214
- } else {
215
- $this->log( __FUNCTION__, "Info: Saving to subscription(s) recurring payment braintree customer ID $braintree_customer_id" );
216
- }
217
-
218
- // Note: A single order may contain multiple subscriptions
219
- // Save the token in each subscription for this order for later use during renewal
220
- foreach ( wcs_get_subscriptions_for_order( $order->id ) as $subscription ) {
221
- update_post_meta( $subscription->id, '_wc_paypal_braintree_payment_method_token', $payment_method_token );
222
- update_post_meta( $subscription->id, '_wc_paypal_braintree_customer_id', $braintree_customer_id );
223
- }
224
-
225
- $order->payment_complete( $transaction_id );
226
- $this->log( __FUNCTION__, "Info: Completed processing of payment for order $order_id" );
227
-
228
- return array(
229
- 'result' => 'success',
230
- 'redirect' => $this->get_return_url( $order ),
231
- );
232
- }
233
-
234
- /**
235
- * Create sales args.
236
- * @param $order
237
- * @param $braintree_customer_id
238
- *
239
- * @return array
240
- */
241
- public function generate_sales_args( $order, $braintree_customer_id ) {
242
- $billing = array(
243
- 'firstName' => $order->billing_first_name,
244
- 'lastName' => $order->billing_last_name,
245
- 'company' => $order->billing_company,
246
- 'streetAddress' => $order->billing_address_1,
247
- 'extendedAddress' => $order->billing_address_2,
248
- 'locality' => $order->billing_city,
249
- 'region' => $order->billing_state,
250
- 'postalCode' => $order->billing_postcode,
251
- 'countryCodeAlpha2' => $order->billing_country,
252
- );
253
-
254
- // Shipping data, assemble
255
- $shipping = array(
256
- 'firstName' => $order->shipping_first_name,
257
- 'lastName' => $order->shipping_last_name,
258
- 'company' => $order->shipping_company,
259
- 'streetAddress' => $order->shipping_address_1,
260
- 'extendedAddress' => $order->shipping_address_2,
261
- 'locality' => $order->shipping_city,
262
- 'region' => $order->shipping_state,
263
- 'postalCode' => $order->shipping_postcode,
264
- 'countryCodeAlpha2' => $order->shipping_country,
265
- );
266
-
267
- $sale_args = array(
268
- 'amount' => $order->order_total,
269
- 'billing' => $billing,
270
- 'shipping' => $shipping,
271
- 'customerId' => $braintree_customer_id,
272
- 'channel' => 'WooThemes_BT', // aka BN tracking code
273
- 'orderId' => $order->id,
274
- 'options' => array(
275
- 'submitForSettlement' => true,
276
- 'storeInVaultOnSuccess' => true,
277
- ),
278
- );
279
-
280
- return apply_filters( 'wc_gateway_paypal_braintree_sale_args', $sale_args );
281
- }
282
-
283
- /**
284
- * scheduled_subscription_payment
285
- *
286
- * Hooked to woocommerce_scheduled_subscription_payment_{gateway_id}
287
- * Completes recurring payments for a subscription
288
- */
289
- public function scheduled_subscription_payment( $amount_to_charge, $order ) {
290
-
291
- $this->log( __FUNCTION__, "Info: Beginning processing of scheduled payment for order {$order->id} for the amount of $amount_to_charge" );
292
- $this->log( __FUNCTION__, "Info: Merchant ID = {$this->merchant_id}" );
293
-
294
- // token is required
295
- $payment_method_token = get_post_meta( $order->id, '_wc_paypal_braintree_payment_method_token', true );
296
- if ( empty( $payment_method_token ) ) {
297
- $this->log( __FUNCTION__, "Error: Payment method token is missing on order meta" );
298
- WC_Subscriptions_Manager::process_subscription_payment_failure_on_order( $order );
299
- return;
300
- }
301
-
302
- // as is the customer id
303
- $braintree_customer_id = get_post_meta( $order->id, '_wc_paypal_braintree_customer_id', true );
304
- if ( empty( $braintree_customer_id ) ) {
305
- $this->log( __FUNCTION__, "Error: Braintree customer ID is missing on order meta" );
306
- WC_Subscriptions_Manager::process_subscription_payment_failure_on_order( $order );
307
- return;
308
- }
309
-
310
- // Create the gateway instance
311
- require_once( dirname( __FILE__ ) . '/../braintree_sdk/lib/Braintree.php' );
312
- $gateway = new Braintree_Gateway( array(
313
- 'accessToken' => $this->merchant_access_token,
314
- ) );
315
-
316
- // Process the sale with the stored token and customer
317
- $sale_args = apply_filters( 'wc_gateway_paypal_braintree_sale_args', array(
318
- 'amount' => $amount_to_charge,
319
- 'paymentMethodToken' => $payment_method_token,
320
- 'recurring' => true,
321
- 'customerId' => $braintree_customer_id,
322
- 'channel' => 'WooThemes_BT', // aka BN tracking code
323
- 'orderId' => $order->id,
324
- 'options' => array(
325
- 'submitForSettlement' => true,
326
- 'storeInVaultOnSuccess' => true,
327
- ),
328
- ) );
329
-
330
- try {
331
- $result = $gateway->transaction()->sale( $sale_args );
332
- } catch ( Exception $e ) {
333
- $this->log( __FUNCTION__, 'Error: Unable to process scheduled payment. Reason: ' . $e->getMessage() );
334
- return false;
335
- }
336
-
337
- if ( ! $result->success ) {
338
- $this->log( __FUNCTION__, "Error: Unable to process scheduled payment: {$result->message}" );
339
- return false;
340
- }
341
-
342
- $transaction_id = $result->transaction->id;
343
- $this->log( __FUNCTION__, "Info: Successfully processed schedule payment, transaction id = $transaction_id" );
344
-
345
- WC_Subscriptions_Manager::process_subscription_payments_on_order( $order );
346
- $this->log( __FUNCTION__, "Info: Completed processing of scheduled payment for order {$order->id}" );
347
- $order->add_order_note( sprintf( __( 'PayPal Braintree charge complete (Charge ID: %s)', 'woocommerce-gateway-paypal-braintree' ), $transaction_id ) );
348
- $order->payment_complete( $transaction_id );
349
- }
350
-
351
- /**
352
- * filter_paypal_braintree_data
353
- *
354
- * For subscriptions, set the singleUse flag to false so paypal-braintree knows we need a token
355
- * for recurring payments
356
- */
357
- public function filter_paypal_braintree_data( $paypal_braintree_data ) {
358
-
359
- if ( array_key_exists( 'checkoutWithPayPal' , $paypal_braintree_data ) ) {
360
- $paypal_braintree_data['checkoutWithPayPal']['singleUse'] = false;
361
- }
362
-
363
- return $paypal_braintree_data;
364
- }
365
-
366
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
classes/class-wc-gateway-paypal-braintree.php DELETED
@@ -1,1144 +0,0 @@
1
- <?php
2
- /**
3
- * PayPal Powered by Braintree Payment Gateway
4
- *
5
- * Provides a Payment Gateway for PayPal Powered by Braintree.
6
- *
7
- * @class WC_Gateway_Paypal_Braintree
8
- * @package WooCommerce
9
- * @category Payment Gateways
10
- * @author WooThemes
11
- */
12
-
13
- abstract class WC_Gateway_Paypal_Braintree extends WC_Payment_Gateway {
14
-
15
- /**
16
- * Version
17
- * @var string
18
- */
19
- public $version = '1.2.1';
20
-
21
- /**
22
- * Checkout template for payment fields
23
- */
24
- public $checkout_template = '';
25
-
26
- /**
27
- * Whether or not the gateway is enabled in wp-admin
28
- * This is initialized from the option, but can differ from $this->enabled
29
- * in the event the gateway is declared not-valid-for-use during construction.
30
- */
31
- protected $enabled_original_setting = '';
32
-
33
- /**
34
- * Whether or not debug is enabled in wp-admin
35
- */
36
- protected $debug = false;
37
-
38
- /**
39
- * Constructor
40
- */
41
- public function __construct() {
42
-
43
- $this->icon = false;
44
- $this->has_fields = true;
45
- $this->title = '';
46
- $this->description = '';
47
-
48
- $this->method_title = __( 'PayPal Powered by Braintree', 'woocommerce-gateway-paypal-braintree' );
49
- $this->method_description = sprintf(
50
- __( 'Works by accepting payment information in a secure form hosted by %sBraintree, a PayPal company%s.', 'woocommerce-gateway-paypal-braintree' ),
51
- '<a href="https://www.braintreepayments.com/">', '</a>'
52
- );
53
- $this->supports = array(
54
- 'products',
55
- 'refunds'
56
- );
57
-
58
- $this->capture = $this->get_option( 'capture', 'yes' ) === 'yes' ? true : false;
59
-
60
- $just_connected = $this->possibly_save_access_token();
61
- $just_disconnected = $this->possibly_discard_access_token();
62
-
63
- // After the merchant uses the Connect to Braintree button, they will
64
- // have an access token we can use. Note - this is stored in WP options
65
- $this->merchant_access_token = get_option( 'wc_paypal_braintree_merchant_access_token', '' );
66
- $this->merchant_id = get_option( 'wc_paypal_braintree_merchant_id', '' );
67
- $this->testmode = get_option( 'wc_paypal_braintree_environment', 'sandbox' ) === 'sandbox';
68
-
69
- $this->init_form_fields();
70
- $this->init_settings();
71
-
72
- $this->debug = $this->get_option( 'debug' ) === 'yes';
73
- $this->enabled_original_setting = $this->enabled;
74
-
75
- // Now that $this->debug is set, we can use logging
76
- if ( $just_connected ) {
77
- $this->log( __FUNCTION__, "Info: Connected to PayPal Braintree successfully. Merchant ID = {$this->merchant_id}" );
78
- }
79
-
80
- if ( $just_disconnected ) {
81
- $this->log( __FUNCTION__, "Info: Disconnected from PayPal Braintree." );
82
- }
83
-
84
- add_action( 'admin_notices', array( $this, 'admin_notices' ) );
85
-
86
- add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
87
- add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
88
-
89
- if ( ! $this->is_valid_for_use() ) {
90
- $this->enabled = 'no';
91
- return;
92
- }
93
-
94
- // Hooks related to the cart Checkout with PayPal flow
95
- add_action( 'woocommerce_api_' . strtolower( get_class( $this ) ), array( $this, 'handle_wc_api' ) );
96
- add_action( 'woocommerce_checkout_billing', array( $this, 'possibly_set_chosen_payment_method' ) );
97
- add_filter( 'woocommerce_checkout_get_value', array( $this, 'possibly_set_checkout_value' ), 10, 2 );
98
- add_filter( 'woocommerce_ship_to_different_address_checked', array( $this, 'possibly_set_ship_to_different_address' ) );
99
- }
100
-
101
- /**
102
- * If we see an access token, save it and add a notice. Returns true on successful connection
103
- *
104
- * @return bool
105
- * @since 1.0.0
106
- */
107
- public function possibly_save_access_token() {
108
-
109
- if ( ! is_admin() || ! is_user_logged_in() ) {
110
- return false;
111
- }
112
-
113
- // Require the access token
114
- if ( ! isset( $_GET['braintree_access_token'] ) ) {
115
- return false;
116
- }
117
-
118
- // Require the nonce
119
- if ( ! isset( $_GET['wc_paypal_braintree_admin_nonce'] ) ) {
120
- return false;
121
- }
122
-
123
- // Verify the nonce
124
- if ( ! wp_verify_nonce( $_GET['wc_paypal_braintree_admin_nonce'], 'connect_paypal_braintree') ) {
125
- wp_die( __( 'Invalid connection request', 'woocommerce-gateway-paypal-braintree' ) );
126
- }
127
-
128
- // Require the access token
129
- $access_token = isset( $_GET['braintree_access_token'] ) ? sanitize_text_field( urldecode( $_GET['braintree_access_token'] ) ) : '';
130
- if ( empty( $access_token ) ) {
131
- return false;
132
- }
133
-
134
- // If we already have a token, ignore this request
135
- $existing_access_token = get_option( 'wc_paypal_braintree_merchant_access_token' , '' );
136
- if ( ! empty( $existing_access_token ) ) {
137
- return false;
138
- }
139
-
140
- update_option( 'wc_paypal_braintree_merchant_access_token', $access_token );
141
-
142
- // Fetch the merchant ID and save it
143
- require_once( dirname( __FILE__ ) . '/../braintree_sdk/lib/Braintree.php' );
144
- $gateway = new Braintree_Gateway( array(
145
- 'accessToken' => $access_token,
146
- ) );
147
-
148
- $merchant_id = $gateway->config->getMerchantId();
149
- update_option( 'wc_paypal_braintree_merchant_id', $merchant_id );
150
-
151
- $environment = $gateway->config->getEnvironment(); // sandbox or production
152
- update_option( 'wc_paypal_braintree_environment', $environment );
153
-
154
- WC_PayPal_Braintree_Loader::getInstance()->add_admin_notice(
155
- 'connected_successfully',
156
- 'updated',
157
- __( 'Connected successfully.', 'woocommerce-gateway-paypal-braintree' )
158
- );
159
-
160
- return true;
161
- }
162
-
163
- /**
164
- * If the user asks, discard the access token and add a notice
165
- *
166
- * @return bool
167
- * @since 1.0.0
168
- */
169
- public function possibly_discard_access_token() {
170
- // Abundance of caution, should never happen
171
- if ( ! is_user_logged_in() ) {
172
- return false;
173
- }
174
-
175
- $disconnect_paypal_braintree = isset( $_GET['disconnect_paypal_braintree'] );
176
- if ( ! $disconnect_paypal_braintree ) {
177
- return false;
178
- }
179
-
180
- // Require the nonce
181
- if ( ! isset( $_GET['wc_paypal_braintree_admin_nonce'] ) ) {
182
- return false;
183
- }
184
-
185
- if ( ! wp_verify_nonce( $_GET['wc_paypal_braintree_admin_nonce'], 'disconnect_paypal_braintree') ) {
186
- wp_die( __( 'Invalid disconnection request', 'woocommerce-gateway-paypal-braintree' ) );
187
- }
188
-
189
- // If we don't have a token, ignore this request
190
- $existing_access_token = get_option( 'wc_paypal_braintree_merchant_access_token' , '' );
191
- if ( empty( $existing_access_token ) ) {
192
- return false;
193
- }
194
-
195
- delete_option( 'wc_paypal_braintree_merchant_access_token' );
196
- delete_option( 'wc_paypal_braintree_merchant_id' );
197
-
198
- WC_PayPal_Braintree_Loader::getInstance()->add_admin_notice(
199
- 'disconnected_successfully',
200
- 'updated',
201
- __( 'Disconnected successfully.', 'woocommerce-gateway-paypal-braintree' )
202
- );
203
-
204
- return true;
205
- }
206
-
207
-
208
- /**
209
- * Initialise Gateway Settings Form Fields common to all the gateways this extension supports
210
- * Child classes may add additional fields
211
- *
212
- * @since 1.0.0
213
- */
214
- public function init_form_fields () {
215
-
216
- $this->form_fields = WC_PayPal_Braintree_Loader::getInstance()->get_shared_form_fields();
217
-
218
- }
219
-
220
- public function admin_options() {
221
-
222
- $current_user = wp_get_current_user();
223
- $section_slug = strtolower( get_class( $this ) );
224
-
225
- $production_connect_url = 'https://connect.woocommerce.com/login/braintree';
226
- $sandbox_connect_url = 'https://connect.woocommerce.com/login/braintreesandbox';
227
-
228
- $redirect_url = add_query_arg(
229
- array(
230
- 'page' => 'wc-settings',
231
- 'tab' => 'checkout',
232
- 'section' => $section_slug
233
- ),
234
- admin_url( 'admin.php' )
235
- );
236
- $redirect_url = wp_nonce_url( $redirect_url, 'connect_paypal_braintree', 'wc_paypal_braintree_admin_nonce' );
237
-
238
- // Note: We doubly urlencode the redirect url to avoid Braintree's server
239
- // decoding it which would cause loss of query params on the final redirect
240
-
241
- // Note: Although the Partner API expects an array
242
- // ( per https://developers.braintreepayments.com/guides/partner-api/sign-up/php )
243
- // our middleware presently wants things flattened, so instead of passing a user
244
- // array and a business array, we pass selected fields with user_ and business_
245
- // prepended
246
-
247
- $query_args = array(
248
- 'redirect' => urlencode( urlencode( $redirect_url ) ),
249
- 'scopes' => 'read_write'
250
- );
251
-
252
- $current_user = wp_get_current_user();
253
-
254
- $query_args['user_email'] = $current_user->user_email;
255
-
256
- if ( ! empty( $current_user->user_firstname ) ) {
257
- $query_args[ 'user_firstName' ] = $current_user->user_firstname;
258
- }
259
-
260
- if ( ! empty( $current_user->user_lastname ) ) {
261
- $query_args[ 'user_lastName' ] = $current_user->user_lastname;
262
- }
263
-
264
- $query_args[ 'business_currency' ] = get_woocommerce_currency();
265
-
266
- // Let's go ahead and assume the user and business are in the same region and country,
267
- // because they probably are. If not, they can edit these anyways
268
- $base_location = wc_get_base_location();
269
- if ( array_key_exists( 'country', $base_location ) ) {
270
- $country = $base_location[ 'country' ];
271
- if ( ! empty( $country ) ) {
272
- $query_args[ 'business_country' ] = $country;
273
- $query_args[ 'user_country' ] = $country;
274
- }
275
- }
276
- if ( array_key_exists( 'state', $base_location ) ) {
277
- $state = $base_location[ 'state' ];
278
- if ( ! empty( $state ) ) {
279
- $query_args[ 'business_region' ] = $state;
280
- $query_args[ 'user_region' ] = $state;
281
- }
282
- }
283
-
284
- $site_name = get_bloginfo( 'name' );
285
- if ( ! empty( $site_name ) ) {
286
- $query_args[ 'business_name' ] = $site_name;
287
- }
288
-
289
- $site_description = get_bloginfo( 'description' );
290
- if ( ! empty( $site_description ) ) {
291
- $query_args[ 'business_description' ] = $site_description;
292
- }
293
-
294
- $query_args[ 'business_website' ] = get_bloginfo( 'url' );
295
-
296
- $production_connect_url = add_query_arg( $query_args, $production_connect_url );
297
- $sandbox_connect_url = add_query_arg( $query_args, $sandbox_connect_url );
298
-
299
- $disconnect_url = add_query_arg(
300
- array(
301
- 'page' => 'wc-settings',
302
- 'tab' => 'checkout',
303
- 'section' => $section_slug,
304
- 'disconnect_paypal_braintree' => 1
305
- ),
306
- admin_url( 'admin.php' )
307
- );
308
- $disconnect_url = wp_nonce_url( $disconnect_url, 'disconnect_paypal_braintree', 'wc_paypal_braintree_admin_nonce' );
309
-
310
- ?>
311
- <div class='paypal-braintree-admin-header'>
312
- <div class='paypal-braintree-admin-brand'>
313
- <img src="<?php echo plugins_url( '../assets/images/branding/paypal-braintree-horizontal.png', __FILE__ ); ?>" />
314
- </div>
315
- <div class='paypal-braintree-admin-payment-methods'>
316
- <img src="<?php echo plugins_url( '../assets/images/payments/visa.png', __FILE__ ); ?>" />
317
- <img src="<?php echo plugins_url( '../assets/images/payments/master-card.png', __FILE__ ); ?>" />
318
- <img src="<?php echo plugins_url( '../assets/images/payments/discover.png', __FILE__ ); ?>" />
319
- <img src="<?php echo plugins_url( '../assets/images/payments/american-express.png', __FILE__ ); ?>" />
320
- <img src="<?php echo plugins_url( '../assets/images/payments/paypal.png', __FILE__ ); ?>" />
321
- </div>
322
- </div>
323
- <?php if ( empty( $this->merchant_access_token ) ) { ?>
324
- <p class='paypal-braintree-admin-connect-prompt'>
325
- <?php echo esc_html( 'Connect with Braintree to start accepting credit and debit card payments in your checkout.', 'woocommerce-gateway-paypal-braintree' ); ?>
326
- <br/>
327
- <a href="https://www.braintreepayments.com/partners/learn-more" target="_blank">
328
- <?php echo esc_html( 'Learn more', 'woocommerce-gateway-paypal-braintree' ); ?>
329
- </a>
330
- </p>
331
- <?php } ?>
332
-
333
- <table class="form-table">
334
- <tbody>
335
- <tr>
336
- <th>
337
- <?php _e( 'Connect/Disconnect', 'woocommerce-gateway-paypal-braintree' ); ?>
338
- <?php
339
- $connect_help_tip = __( 'Click button to create an account with Braintree and start transacting.', 'woocommerce-gateway-paypal-braintree' );
340
- if ( ! empty( $this->merchant_access_token ) ) {
341
- $connect_help_tip = sprintf(
342
- '%s<br><br>%s<br><br>%s',
343
- __( 'You just connected your Braintree account to WooCommerce. You can start taking payments now.', 'woocommerce-gateway-paypal-braintree' ),
344
- __( 'Once you have processed a payment, PayPal will review your application for final approval. Before you ship any goods make sure you have received a final approval for your Braintree account.', 'woocommerce-gateway-paypal-braintree' ),
345
- __( 'Questions? We are a phone call away: 1-855-489-0345.', 'woocommerce-gateway-paypal-braintree' )
346
- );
347
- }
348
- echo wc_help_tip( $connect_help_tip );
349
- ?>
350
- </th>
351
- <td>
352
- <?php if ( ! empty( $this->merchant_access_token ) ) { ?>
353
- <a href="<?php echo esc_attr( $disconnect_url ); ?>" class='button-primary'>
354
- <?php echo esc_html__( 'Disconnect from PayPal Powered by Braintree', 'woocommerce-gateway-paypal-braintree' ); ?>
355
- </a>
356
- <?php } else { ?>
357
- <a href="<?php echo esc_attr( $production_connect_url ); ?>">
358
- <img src="<?php echo plugins_url( '../assets/images/button/connect-braintree.png', __FILE__ ); ?>"/>
359
- </a>
360
- <br/>
361
- <br/>
362
- <a href="<?php echo esc_attr( $sandbox_connect_url ); ?>">
363
- <?php echo esc_html__( 'Not ready to accept live payments? Click here to connect using sandbox mode.', 'woocommerce-gateway-paypal-braintree' ); ?>
364
- </a>
365
- <?php } ?>
366
- </td>
367
- </tr>
368
- </tbody>
369
- </table>
370
-
371
- <table class="form-table">
372
- <?php $this->generate_settings_html(); ?>
373
- </table>
374
- <?php
375
- }
376
-
377
-
378
- /**
379
- * Save the admin options, ask the loader to clone to siblings
380
- */
381
- public function process_admin_options() {
382
- if ( parent::process_admin_options() ) {
383
- WC_PayPal_Braintree_Loader::getInstance()->clone_fields_from_id( $this->id );
384
- }
385
- }
386
-
387
-
388
- /**
389
- * Check for required settings, and if SSL is enabled. We use a slug keyed array to avoid
390
- * duplicate notices from the paypal and card concrete classes
391
- */
392
- public function admin_notices() {
393
-
394
- // If the gateway is supposed to be enabled, check for required settings
395
- if ( 'yes' === $this->enabled_original_setting ) {
396
-
397
- $general_settings_url = add_query_arg( 'page', 'wc-settings', admin_url( 'admin.php' ) );
398
- $checkout_settings_url = add_query_arg( 'tab', 'checkout', $general_settings_url );
399
- $gateway_settings_url = add_query_arg( 'section', strtolower( get_class( $this ) ), $checkout_settings_url );
400
-
401
- // Check Currency
402
- if ( ! $this->is_shop_currency_supported() ) {
403
- WC_PayPal_Braintree_Loader::getInstance()->add_admin_notice(
404
- 'shop_currency_not_supported',
405
- 'error',
406
- sprintf( __( 'PayPal Powered by Braintree error: Your shop\'s currency is not supported. Please check <a href="%s">here</a>.', 'woocommerce-gateway-paypal-braintree' ), $general_settings_url )
407
- );
408
- }
409
-
410
- // Show message if enabled and FORCE SSL is disabled and WordpressHTTPS plugin is not detected
411
- if ( get_option( 'woocommerce_force_ssl_checkout' ) == 'no' && ! class_exists( 'WordPressHTTPS' ) ) {
412
- WC_PayPal_Braintree_Loader::getInstance()->add_admin_notice(
413
- 'ssl_lacking',
414
- 'error',
415
- sprintf( __( 'PayPal Powered by Braintree is enabled, but the <a href="%s">force SSL option</a> is disabled; your checkout may not be secure! Please enable SSL and ensure your server has a valid SSL certificate - PayPal Powered by Braintree will only work in test mode.', 'woocommerce-gateway-paypal-braintree' ), $checkout_settings_url )
416
- );
417
- }
418
-
419
- }
420
-
421
- }
422
-
423
-
424
- /**
425
- * handle_wc_api
426
- *
427
- * Exposes an endpoint that the cart.js javascript can use to post back checkout details provided by
428
- * PayPal during the cart based Checkout with PayPal flow
429
- *
430
- * @since 1.0.0
431
- */
432
- public function handle_wc_api() {
433
-
434
- $action = isset( $_GET['action'] ) ? sanitize_text_field( $_GET['action'] ) : '';
435
- if ( empty( $action ) ) {
436
- return;
437
- }
438
-
439
- if ( 'checkout_details' !== $action ) {
440
- return;
441
- }
442
-
443
- // Save the $_POST data to the session for later retrieval
444
- $sanitized_data = self::sanitize_post_back();
445
- WC()->session->set( 'paypal_braintree_postback', $sanitized_data );
446
- WC()->session->set( 'chosen_payment_method', get_class( $this ) );
447
-
448
- // return a URL for the client to navigate to
449
- wp_send_json( array(
450
- "success" => true,
451
- "redirectTo" => WC()->cart->get_checkout_url()
452
- )
453
- );
454
- }
455
-
456
-
457
- /**
458
- * When cart based Checkout with PayPal is in effect, this method will be called by the WC API
459
- * to sanitize and repackage PayPal fields into WC fields for later use in pre-populating the
460
- * checkout form
461
- *
462
- * @since 1.0.0
463
- * @return bool
464
- */
465
- protected function sanitize_post_back() {
466
-
467
- $paypalbraintree_nonce = sanitize_text_field( self::get_posted_variable( 'nonce', '' ) );
468
-
469
- $details = self::sanitize_array( self::get_posted_variable( 'details', array() ) );
470
- $billing_first_name = array_key_exists( 'firstName', $details ) ? $details['firstName'] : '';
471
- $billing_last_name = array_key_exists( 'lastName', $details ) ? $details['lastName'] : '';
472
- $billing_phone = array_key_exists( 'phone', $details ) ? $details['phone'] : '';
473
- $billing_email = array_key_exists( 'email', $details ) ? $details['email'] : '';
474
-
475
- $billingAddress = array_key_exists( 'billingAddress', $details ) ? $details['billingAddress'] : array();
476
- if ( ! is_array( $billingAddress ) ) {
477
- $billingAddress = array();
478
- }
479
- $billing_address_1 = array_key_exists( 'streetAddress', $billingAddress ) ? $billingAddress['streetAddress'] : '';
480
- $billing_address_2 = array_key_exists( 'extendedAddress', $billingAddress ) ? $billingAddress['extendedAddress'] : '';
481
- $billing_city = array_key_exists( 'locality', $billingAddress ) ? $billingAddress['locality'] : '';
482
- $billing_state = array_key_exists( 'region', $billingAddress ) ? $billingAddress['region'] : '';
483
- $billing_postcode = array_key_exists( 'postalCode', $billingAddress ) ? $billingAddress['postalCode'] : '';
484
- $billing_country = array_key_exists( 'countryCodeAlpha2', $billingAddress ) ? $billingAddress['countryCodeAlpha2'] : '';
485
-
486
- $shippingAddress = array_key_exists( 'shippingAddress', $details ) ? $details['shippingAddress'] : array();
487
- if ( ! is_array( $shippingAddress ) ) {
488
- $shippingAddress = array();
489
- }
490
- $shipping_address_1 = array_key_exists( 'streetAddress', $shippingAddress ) ? $shippingAddress['streetAddress'] : '';
491
- $shipping_address_2 = array_key_exists( 'extendedAddress', $shippingAddress ) ? $shippingAddress['extendedAddress'] : '';
492
- $shipping_city = array_key_exists( 'locality', $shippingAddress ) ? $shippingAddress['locality'] : '';
493
- $shipping_state = array_key_exists( 'region', $shippingAddress ) ? $shippingAddress['region'] : '';
494
- $shipping_postcode = array_key_exists( 'postalCode', $shippingAddress ) ? $shippingAddress['postalCode'] : '';
495
- $shipping_country = array_key_exists( 'countryCodeAlpha2', $shippingAddress ) ? $shippingAddress['countryCodeAlpha2'] : '';
496
-
497
- $shipping_recipient = array_key_exists( 'recipientName', $shippingAddress ) ? $shippingAddress['recipientName'] : '';
498
- $shipping_first_name = '';
499
- $shipping_last_name = '';
500
- if ( ! empty( $shipping_recipient ) ) {
501
- $shipping_recipient_parts = explode( " ", $shipping_recipient );
502
- $shipping_first_name = $shipping_recipient_parts[0];
503
- unset( $shipping_recipient_parts[0] );
504
- $shipping_last_name = implode( " ", $shipping_recipient_parts );
505
- }
506
-
507
- $ship_to_different_address = 1;
508
-
509
- $sanitized_array = compact(
510
- 'paypalbraintree_nonce',
511
- 'billing_first_name', 'billing_last_name', 'billing_phone', 'billing_email',
512
- 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country',
513
- 'shipping_first_name', 'shipping_last_name',
514
- 'shipping_address_1', 'shipping_address_2', 'shipping_city', 'shipping_state', 'shipping_postcode', 'shipping_country',
515
- 'ship_to_different_address'
516
- );
517
-
518
- return $sanitized_array;
519
- }
520
-
521
-
522
- /**
523
- * Validate the shop currency is supported
524
- * https://developers.braintreepayments.com/reference/general/currencies
525
- *
526
- * @since 1.0.0
527
- */
528
- public function is_shop_currency_supported() {
529
-
530
- $supported_currencies = array(
531
- 'AED', // United Arab Emirates Dirham
532
- 'AFN', // Afghan Afghani
533
- 'ALL', // Albanian Lek
534
- 'AMD', // Armenian Dram
535
- 'ANG', // Netherlands Antillean Gulden
536
- 'AOA', // Angolan Kwanza
537
- 'ARS', // Argentine Peso
538
- 'AUD', // Australian Dollar
539
- 'AWG', // Aruban Florin
540
- 'AZN', // Azerbaijani Manat
541
- 'BAM', // Bosnia and Herzegovina Convertible Mark
542
- 'BBD', // Barbadian Dollar
543
- 'BDT', // Bangladeshi Taka
544
- 'BGN', // Bulgarian Lev
545
- 'BHD', // Bahraini Dinar
546
- 'BIF', // Burundian Franc
547
- 'BMD', // Bermudian Dollar
548
- 'BND', // Brunei Dollar
549
- 'BOB', // Bolivian Boliviano
550
- 'BRL', // Brazilian Real
551
- 'BSD', // Bahamian Dollar
552
- 'BTN', // Bhutanese Ngultrum
553
- 'BWP', // Botswana Pula
554
- 'BYR', // Belarusian Ruble
555
- 'BZD', // Belize Dollar
556
- 'CAD', // Canadian Dollar
557
- 'CDF', // Congolese Franc
558
- 'CHF', // Swiss Franc
559
- 'CLP', // Chilean Peso
560
- 'CNY', // Chinese Renminbi Yuan
561
- 'COP', // Colombian Peso
562
- 'CRC', // Costa Rican Colón
563
- 'CUC', // Cuban Convertible Peso
564
- 'CUP', // Cuban Peso
565
- 'CVE', // Cape Verdean Escudo
566
- 'CZK', // Czech Koruna
567
- 'DJF', // Djiboutian Franc
568
- 'DKK', // Danish Krone
569
- 'DOP', // Dominican Peso
570
- 'DZD', // Algerian Dinar
571
- 'EEK', // Estonian Kroon
572
- 'EGP', // Egyptian Pound
573
- 'ERN', // Eritrean Nakfa
574
- 'ETB', // Ethiopian Birr
575
- 'EUR', // Euro
576
- 'FJD', // Fijian Dollar
577
- 'FKP', // Falkland Pound
578
- 'GBP', // British Pound
579
- 'GEL', // Georgian Lari
580
- 'GHS', // Ghanaian Cedi
581
- 'GIP', // Gibraltar Pound
582
- 'GMD', // Gambian Dalasi
583
- 'GNF', // Guinean Franc
584
- 'GTQ', // Guatemalan Quetzal
585
- 'GYD', // Guyanese Dollar
586
- 'HKD', // Hong Kong Dollar
587
- 'HNL', // Honduran Lempira
588
- 'HRK', // Croatian Kuna
589
- 'HTG', // Haitian Gourde
590
- 'HUF', // Hungarian Forint
591
- 'IDR', // Indonesian Rupiah
592
- 'ILS', // Israeli New Sheqel
593
- 'INR', // Indian Rupee
594
- 'IQD', // Iraqi Dinar
595
- 'IRR', // Iranian Rial
596
- 'ISK', // Icelandic Króna
597
- 'JMD', // Jamaican Dollar
598
- 'JOD', // Jordanian Dinar
599
- 'JPY', // Japanese Yen
600
- 'KES', // Kenyan Shilling
601
- 'KGS', // Kyrgyzstani Som
602
- 'KHR', // Cambodian Riel
603
- 'KMF', // Comorian Franc
604
- 'KPW', // North Korean Won
605
- 'KRW', // South Korean Won
606
- 'KWD', // Kuwaiti Dinar
607
- 'KYD', // Cayman Islands Dollar
608
- 'KZT', // Kazakhstani Tenge
609
- 'LAK', // Lao Kip
610
- 'LBP', // Lebanese Lira
611
- 'LKR', // Sri Lankan Rupee
612
- 'LRD', // Liberian Dollar
613
- 'LSL', // Lesotho Loti
614
- 'LTL', // Lithuanian Litas
615
- 'LVL', // Latvian Lats
616
- 'LYD', // Libyan Dinar
617
- 'MAD', // Moroccan Dirham
618
- 'MDL', // Moldovan Leu
619
- 'MGA', // Malagasy Ariary
620
- 'MKD', // Macedonian Denar
621
- 'MMK', // Myanmar Kyat
622
- 'MNT', // Mongolian Tögrög
623
- 'MOP', // Macanese Pataca
624
- 'MRO', // Mauritanian Ouguiya
625
- 'MUR', // Mauritian Rupee
626
- 'MVR', // Maldivian Rufiyaa
627
- 'MWK', // Malawian Kwacha
628
- 'MXN', // Mexican Peso
629
- 'MYR', // Malaysian Ringgit
630
- 'MZN', // Mozambican Metical
631
- 'NAD', // Namibian Dollar
632
- 'NGN', // Nigerian Naira
633
- 'NIO', // Nicaraguan Córdoba
634
- 'NOK', // Norwegian Krone
635
- 'NPR', // Nepalese Rupee
636
- 'NZD', // New Zealand Dollar
637
- 'OMR', // Omani Rial
638
- 'PAB', // Panamanian Balboa
639
- 'PEN', // Peruvian Nuevo Sol
640
- 'PGK', // Papua New Guinean Kina
641
- 'PHP', // Philippine Peso
642
- 'PKR', // Pakistani Rupee
643
- 'PLN', // Polish Złoty
644
- 'PYG', // Paraguayan Guaraní
645
- 'QAR', // Qatari Riyal
646
- 'RON', // Romanian Leu
647
- 'RSD', // Serbian Dinar
648
- 'RUB', // Russian Ruble
649
- 'RWF', // Rwandan Franc
650
- 'SAR', // Saudi Riyal
651
- 'SBD', // Solomon Islands Dollar
652
- 'SCR', // Seychellois Rupee
653
- 'SDG', // Sudanese Pound
654
- 'SEK', // Swedish Krona
655
- 'SGD', // Singapore Dollar
656
- 'SHP', // Saint Helenian Pound
657
- 'SKK', // Slovak Koruna
658
- 'SLL', // Sierra Leonean Leone
659
- 'SOS', // Somali Shilling
660
- 'SRD', // Surinamese Dollar
661
- 'STD', // São Tomé and Príncipe Dobra
662
- 'SVC', // Salvadoran Colón
663
- 'SYP', // Syrian Pound
664
- 'SZL', // Swazi Lilangeni
665
- 'THB', // Thai Baht
666
- 'TJS', // Tajikistani Somoni
667
- 'TMM', // Turkmenistani Manat
668
- 'TMT', // Turkmenistani Manat
669
- 'TND', // Tunisian Dinar
670
- 'TOP', // Tongan Paʻanga
671
- 'TRY', // Turkish New Lira
672
- 'TTD', // Trinidad and Tobago Dollar
673
- 'TWD', // New Taiwan Dollar
674
- 'TZS', // Tanzanian Shilling
675
- 'UAH', // Ukrainian Hryvnia
676
- 'UGX', // Ugandan Shilling
677
- 'USD', // United States Dollar
678
- 'UYU', // Uruguayan Peso
679
- 'UZS', // Uzbekistani Som
680
- 'VEF', // Venezuelan Bolívar
681
- 'VND', // Vietnamese Đồng
682
- 'VUV', // Vanuatu Vatu
683
- 'WST', // Samoan Tala
684
- 'XAF', // Central African Cfa Franc
685
- 'XCD', // East Caribbean Dollar
686
- 'XOF', // West African Cfa Franc
687
- 'XPF', // Cfp Franc
688
- 'YER', // Yemeni Rial
689
- 'ZAR', // South African Rand
690
- 'ZMK', // Zambian Kwacha
691
- 'ZWD' // Zimbabwean Dollar
692
- );
693
-
694
- return ( in_array( get_woocommerce_currency(), $supported_currencies ) );
695
- }
696
-
697
- /**
698
- * Don't allow use of this extension if the currency is not supported or if setup is incomplete
699
- *
700
- * @since 1.0.0
701
- */
702
- function is_valid_for_use() {
703
- if ( ! is_ssl() && ! $this->testmode ) {
704
- return false;
705
- }
706
-
707
- if ( ! $this->is_shop_currency_supported() ) {
708
- return false;
709
- }
710
-
711
- if ( empty( $this->merchant_access_token ) ) {
712
- return false;
713
- }
714
-
715
- return true;
716
- }
717
-
718
-
719
- /**
720
- * payment_fields
721
- *
722
- * @since 1.0.0
723
- */
724
- public function payment_fields() {
725
-
726
- $description = $this->get_description();
727
- if ( $this->testmode ) {
728
- $description .= ' ' . __( '(Sandbox mode is enabled -- Use a test account)', 'woocommerce-gateway-paypal-braintree' );
729
- }
730
-
731
- $model = array(
732
- 'description' => $description
733
- );
734
-
735
- // Add nonce from postback data if present
736
- if ( WC_PayPal_Braintree_Loader::getInstance()->does_session_have_postback_data() ) {
737
- $postback_data = WC()->session->get( 'paypal_braintree_postback' );
738
- $model['paypalbraintree_nonce'] = $postback_data['paypalbraintree_nonce'];
739
- }
740
-
741
- if ( ! empty( $this->checkout_template ) ) {
742
- wc_get_template(
743
- $this->checkout_template,
744
- array(
745
- 'model' => $model
746
- ),
747
- '',
748
- dirname( __FILE__ ) . '/../templates/'
749
- );
750
- }
751
-
752
- }
753
-
754
- /**
755
- * validate_fields
756
- *
757
- * @since 1.0.0
758
- */
759
- public function validate_fields() {
760
- return true;
761
- }
762
-
763
- public static function get_posted_variable( $variable, $default = '' ) {
764
- return ( isset( $_POST[$variable] ) ? $_POST[$variable] : $default );
765
- }
766
-
767
- public static function sanitize_array( $array ) {
768
- $sanitized_array = array();
769
-
770
- foreach( $array as $key => $value ) {
771
- $sanitized_array[$key] = is_array( $value ) ? self::sanitize_array( $value ) : sanitize_text_field( $value );
772
- }
773
-
774
- return $sanitized_array;
775
- }
776
-
777
- /**
778
- * process_payment
779
- *
780
- * @since 1.0.0
781
- */
782
- public function process_payment( $order_id ) {
783
- $order = wc_get_order( $order_id );
784
-
785
- $this->log( __FUNCTION__, "Info: Beginning processing payment for order $order_id for the amount of {$order->order_total}" );
786
- $this->log( __FUNCTION__, "Info: Merchant ID = {$this->merchant_id}" );
787
-
788
- if ( ! $order->needs_payment() ) {
789
- $this->log( __FUNCTION__, "Error: Order does not need payment." );
790
- wc_add_notice( __( 'Error: This order does not need a payment.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
791
- return false;
792
- }
793
-
794
- $paypal_braintree_nonce = self::get_posted_variable( 'paypalbraintree_nonce' );
795
- if ( empty( $paypal_braintree_nonce ) ) {
796
- $this->log( __FUNCTION__, "Error: The paypal_braintree_nonce was unexpectedly empty" );
797
- wc_add_notice( __( 'Error: PayPal Powered by Braintree did not supply a payment nonce. Please try again later or use another means of payment.', 'woocommerce-gateway-paypal-braintree' ), 'error' );
798
- return false;
799
- }
800
-
801
- // Billing data, assemble
802
- $billing = array(
803
- 'firstName' => $order->billing_first_name,
804
- 'lastName' => $order->billing_last_name,
805
- 'company' => $order->billing_company,
806
- 'streetAddress' => $order->billing_address_1,
807
- 'extendedAddress' => $order->billing_address_2,
808
- 'locality' => $order->billing_city,
809
- 'region' => $order->billing_state,
810
- 'postalCode' => $order->billing_postcode,
811
- 'countryCodeAlpha2' => $order->billing_country
812
- );
813
-
814
- // Shipping data, assemble
815
- $shipping = array(
816
- 'firstName' => $order->shipping_first_name,
817
- 'lastName' => $order->shipping_last_name,
818
- 'company' => $order->shipping_company,
819
- 'streetAddress' => $order->shipping_address_1,
820
- 'extendedAddress' => $order->shipping_address_2,
821
- 'locality' => $order->shipping_city,
822
- 'region' => $order->shipping_state,
823
- 'postalCode' => $order->shipping_postcode,
824
- 'countryCodeAlpha2' => $order->shipping_country
825
- );
826
-
827
- $sale_args = apply_filters( 'wc_gateway_paypal_braintree_sale_args', array(
828
- 'amount' => $order->order_total,
829
- 'billing' => $billing,
830
- 'shipping' => $shipping,
831
- 'paymentMethodNonce' => $paypal_braintree_nonce,
832
- 'channel' => 'WooThemes_BT', // aka BN tracking code
833
- 'orderId' => $order_id,
834
- 'options' => array(
835
- 'submitForSettlement' => $this->capture ? 'true' : 'false',
836
- ),
837
- ) );
838
-
839
- require_once( dirname( __FILE__ ) . '/../braintree_sdk/lib/Braintree.php' );
840
- $gateway = new Braintree_Gateway( array(
841
- 'accessToken' => $this->merchant_access_token,
842
- ) );
843
-
844
- try {
845
- $result = $gateway->transaction()->sale( $sale_args );
846
- } catch ( Exception $e ) {
847
- $notice = sprintf( __( 'Error: PayPal Powered by Braintree was unable to complete the transaction. Please try again later or use another means of payment. Reason: %s', 'woocommerce-gateway-paypal-braintree' ), $e->getMessage() );
848
- wc_add_notice( $notice, 'error' );
849
- $this->log( __FUNCTION__, 'Error: Unable to complete transaction. Reason: ' . $e->getMessage() );
850
- return false;
851
- }
852
-
853
- // Check result
854
- if ( ! $result->success ) {
855
- $notice = sprintf( __( 'Error: PayPal Powered by Braintree was unable to complete the transaction. Please try again later or use another means of payment. Reason: %s', 'woocommerce-gateway-paypal-braintree' ), $result->message );
856
- wc_add_notice( $notice, 'error' );
857
- $this->log( __FUNCTION__, "Error: Unable to complete transaction. Reason: {$result->message}" );
858
- return false;
859
- }
860
-
861
- $transaction_id = $result->transaction->id;
862
- $maybe_settled_later = array(
863
- Braintree_Transaction::SETTLING,
864
- Braintree_Transaction::SETTLEMENT_PENDING,
865
- Braintree_Transaction::SUBMITTED_FOR_SETTLEMENT,
866
- );
867
-
868
- if ( in_array( $result->transaction->status, $maybe_settled_later ) ) {
869
- // Store captured value.
870
- update_post_meta( $order->id, '_pp_braintree_charge_captured', 'yes' );
871
-
872
- $this->log( __FUNCTION__, sprintf( 'Info: Successfully processed payment, transaction id = %s, status = %s', $transaction_id, $result->transaction->status ) );
873
-
874
- // Payment complete.
875
- $order->payment_complete( $transaction_id );
876
-
877
- $this->log( __FUNCTION__, "Info: Completed processing of payment for order $order_id" );
878
-
879
- // Add order note
880
- $order->add_order_note( sprintf( __( 'PayPal Braintree charge complete (Charge ID: %s)', 'woocommerce-gateway-paypal-braintree' ), $transaction_id ) );
881
- } else if ( Braintree_Transaction::AUTHORIZED === $result->transaction->status ) {
882
-
883
- $this->log( __FUNCTION__, sprintf( 'Info: Successfully authorized transaction id = %s, status = %s', $transaction_id, $result->transaction->status ) );
884
-
885
- update_post_meta( $order->id, '_pp_braintree_charge_captured', 'no' );
886
-
887
- add_post_meta( $order->id, '_transaction_id', $transaction_id, true );
888
-
889
- // Mark as on-hold.
890
- $order->update_status( 'on-hold', sprintf( __( 'PayPal Braintree charge authorized (Charge ID: %s). Process order to take payment, or cancel to remove the pre-authorization.', 'woocommerce-gateway-paypal-braintree' ), $transaction_id ) );
891
-
892
- // Reduce stock levels
893
- $order->reduce_order_stock();
894
-
895
- } else {
896
-
897
- $this->log( __FUNCTION__, sprintf( 'Info: unhandled transaction id = %s, status = %s', $transaction_id, $result->transaction->status ) );
898
-
899
- $order->update_status( 'on-hold', sprintf( __( 'Transaction was submitted to PayPal Braintree but not handled by WooCommerce order, transaction_id: %s, status: %s. Order was put in-hold.', 'woocommerce-gateway-paypal-braintree' ), $transaction_id, $tresult->transaction->status ) );
900
- }
901
-
902
- // on success, return thank you page redirect
903
- return array(
904
- 'result' => 'success',
905
- 'redirect' => $this->get_return_url( $order )
906
- );
907
- }
908
-
909
- /**
910
- * Get the order's transaction url
911
- * @param WC_Order $order
912
- * @return bool
913
- */
914
- function get_transaction_url( $order ) {
915
- $transaction_id = $order->get_transaction_id();
916
-
917
- if ( empty( $transaction_id ) ) {
918
- return false;
919
- }
920
-
921
- if ( $this->testmode ) {
922
- $server = "sandbox.braintreegateway.com";
923
- } else {
924
- $server = "braintreegateway.com";
925
- }
926
-
927
- return "https://" . $server . "/merchants/" . urlencode( $this->merchant_id ). "/transactions/" . urlencode( $transaction_id );
928
- }
929
-
930
-
931
- /**
932
- * Can the order be refunded?
933
- * @param WC_Order $order
934
- * @return bool
935
- */
936
- public function can_refund_order( $order ) {
937
- return $order && $order->get_transaction_id();
938
- }
939
-
940
-
941
- /**
942
- * Process a refund if supported
943
- * @param int $order_id
944
- * @param float $amount
945
- * @param string $reason
946
- * @return boolean True or false based on success, or a WP_Error object
947
- */
948
- public function process_refund( $order_id, $refund_amount = null, $reason = '' ) {
949
-
950
- $this->log( __FUNCTION__, "Info: Beginning processing refund/void for order $order_id" );
951
- $this->log( __FUNCTION__, "Info: Merchant ID = {$this->merchant_id}" );
952
-
953
- $order = wc_get_order( $order_id );
954
-
955
- if ( ! $this->can_refund_order( $order ) ) {
956
- $this->log( __FUNCTION__, "Error: Unable to refund/void order {$order_id}. Order has no transaction ID." );
957
- return false;
958
- }
959
-
960
- if ( ! $refund_amount ) {
961
- $refund_amount = floatval( $order->get_total() );
962
- }
963
-
964
- $this->log( __FUNCTION__, "Info: Amount = {$refund_amount}" );
965
-
966
- $transaction_id = $order->get_transaction_id();
967
-
968
- require_once( dirname( __FILE__ ) . '/../braintree_sdk/lib/Braintree.php' );
969
- $gateway = new Braintree_Gateway( array(
970
- 'accessToken' => $this->merchant_access_token,
971
- ) );
972
-
973
- // See if the transaction is not yet settled and should be voided instead of refunded
974
- // If for some reason the transaction cannot be found, an Exception will be thrown
975
-
976
- try {
977
- $transaction = $gateway->transaction()->find( $transaction_id );
978
- } catch ( Exception $e ) {
979
- $this->log( __FUNCTION__, "Error: Unable to find transaction with transaction ID {$transaction_id}. Reason: " . $e->getMessage() );
980
- return false;
981
- }
982
-
983
- $this->log( __FUNCTION__, "Info: Order {$order_id} with transaction ID {$transaction_id} has status {$transaction->status}" );
984
-
985
- // Ref: https://developers.braintreepayments.com/reference/request/transaction/void/php
986
- // Ref: https://developers.braintreepayments.com/reference/request/transaction/refund/php
987
- $action_to_take = '';
988
- switch ( $transaction->status ) {
989
- case Braintree_Transaction::AUTHORIZED :
990
- case Braintree_Transaction::SUBMITTED_FOR_SETTLEMENT :
991
- case Braintree_Transaction::SETTLEMENT_PENDING :
992
- $action_to_take = "void";
993
- break;
994
- case Braintree_Transaction::SETTLED :
995
- case Braintree_Transaction::SETTLING :
996
- $action_to_take = "refund";
997
- break;
998
- }
999
-
1000
- if ( empty( $action_to_take ) ) {
1001
- $this->log( __FUNCTION__, "Error: The transaction cannot be voided nor refunded in its current state: state = {$transaction->status}" );
1002
- return false;
1003
- }
1004
-
1005
- // Only void transaction when refund amount equals to order's total.
1006
- if ( 'void' === $action_to_take && $refund_amount != $order->get_total() ) {
1007
- return new WP_Error( 'unable_to_void', __( 'Unable to void unsettled transaction when refunding partially.', 'woocommerce-gateway-paypal-braintree' ) );
1008
- }
1009
-
1010
- try {
1011
- if ( "void" === $action_to_take ) {
1012
- $result = $gateway->transaction()->void( $transaction_id );
1013
- } else {
1014
- $result = $gateway->transaction()->refund( $transaction_id, $refund_amount );
1015
- }
1016
- } catch ( Exception $e ) {
1017
- $this->log( __FUNCTION__, 'Error: The transaction cannot be voided nor refunded. Reason: ' . $e->getMessage() );
1018
- return false;
1019
- }
1020
-
1021
- if ( ! $result->success ) {
1022
- $this->log( __FUNCTION__, "Error: The transaction cannot be voided nor refunded - reason: = {$result->message}" );
1023
- return false;
1024
- }
1025
-
1026
- // Get the refund/void transaction ID
1027
- $latest_transaction_id = $result->transaction->id;
1028
-
1029
- if ( "void" === $action_to_take ) {
1030
- $order->add_order_note(
1031
- sprintf(
1032
- __( 'Voided - Void ID: %s - Reason: %s', 'woocommerce-gateway-paypal-braintree' ),
1033
- $latest_transaction_id,
1034
- $reason
1035
- )
1036
- );
1037
- $this->log( __FUNCTION__, "Info: Successfully voided order {$order_id}" );
1038
- } else {
1039
- $order->add_order_note(
1040
- sprintf(
1041
- __( 'Refunded %s - Refund ID: %s - Reason: %s', 'woocommerce-gateway-paypal-braintree' ),
1042
- wc_price( $refund_amount ),
1043
- $latest_transaction_id,
1044
- $reason
1045
- )
1046
- );
1047
- $this->log( __FUNCTION__, "Info: Successfully refunded {$refund_amount} for order {$order_id}" );
1048
- }
1049
-
1050
- return true;
1051
- }
1052
-
1053
- /**
1054
- * admin_enqueue_scripts
1055
- *
1056
- * @since 1.0.0
1057
- */
1058
- public function admin_enqueue_scripts() {
1059
- wp_enqueue_style( 'paypal_braintree_admin_styles', plugins_url( '../assets/css/admin.css', __FILE__ ) );
1060
- }
1061
-
1062
-
1063
- /**
1064
- * When cart based Checkout with PayPal is in effect, we need to select ourselves as the payment method.
1065
- *
1066
- * @since 1.0.0
1067
- */
1068
- public function possibly_set_chosen_payment_method() {
1069
-
1070
- // skip if this is a real POST
1071
- if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
1072
- return;
1073
- }
1074
-
1075
- // skip if PayPal data not available
1076
- if ( ! WC_PayPal_Braintree_Loader::getInstance()->does_session_have_postback_data() ) {
1077
- return;
1078
- }
1079
-
1080
- // set as chosen payment method (for WC 2.3+)
1081
- $this->chosen = true;
1082
- }
1083
-
1084
-
1085
- /**
1086
- * When cart based Checkout with PayPal is in effect, we need to take the data we saved in the session
1087
- * and fill in the checkout form with it.
1088
- *
1089
- * @since 1.0.0
1090
- */
1091
- public function possibly_set_checkout_value( $value, $key ) {
1092
-
1093
- // skip if this is a real POST
1094
- if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
1095
- return $value;
1096
- }
1097
-
1098
- // skip if PayPal data not available
1099
- if ( ! WC_PayPal_Braintree_Loader::getInstance()->does_session_have_postback_data() ) {
1100
- return $value;
1101
- }
1102
-
1103
- $postback_data = WC()->session->get( 'paypal_braintree_postback' );
1104
- if ( array_key_exists( $key, $postback_data ) ) {
1105
- return $postback_data[$key];
1106
- }
1107
-
1108
- if ( 'order_comments' === $key ) {
1109
- if ( array_key_exists( 'order_note', $postback_data ) ) {
1110
- return $postback_data['order_note'];
1111
- }
1112
- }
1113
-
1114
- return $value;
1115
- }
1116
-
1117
-
1118
- /**
1119
- * When cart based Checkout with PayPal is in effect, we need to tick the checkbox to ensure
1120
- * the shipping details provided by PayPal are saved with the order.
1121
- *
1122
- * @since 1.0.0
1123
- */
1124
- public function possibly_set_ship_to_different_address( $ship_to_different_address ) {
1125
-
1126
- if ( WC_PayPal_Braintree_Loader::getInstance()->does_session_have_postback_data() ) {
1127
- return true;
1128
- }
1129
-
1130
- return $ship_to_different_address;
1131
- }
1132
-
1133
- /**
1134
- * Shorthand for loader singleton logger
1135
- *
1136
- * @since 1.0.0
1137
- */
1138
- protected function log( $context, $message ) {
1139
- if ( $this->debug ) {
1140
- WC_PayPal_Braintree_Loader::getInstance()->log( $context, $message );
1141
- }
1142
- }
1143
-
1144
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
i18n/languages/woocommerce-gateway-paypal-powered-by-braintree.pot ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2017 WooCommerce
2
+ # This file is distributed under the same license as the WooCommerce PayPal Powered by Braintree Gateway package.
3
+ msgid ""
4
+ msgstr ""
5
+ "Project-Id-Version: WooCommerce PayPal Powered by Braintree Gateway 2.0.0\n"
6
+ "Report-Msgid-Bugs-To: "
7
+ "https://wordpress.org/support/plugin/woocommerce-gateway-paypal-powered-by-"
8
+ "braintree/\n"
9
+ "POT-Creation-Date: 2017-02-10 18:32:26+00:00\n"
10
+ "MIME-Version: 1.0\n"
11
+ "Content-Type: text/plain; charset=utf-8\n"
12
+ "Content-Transfer-Encoding: 8bit\n"
13
+ "PO-Revision-Date: 2017-MO-DA HO:MI+ZONE\n"
14
+ "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
15
+ "Language-Team: LANGUAGE <LL@li.org>\n"
16
+
17
+ #: class-wc-braintree.php:35
18
+ msgid ""
19
+ "WooCommerce PayPal Powered by Braintree is inactive because WooCommerce is "
20
+ "not installed."
21
+ msgstr ""
22
+
23
+ #: class-wc-braintree.php:233
24
+ msgid "Connected successfully."
25
+ msgstr ""
26
+
27
+ #: class-wc-braintree.php:236
28
+ msgid "There was an error connecting your Braintree account. Please try again."
29
+ msgstr ""
30
+
31
+ #: class-wc-braintree.php:266
32
+ msgid "Invalid connection request"
33
+ msgstr ""
34
+
35
+ #: class-wc-braintree.php:308
36
+ msgid "Disconnected successfully."
37
+ msgstr ""
38
+
39
+ #: class-wc-braintree.php:333
40
+ msgid "Invalid disconnect request"
41
+ msgstr ""
42
+
43
+ #: class-wc-braintree.php:393
44
+ msgid ""
45
+ "Heads up! You've enabled advanced fraud tools for Braintree. Please make "
46
+ "sure that advanced fraud tools are also enabled in your Braintree account. "
47
+ "Need help? See the %1$sdocumentation%2$s."
48
+ msgstr ""
49
+
50
+ #: class-wc-braintree.php:411
51
+ msgid ""
52
+ "PayPal powered by Braintree is almost ready. To get started, %1$sconnect "
53
+ "your Braintree account%2$s."
54
+ msgstr ""
55
+
56
+ #: class-wc-braintree.php:423
57
+ msgid ""
58
+ "Upgrade successful! WooCommerce Braintree deactivated, and PayPal Powered "
59
+ "by Braintree has been %1$sconfigured with your previous settings%2$s."
60
+ msgstr ""
61
+
62
+ #: class-wc-braintree.php:436
63
+ msgid ""
64
+ "WooCommerce is not being forced over SSL -- Using PayPal with Braintree "
65
+ "requires that checkout to be forced over SSL."
66
+ msgstr ""
67
+
68
+ #. Plugin Name of the plugin/theme
69
+ msgid "WooCommerce PayPal Powered by Braintree Gateway"
70
+ msgstr ""
71
+
72
+ #: class-wc-braintree.php:533
73
+ msgid "Configure Credit Card"
74
+ msgstr ""
75
+
76
+ #: class-wc-braintree.php:533
77
+ msgid "Configure PayPal"
78
+ msgstr ""
79
+
80
+ #: includes/api/class-wc-braintree-api-response-message-helper.php:137
81
+ msgid ""
82
+ "Sorry, we cannot process your transaction. The PayPal account is either "
83
+ "locked or closed. Please use a different account or a different payment "
84
+ "method."
85
+ msgstr ""
86
+
87
+ #: includes/api/class-wc-braintree-api.php:194
88
+ msgid "The billing address for this transaction does not match the cardholders."
89
+ msgstr ""
90
+
91
+ #: includes/api/class-wc-braintree-api.php:198
92
+ msgid "The CSC for the transaction was invalid or incorrect."
93
+ msgstr ""
94
+
95
+ #: includes/api/class-wc-braintree-api.php:527
96
+ msgid ""
97
+ "Invalid Credentials, please double-check your API credentials (Merchant ID, "
98
+ "Public Key, Private Key, and Merchant Account ID) and try again."
99
+ msgstr ""
100
+
101
+ #: includes/api/class-wc-braintree-api.php:531
102
+ msgid ""
103
+ "Authorization Failed, please verify the user for the API credentials "
104
+ "provided can perform transactions and that the request data is correct."
105
+ msgstr ""
106
+
107
+ #: includes/api/class-wc-braintree-api.php:535
108
+ msgid "Braintree is currently down for maintenance, please try again later."
109
+ msgstr ""
110
+
111
+ #: includes/api/class-wc-braintree-api.php:539
112
+ msgid "The record cannot be found, please contact support."
113
+ msgstr ""
114
+
115
+ #: includes/api/class-wc-braintree-api.php:543
116
+ msgid ""
117
+ "Braintree encountered an error when processing your request, please try "
118
+ "again later or contact support."
119
+ msgstr ""
120
+
121
+ #: includes/api/class-wc-braintree-api.php:547
122
+ msgid ""
123
+ "Braintree cannot verify your server's SSL certificate. Please contact your "
124
+ "hosting provider or try again later."
125
+ msgstr ""
126
+
127
+ #: includes/api/responses/class-wc-braintree-api-credit-card-transaction-response.php:64
128
+ msgid "Required credit card token is missing or empty!"
129
+ msgstr ""
130
+
131
+ #: includes/api/responses/class-wc-braintree-api-paypal-transaction-response.php:66
132
+ msgid "Required PayPal token is missing or empty!"
133
+ msgstr ""
134
+
135
+ #: includes/class-wc-braintree-frontend.php:113
136
+ #. translators: %s - last four digits of a card/account
137
+ msgid "ending in %s"
138
+ msgstr ""
139
+
140
+ #: includes/class-wc-braintree-frontend.php:119
141
+ msgid "(default)"
142
+ msgstr ""
143
+
144
+ #: includes/class-wc-braintree-paypal-cart.php:370
145
+ msgid "Cancel"
146
+ msgstr ""
147
+
148
+ #: includes/class-wc-gateway-braintree-credit-card.php:61
149
+ msgid "Braintree (Credit Card)"
150
+ msgstr ""
151
+
152
+ #: includes/class-wc-gateway-braintree-credit-card.php:62
153
+ msgid "Allow customers to securely pay using their credit card via Braintree."
154
+ msgstr ""
155
+
156
+ #: includes/class-wc-gateway-braintree-credit-card.php:151
157
+ msgid "Basic"
158
+ msgstr ""
159
+
160
+ #: includes/class-wc-gateway-braintree-credit-card.php:152
161
+ msgid "Advanced"
162
+ msgstr ""
163
+
164
+ #: includes/class-wc-gateway-braintree-credit-card.php:157
165
+ msgid "Kount Direct"
166
+ msgstr ""
167
+
168
+ #: includes/class-wc-gateway-braintree-credit-card.php:164
169
+ msgid "Fraud Settings"
170
+ msgstr ""
171
+
172
+ #: includes/class-wc-gateway-braintree-credit-card.php:168
173
+ msgid "Fraud Tool"
174
+ msgstr ""
175
+
176
+ #: includes/class-wc-gateway-braintree-credit-card.php:171
177
+ msgid ""
178
+ "Select the fraud tool you want to use. Basic is enabled by default and "
179
+ "requires no additional configuration. Advanced requires you to enable "
180
+ "advanced fraud tools in your Braintree control panel. To use Kount Direct "
181
+ "you must contact Braintree support."
182
+ msgstr ""
183
+
184
+ #: includes/class-wc-gateway-braintree-credit-card.php:175
185
+ msgid "Kount merchant ID"
186
+ msgstr ""
187
+
188
+ #: includes/class-wc-gateway-braintree-credit-card.php:178
189
+ msgid "Speak with your account management team at Braintree to get this."
190
+ msgstr ""
191
+
192
+ #: includes/class-wc-gateway-braintree-credit-card.php:183
193
+ msgid "3D Secure (Verified by Visa, MasterCard SecureCode)"
194
+ msgstr ""
195
+
196
+ #: includes/class-wc-gateway-braintree-credit-card.php:185
197
+ msgid ""
198
+ "3D Secure benefits cardholders and merchants by providing an additional "
199
+ "layer of verification. %1$sLearn more about 3D Secure%2$s."
200
+ msgstr ""
201
+
202
+ #: includes/class-wc-gateway-braintree-credit-card.php:188
203
+ msgid "3D Secure"
204
+ msgstr ""
205
+
206
+ #: includes/class-wc-gateway-braintree-credit-card.php:190
207
+ msgid "Enable 3D Secure (Visa and MasterCard cards only)"
208
+ msgstr ""
209
+
210
+ #: includes/class-wc-gateway-braintree-credit-card.php:191
211
+ msgid ""
212
+ "You must contact Braintree support to add this feature to your Braintree "
213
+ "account before enabling this option."
214
+ msgstr ""
215
+
216
+ #: includes/class-wc-gateway-braintree-credit-card.php:212
217
+ msgid "Card Verification (CSC)"
218
+ msgstr ""
219
+
220
+ #: includes/class-wc-gateway-braintree-credit-card.php:213
221
+ msgid "Display and Require the Card Security Code (CVV/CID) field on checkout"
222
+ msgstr ""
223
+
224
+ #: includes/class-wc-gateway-braintree-credit-card.php:677
225
+ #: includes/payment-forms/class-wc-braintree-hosted-fields-payment-form.php:124
226
+ msgid ""
227
+ "We cannot process your order with the payment information that you "
228
+ "provided. Please use an alternate payment method."
229
+ msgstr ""
230
+
231
+ #: includes/class-wc-gateway-braintree-credit-card.php:684
232
+ #: includes/class-wc-gateway-braintree.php:158
233
+ msgid ""
234
+ "Oops, there was a temporary payment error. Please try another payment "
235
+ "method or contact us to complete your transaction."
236
+ msgstr ""
237
+
238
+ #: includes/class-wc-gateway-braintree-paypal.php:52
239
+ msgid "Braintree (PayPal)"
240
+ msgstr ""
241
+
242
+ #: includes/class-wc-gateway-braintree-paypal.php:53
243
+ msgid "Allow customers to securely pay using their PayPal account via Braintree."
244
+ msgstr ""
245
+
246
+ #: includes/class-wc-gateway-braintree-paypal.php:119
247
+ msgid "Token ID"
248
+ msgstr ""
249
+
250
+ #: includes/class-wc-gateway-braintree-paypal.php:124
251
+ msgid "Email"
252
+ msgstr ""
253
+
254
+ #: includes/class-wc-gateway-braintree-paypal.php:163
255
+ msgid "Use a new PayPal account"
256
+ msgstr ""
257
+
258
+ #: includes/class-wc-gateway-braintree-paypal.php:167
259
+ msgid "PayPal Accounts"
260
+ msgstr ""
261
+
262
+ #: includes/class-wc-gateway-braintree-paypal.php:188
263
+ msgid "Unlink"
264
+ msgstr ""
265
+
266
+ #: includes/class-wc-gateway-braintree-paypal.php:333
267
+ #. translators: Placeholders: %1$s - payment method title (e.g. PayPal), %2$s -
268
+ #. transaction environment (either Sandbox or blank string), %3$s - type of
269
+ #. transaction (either Authorization or Payment)
270
+ msgid "%1$s %2$s %3$s Approved"
271
+ msgstr ""
272
+
273
+ #: includes/class-wc-gateway-braintree-paypal.php:335
274
+ #: includes/class-wc-gateway-braintree.php:1248
275
+ msgid "Sandbox"
276
+ msgstr ""
277
+
278
+ #: includes/class-wc-gateway-braintree-paypal.php:336
279
+ msgid "Authorization"
280
+ msgstr ""
281
+
282
+ #: includes/class-wc-gateway-braintree-paypal.php:336
283
+ msgid "Payment"
284
+ msgstr ""
285
+
286
+ #: includes/class-wc-gateway-braintree-paypal.php:342
287
+ #. translators: Placeholders: %s - transaction ID
288
+ msgid "(Transaction ID %s)"
289
+ msgstr ""
290
+
291
+ #: includes/class-wc-gateway-braintree-paypal.php:363
292
+ msgid "PayPal Account Saved: %s"
293
+ msgstr ""
294
+
295
+ #: includes/class-wc-gateway-braintree-paypal.php:442
296
+ msgid "PayPal"
297
+ msgstr ""
298
+
299
+ #: includes/class-wc-gateway-braintree-paypal.php:456
300
+ msgid ""
301
+ "Click the PayPal icon below to sign into your PayPal account and pay "
302
+ "securely."
303
+ msgstr ""
304
+
305
+ #: includes/class-wc-gateway-braintree.php:127
306
+ msgid "Oops, something went wrong. Please try a different payment method."
307
+ msgstr ""
308
+
309
+ #: includes/class-wc-gateway-braintree.php:311
310
+ msgid "Public Key"
311
+ msgstr ""
312
+
313
+ #: includes/class-wc-gateway-braintree.php:314
314
+ msgid "The Public Key for your Braintree account."
315
+ msgstr ""
316
+
317
+ #: includes/class-wc-gateway-braintree.php:318
318
+ msgid "Private Key"
319
+ msgstr ""
320
+
321
+ #: includes/class-wc-gateway-braintree.php:321
322
+ msgid "The Private Key for your Braintree account."
323
+ msgstr ""
324
+
325
+ #: includes/class-wc-gateway-braintree.php:325
326
+ msgid "Merchant ID"
327
+ msgstr ""
328
+
329
+ #: includes/class-wc-gateway-braintree.php:328
330
+ msgid "The Merchant ID for your Braintree account."
331
+ msgstr ""
332
+
333
+ #: includes/class-wc-gateway-braintree.php:333
334
+ msgid "Sandbox Public Key"
335
+ msgstr ""
336
+
337
+ #: includes/class-wc-gateway-braintree.php:336
338
+ msgid "The Public Key for your Braintree sandbox account."
339
+ msgstr ""
340
+
341
+ #: includes/class-wc-gateway-braintree.php:340
342
+ msgid "Sandbox Private Key"
343
+ msgstr ""
344
+
345
+ #: includes/class-wc-gateway-braintree.php:343
346
+ msgid "The Private Key for your Braintree sandbox account."
347
+ msgstr ""
348
+
349
+ #: includes/class-wc-gateway-braintree.php:347
350
+ msgid "Sandbox Merchant ID"
351
+ msgstr ""
352
+
353
+ #: includes/class-wc-gateway-braintree.php:350
354
+ msgid "The Merchant ID for your Braintree sandbox account."
355
+ msgstr ""
356
+
357
+ #: includes/class-wc-gateway-braintree.php:355
358
+ msgid "Merchant Account IDs"
359
+ msgstr ""
360
+
361
+ #: includes/class-wc-gateway-braintree.php:358
362
+ msgid ""
363
+ "Enter additional merchant account IDs if you do not want to use your "
364
+ "Braintree account default. %1$sLearn more about merchant account IDs%2$s"
365
+ msgstr ""
366
+
367
+ #: includes/class-wc-gateway-braintree.php:367
368
+ msgid "Dynamic Descriptors"
369
+ msgstr ""
370
+
371
+ #: includes/class-wc-gateway-braintree.php:370
372
+ #. translators: Placeholders: %1$s - <p> tag, %2$s - </p> tag, %3$s - <a> tag,
373
+ #. %4$s - </a> tag
374
+ msgid ""
375
+ "Dynamic descriptors define what will appear on your customers' credit card "
376
+ "statements for a specific purchase. Contact Braintree to enable these for "
377
+ "your account.%1$sPlease ensure that you have %3$sread the documentation on "
378
+ "dynamic descriptors%4$s and are using an accepted format.%2$s"
379
+ msgstr ""
380
+
381
+ #: includes/class-wc-gateway-braintree.php:374
382
+ msgid "Name"
383
+ msgstr ""
384
+
385
+ #: includes/class-wc-gateway-braintree.php:377
386
+ msgid ""
387
+ "The value in the business name field of a customer's statement. Company "
388
+ "name/DBA section must be either 3, 7 or 12 characters and the product "
389
+ "descriptor can be up to 18, 14, or 9 characters respectively (with an * in "
390
+ "between for a total descriptor name of 22 characters)."
391
+ msgstr ""
392
+
393
+ #: includes/class-wc-gateway-braintree.php:382
394
+ msgid "Phone"
395
+ msgstr ""
396
+
397
+ #: includes/class-wc-gateway-braintree.php:385
398
+ msgid ""
399
+ "The value in the phone number field of a customer's statement. Phone must "
400
+ "be exactly 10 characters and can only contain numbers, dashes, parentheses "
401
+ "and periods."
402
+ msgstr ""
403
+
404
+ #: includes/class-wc-gateway-braintree.php:390
405
+ msgid "URL"
406
+ msgstr ""
407
+
408
+ #: includes/class-wc-gateway-braintree.php:393
409
+ msgid ""
410
+ "The value in the URL/web address field of a customer's statement. The URL "
411
+ "must be 13 characters or less."
412
+ msgstr ""
413
+
414
+ #: includes/class-wc-gateway-braintree.php:426
415
+ msgid "Enter connection credentials manually"
416
+ msgstr ""
417
+
418
+ #: includes/class-wc-gateway-braintree.php:450
419
+ msgid "Disabled because the other gateway is not connected manually."
420
+ msgstr ""
421
+
422
+ #: includes/class-wc-gateway-braintree.php:469
423
+ msgid ""
424
+ "You just connected your Braintree account to WooCommerce. You can start "
425
+ "taking payments now."
426
+ msgstr ""
427
+
428
+ #: includes/class-wc-gateway-braintree.php:470
429
+ msgid ""
430
+ "Once you have processed a payment, PayPal will review your application for "
431
+ "final approval. Before you ship any goods make sure you have received a "
432
+ "final approval for your Braintree account."
433
+ msgstr ""
434
+
435
+ #: includes/class-wc-gateway-braintree.php:471
436
+ msgid "Questions? We are a phone call away: 1-855-489-0345."
437
+ msgstr ""
438
+
439
+ #: includes/class-wc-gateway-braintree.php:476
440
+ msgid "Click button to create an account with Braintree and start transacting."
441
+ msgstr ""
442
+
443
+ #: includes/class-wc-gateway-braintree.php:591
444
+ msgid "Add merchant account ID for %s"
445
+ msgstr ""
446
+
447
+ #: includes/class-wc-gateway-braintree.php:696
448
+ msgid "Add merchant account ID for "
449
+ msgstr ""
450
+
451
+ #: includes/class-wc-gateway-braintree.php:794
452
+ msgid "Merchant Account ID (%s)"
453
+ msgstr ""
454
+
455
+ #: includes/class-wc-gateway-braintree.php:805
456
+ msgid "Enter merchant account ID"
457
+ msgstr ""
458
+
459
+ #: includes/class-wc-gateway-braintree.php:806
460
+ msgid "Remove this merchant account ID"
461
+ msgstr ""
462
+
463
+ #: includes/class-wc-gateway-braintree.php:1248
464
+ msgid "Production"
465
+ msgstr ""
466
+
467
+ #: includes/payment-forms/class-wc-braintree-hosted-fields-payment-form.php:85
468
+ msgid "Expiration (MMYY)"
469
+ msgstr ""
470
+
471
+ #: includes/payment-forms/class-wc-braintree-paypal-payment-form.php:47
472
+ msgid ""
473
+ "Please click the blue \"PayPal\" button below to log into your PayPal "
474
+ "account before placing your order."
475
+ msgstr ""
476
+
477
+ #: includes/payment-forms/class-wc-braintree-paypal-payment-form.php:48
478
+ msgid ""
479
+ "Please click the blue \"PayPal\" button below to log into your PayPal "
480
+ "account before adding your payment method."
481
+ msgstr ""
482
+
483
+ #: includes/views/admin-html-braintree-auth.php:32
484
+ msgid "Connect/Disconnect"
485
+ msgstr ""
486
+
487
+ #: includes/views/admin-html-braintree-auth.php:40
488
+ msgid "Disconnect from PayPal Powered by Braintree"
489
+ msgstr ""
490
+
491
+ #: includes/views/admin-html-braintree-auth.php:48
492
+ msgid "Not ready to accept live payments? Click here to connect using sandbox mode."
493
+ msgstr ""
494
+
495
+ #: woocommerce-gateway-paypal-powered-by-braintree.php:113
496
+ msgid ""
497
+ "WooCommerce PayPal powered by Braintree is inactive. Please deactivate the "
498
+ "retired WooCommerce Braintree plugin."
499
+ msgstr ""
500
+
501
+ #: woocommerce-gateway-paypal-powered-by-braintree.php:198
502
+ msgid ""
503
+ "The minimum PHP version required for this plugin is %1$s. You are running "
504
+ "%2$s."
505
+ msgstr ""
506
+
507
+ #. Plugin URI of the plugin/theme
508
+ msgid ""
509
+ "https://docs.woocommerce.com/document/woocommerce-gateway-paypal-powered-by-"
510
+ "braintree/"
511
+ msgstr ""
512
+
513
+ #. Description of the plugin/theme
514
+ msgid ""
515
+ "Receive credit card or PayPal payments using Paypal Powered by Braintree. "
516
+ "A server with cURL, SSL support, and a valid SSL certificate is required "
517
+ "(for security reasons) for this gateway to function. Requires PHP 5.4+"
518
+ msgstr ""
519
+
520
+ #. Author of the plugin/theme
521
+ msgid "WooCommerce"
522
+ msgstr ""
523
+
524
+ #. Author URI of the plugin/theme
525
+ msgid "http://woocommerce.com/"
526
+ msgstr ""
527
+
528
+ #: includes/class-wc-braintree-frontend.php:66
529
+ msgctxt "Payment Method Type"
530
+ msgid "Type"
531
+ msgstr ""
includes/api/class-wc-braintree-api-response-message-helper.php ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Response-Message-Helper
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Response Message Helper
31
+ *
32
+ * Builds customer-friendly response messages by mapping the various Braintree
33
+ * error codes to standardized messages
34
+ *
35
+ * @link https://developers.braintreepayments.com/reference/general/processor-responses/authorization-responses
36
+ * @link https://developers.braintreepayments.com/reference/general/validation-errors/all/php
37
+ *
38
+ * @since 3.0.0
39
+ * @see SV_WC_Payment_Gateway_API_Response_Message_Helper
40
+ */
41
+ class WC_Braintree_API_Response_Message_Helper extends WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Response_Message_Helper {
42
+
43
+
44
+ /** @var \WC_Braintree_API_Response response */
45
+ protected $response;
46
+
47
+ /** @var array decline codes */
48
+ protected $decline_codes = array(
49
+ 'cvv' => 'csc_mismatch',
50
+ 'avs' => 'avs_mismatch',
51
+ '2000' => 'card_declined',
52
+ '2001' => 'insufficient_funds',
53
+ '2002' => 'credit_limit_reached',
54
+ '2003' => 'card_declined',
55
+ '2004' => 'card_expired',
56
+ '2005' => 'card_number_invalid',
57
+ '2006' => 'card_expiry_invalid',
58
+ '2007' => 'card_type_invalid',
59
+ '2008' => 'card_number_invalid',
60
+ '2010' => 'csc_mismatch',
61
+ '2012' => 'card_declined',
62
+ '2013' => 'card_declined',
63
+ '2014' => 'card_declined',
64
+ '2016' => 'error',
65
+ '2017' => 'card_declined',
66
+ '2018' => 'card_declined',
67
+ '2023' => 'card_type_not_accepted',
68
+ '2024' => 'card_type_not_accepted',
69
+ '2038' => 'card_declined',
70
+ '2046' => 'card_declined',
71
+ '2056' => 'credit_limit_reached',
72
+ '2059' => 'avs_mismatch',
73
+ '2060' => 'avs_mismatch',
74
+ '2075' => 'paypal_closed',
75
+ );
76
+
77
+
78
+ /**
79
+ * Initialize the API response message handler
80
+ *
81
+ * @since 3.0.0
82
+ * @param \WC_Braintree_API_Response $response
83
+ */
84
+ public function __construct( $response ) {
85
+
86
+ $this->response = $response;
87
+ }
88
+
89
+
90
+ /**
91
+ * Get the user-facing error/decline message. Used in place of the get_user_message()
92
+ * method because this class is instantiated with the response class and handles
93
+ * generating the message ID internally
94
+ *
95
+ * @since 3.0.0
96
+ * @return string
97
+ */
98
+ public function get_message() {
99
+
100
+ // not handling specific validation error messages right now
101
+ if ( $this->get_response()->has_validation_errors() ) {
102
+ return $this->get_user_message( 'error' );
103
+ }
104
+
105
+ // note that $this->get_response()->response->message contains a Braintree-provided humanized error message, but it's generally
106
+ // not appropriate for display to customers so it's not used here
107
+
108
+ $response_code = $this->get_response()->get_failure_status_info( 'code' );
109
+
110
+ // If the order was authorized for later capture, then there is no decline message
111
+ if ( 'authorized' === $response_code ) {
112
+ return '';
113
+ }
114
+
115
+ $message_id = isset( $this->decline_codes[ $response_code ] ) ? $this->decline_codes[ $response_code ] : 'decline';
116
+
117
+ return $this->get_user_message( $message_id );
118
+ }
119
+
120
+
121
+ /**
122
+ * Returns a message appropriate for a frontend user. This should be used
123
+ * to provide enough information to a user to allow them to resolve an
124
+ * issue on their own, but not enough to help nefarious folks fishing for
125
+ * info. Adds a few custom authorize.net-specific user error messages.
126
+ *
127
+ * @since 2.0.0
128
+ * @see SV_WC_Payment_Gateway_API_Response_Message_Helper::get_user_message()
129
+ * @param string $message_id identifies the message to return
130
+ * @return string a user message
131
+ */
132
+ public function get_user_message( $message_id ) {
133
+
134
+ switch ( $message_id ) {
135
+
136
+ case 'paypal_closed':
137
+ $message = __( 'Sorry, we cannot process your transaction. The PayPal account is either locked or closed. Please use a different account or a different payment method.', 'woocommerce-gateway-paypal-powered-by-braintree' );
138
+ break;
139
+
140
+ default:
141
+ $message = parent::get_user_message( $message_id );
142
+ }
143
+
144
+ /**
145
+ * Braintree API Response User Message Filter.
146
+ *
147
+ * Allow actors to change the message displayed to customers as a result
148
+ * of a transaction error.
149
+ *
150
+ * @since 3.0.0
151
+ * @param string $message message displayed to customers
152
+ * @param string $message_id parsed message ID, e.g. 'decline'
153
+ * @param \WC_Braintree_API_Response_Message_Helper $this instance
154
+ */
155
+ return apply_filters( 'wc_braintree_api_response_user_message', $message, $message_id, $this );
156
+ }
157
+
158
+
159
+ /**
160
+ * Return the response object for this user message
161
+ *
162
+ * @since 3.0.0
163
+ * @return \WC_Braintree_API_Response
164
+ */
165
+ public function get_response() {
166
+
167
+ return $this->response;
168
+ }
169
+
170
+
171
+ }
includes/api/class-wc-braintree-api.php ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Class
31
+ *
32
+ * This is a pseudo-wrapper around the Braintree PHP SDK
33
+ *
34
+ * @link https://github.com/braintree/braintree_php
35
+ * @link https://developers.braintreepayments.com/javascript+php/reference/overview
36
+ *
37
+ * @since 3.0.0
38
+ */
39
+ class WC_Braintree_API extends WC_Braintree_Framework\SV_WC_API_Base implements WC_Braintree_Framework\SV_WC_Payment_Gateway_API {
40
+
41
+
42
+ /** Braintree Partner ID for transactions using Braintree Auth */
43
+ const BT_AUTH_CHANNEL = 'woothemes_bt';
44
+
45
+ /** Braintree Partner ID for transactions using API keys */
46
+ const API_CHANNEL = 'woocommerce_bt';
47
+
48
+
49
+ /** @var \WC_Gateway_Braintree class instance */
50
+ protected $gateway;
51
+
52
+ /** @var \WC_Order order associated with the request, if any */
53
+ protected $order;
54
+
55
+
56
+ /**
57
+ * Constructor - setup request object and set endpoint
58
+ *
59
+ * @since 3.0.0
60
+ * @param \WC_Gateway_Braintree $gateway class instance
61
+ */
62
+ public function __construct( $gateway ) {
63
+
64
+ $this->gateway = $gateway;
65
+
66
+ $this->init_sdk();
67
+ }
68
+
69
+
70
+ /**
71
+ * Load and configure the Braintree SDK
72
+ *
73
+ * @since 3.0.0
74
+ */
75
+ protected function init_sdk() {
76
+
77
+ // if SDK is already loaded, bail
78
+ if ( class_exists( 'Braintree\Configuration', false ) ) {
79
+ return;
80
+ }
81
+
82
+ // load Braintree PHP SDK
83
+ require_once( $this->get_gateway()->get_plugin()->get_plugin_path() . '/lib/Braintree.php' );
84
+ }
85
+
86
+
87
+ /** API Methods ***********************************************************/
88
+
89
+
90
+ /**
91
+ * Get a client token for initializing the hosted fields or PayPal forms
92
+ *
93
+ * @since 3.0.0
94
+ * @param array $args
95
+ * @return \WC_Braintree_API_Client_Token_Response
96
+ * @throws \SV_WC_Payment_Gateway_Exception
97
+ */
98
+ public function get_client_token( Array $args = array() ) {
99
+
100
+ $request = $this->get_new_request( array(
101
+ 'type' => 'client-token',
102
+ ) );
103
+
104
+ $request->get_token( $args );
105
+
106
+ return $this->perform_request( $request );
107
+ }
108
+
109
+
110
+ /**
111
+ * Create a new credit card charge transaction
112
+ *
113
+ * @since 3.0.0
114
+ * @see SV_WC_Payment_Gateway_API::credit_card_charge()
115
+ * @param \WC_Order $order order
116
+ * @return \WC_Braintree_API_Credit_Card_Transaction_Response|\WC_Braintree_API_PayPal_Transaction_Response
117
+ * @throws \SV_WC_Payment_Gateway_Exception
118
+ */
119
+ public function credit_card_charge( WC_Order $order ) {
120
+
121
+ // pre-verify CSC
122
+ if ( $this->get_gateway()->is_credit_card_gateway() && $this->get_gateway()->is_csc_required() ) {
123
+ $this->verify_csc( $order );
124
+ }
125
+
126
+ $request = $this->get_new_request( array(
127
+ 'type' => 'transaction',
128
+ 'order' => $order,
129
+ ) );
130
+
131
+ $request->create_credit_card_charge();
132
+
133
+ return $this->perform_request( $request );
134
+ }
135
+
136
+
137
+ /**
138
+ * Create a new credit card auth transaction
139
+ *
140
+ * @since 3.0.0
141
+ * @see SV_WC_Payment_Gateway_API::credit_card_authorization()
142
+ * @param \WC_Order $order order
143
+ * @return \WC_Braintree_API_Credit_Card_Transaction_Response|\WC_Braintree_API_PayPal_Transaction_Response
144
+ * @throws \SV_WC_Payment_Gateway_Exception
145
+ */
146
+ public function credit_card_authorization( WC_Order $order ) {
147
+
148
+ // pre-verify CSC
149
+ if ( $this->get_gateway()->is_credit_card_gateway() && $this->get_gateway()->is_csc_required() ) {
150
+ $this->verify_csc( $order );
151
+ }
152
+
153
+ $request = $this->get_new_request( array(
154
+ 'type' => 'transaction',
155
+ 'order' => $order,
156
+ ) );
157
+
158
+ $request->create_credit_card_auth();
159
+
160
+ return $this->perform_request( $request );
161
+ }
162
+
163
+
164
+ /**
165
+ * Verify the CSC for a transaction when using a saved payment toke and CSC
166
+ * is required. This must be done prior to processing the actual transaction.
167
+ *
168
+ * @since 3.0.0
169
+ * @param \WC_Order $ordero rder
170
+ * @throws \SV_WC_Payment_Gateway_Exception if CSC verification fails
171
+ */
172
+ public function verify_csc( WC_Order $order ) {
173
+
174
+ // don't verify the CSC for transactions that are already 3ds verified
175
+ if ( ! empty( $order->payment->use_3ds_nonce ) ) {
176
+ return;
177
+ }
178
+
179
+ if ( ! empty( $order->payment->nonce ) && ! empty( $order->payment->token ) ) {
180
+
181
+ $request = $this->get_new_request( array(
182
+ 'type' => 'payment-method',
183
+ 'order' => $order,
184
+ ) );
185
+
186
+ $request->verify_csc( $order->payment->token, $order->payment->nonce );
187
+
188
+ $result = $this->perform_request( $request );
189
+
190
+ if ( ! $result->transaction_approved() ) {
191
+
192
+ if ( $result->has_avs_rejection() ) {
193
+
194
+ $message = __( 'The billing address for this transaction does not match the cardholders.', 'woocommerce-gateway-paypal-powered-by-braintree' );
195
+
196
+ } elseif ( $result->has_cvv_rejection() ) {
197
+
198
+ $message = __( 'The CSC for the transaction was invalid or incorrect.', 'woocommerce-gateway-paypal-powered-by-braintree' );
199
+
200
+ } else {
201
+
202
+ $message = $result->get_user_message();
203
+ }
204
+
205
+ throw new SV_WC_Payment_Gateway_Exception( $message );
206
+ }
207
+ }
208
+ }
209
+
210
+
211
+ /**
212
+ * Capture funds for a credit card authorization
213
+ *
214
+ * @since 3.0.0
215
+ * @see SV_WC_Payment_Gateway_API::credit_card_capture()
216
+ * @param \WC_Order $order order
217
+ * @return \WC_Braintree_API_Transaction_Response
218
+ * @throws \SV_WC_Payment_Gateway_Exception
219
+ */
220
+ public function credit_card_capture( WC_Order $order ) {
221
+
222
+ $request = $this->get_new_request( array(
223
+ 'type' => 'transaction',
224
+ 'order' => $order,
225
+ ) );
226
+
227
+ $request->create_credit_card_capture();
228
+
229
+ return $this->perform_request( $request );
230
+ }
231
+
232
+
233
+ /**
234
+ * Check Debit - no-op
235
+ *
236
+ * @since 3.0.0
237
+ * @param \WC_Order $order order
238
+ * @return null
239
+ */
240
+ public function check_debit( WC_Order $order ) { }
241
+
242
+
243
+ /**
244
+ * Perform a refund for the order
245
+ *
246
+ * @since 3.0.0
247
+ * @param \WC_Order $order the order
248
+ * @return \WC_Braintree_API_Transaction_Response
249
+ * @throws \SV_WC_Payment_Gateway_Exception
250
+ */
251
+ public function refund( WC_Order $order ) {
252
+
253
+ $request = $this->get_new_request( array(
254
+ 'type' => 'transaction',
255
+ 'order' => $order,
256
+ ) );
257
+
258
+ $request->create_refund();
259
+
260
+ return $this->perform_request( $request );
261
+ }
262
+
263
+
264
+ /**
265
+ * Perform a void for the order
266
+ *
267
+ * @since 3.0.0
268
+ * @param \WC_Order $order the order
269
+ * @return \WC_Braintree_API_Transaction_Response
270
+ * @throws \SV_WC_Payment_Gateway_Exception
271
+ */
272
+ public function void( WC_Order $order ) {
273
+
274
+ $request = $this->get_new_request( array(
275
+ 'type' => 'transaction',
276
+ 'order' => $order,
277
+ ) );
278
+
279
+ $request->create_void();
280
+
281
+ return $this->perform_request( $request );
282
+ }
283
+
284
+
285
+ /** API Tokenization methods **********************************************/
286
+
287
+
288
+ /**
289
+ * Tokenize the payment method associated with the order
290
+ *
291
+ * @since 3.0.0
292
+ * @see SV_WC_Payment_Gateway_API::tokenize_payment_method()
293
+ * @param WC_Order $order the order with associated payment and customer info
294
+ * @return \WC_Braintree_API_Customer_Response|\WC_Braintree_API_Payment_Method_Response
295
+ */
296
+ public function tokenize_payment_method( WC_Order $order ) {
297
+
298
+ if ( $order->customer_id ) {
299
+
300
+ // create a payment method for existing customer
301
+ $request = $this->get_new_request( array(
302
+ 'type' => 'payment-method',
303
+ 'order' => $order,
304
+ ) );
305
+
306
+ $request->create_payment_method( $order );
307
+
308
+ } else {
309
+
310
+ // create both customer and payment method
311
+ $request = $this->get_new_request( array(
312
+ 'type' => 'customer',
313
+ 'order' => $order,
314
+ ) );
315
+
316
+ $request->create_customer( $order );
317
+ }
318
+
319
+ return $this->perform_request( $request );
320
+ }
321
+
322
+
323
+ /**
324
+ * Get the tokenized payment methods for the customer
325
+ *
326
+ * @since 3.0.0
327
+ * @see SV_WC_Payment_Gateway_API::get_tokenized_payment_methods()
328
+ * @param string $customer_id unique
329
+ * @return \WC_Braintree_API_Customer_response
330
+ * @throws \SV_WC_API_Exception
331
+ */
332
+ public function get_tokenized_payment_methods( $customer_id ) {
333
+
334
+ $request = $this->get_new_request( array( 'type' => 'customer' ) );
335
+
336
+ $request->get_payment_methods( $customer_id );
337
+
338
+ return $this->perform_request( $request );
339
+ }
340
+
341
+
342
+ /**
343
+ * Update the tokenized payment method for given customer
344
+ *
345
+ * @since 3.0.0
346
+ * @param WC_Order $order
347
+ */
348
+ public function update_tokenized_payment_method( WC_Order $order ) {
349
+
350
+ // update payment method
351
+ // https://developers.braintreepayments.com/javascript+php/reference/request/payment-method/update
352
+ }
353
+
354
+
355
+ /**
356
+ * Remove the given tokenized payment method for the customer
357
+ *
358
+ * @since 3.0.0
359
+ * @see SV_WC_Payment_Gateway_API::remove_tokenized_payment_method()
360
+ * @param string $token the payment method token
361
+ * @param string $customer_id unique
362
+ * @return \WC_Authorize_Net_CIM_API_Payment_Profile_Response
363
+ */
364
+ public function remove_tokenized_payment_method( $token, $customer_id ) {
365
+
366
+ $request = $this->get_new_request( array( 'type' => 'payment-method' ) );
367
+
368
+ $request->delete_payment_method( $token );
369
+
370
+ return $this->perform_request( $request );
371
+ }
372
+
373
+
374
+ /**
375
+ * Braintree supports retrieving tokenized payment methods
376
+ *
377
+ * @since 3.0.0
378
+ * @see SV_WC_Payment_Gateway_API::supports_get_tokenized_payment_methods()
379
+ * @return boolean true
380
+ */
381
+ public function supports_get_tokenized_payment_methods() {
382
+ return true;
383
+ }
384
+
385
+
386
+ /**
387
+ * Braintree supports removing tokenized payment methods
388
+ *
389
+ * @since 3.0.0
390
+ * @see SV_WC_Payment_Gateway_API::supports_remove_tokenized_payment_method()
391
+ * @return boolean true
392
+ */
393
+ public function supports_remove_tokenized_payment_method() {
394
+ return true;
395
+ }
396
+
397
+
398
+ /**
399
+ * Get payment method info from a client-side provided nonce, generally
400
+ * used for retrieving and verifying 3D secure information server-side
401
+ *
402
+ * @since 3.0.0
403
+ * @param string $nonce payment nonce
404
+ * @return \WC_Braintree_API_Payment_Method_Nonce_Response
405
+ * @throws \Exception
406
+ */
407
+ public function get_payment_method_from_nonce( $nonce ) {
408
+
409
+ $request = $this->get_new_request( array( 'type' => 'payment-method-nonce' ) );
410
+
411
+ $request->get_payment_method( $nonce );
412
+
413
+ return $this->perform_request( $request );
414
+ }
415
+
416
+ /**
417
+ * Get the payment nonce from a given payment token, generally used to
418
+ * provide a nonce for a previously vaulted payment method to the client-side
419
+ * 3D Secure verification script
420
+ *
421
+ * @since 3.0.0
422
+ * @param string $token payment method token ID
423
+ * @return \WC_Braintree_API_Payment_Method_Nonce_Response
424
+ * @throws \Exception
425
+ */
426
+ public function get_nonce_from_payment_token( $token ) {
427
+
428
+ $request = $this->get_new_request( array( 'type' => 'payment-method-nonce' ) );
429
+
430
+ $request->create_nonce( $token );
431
+
432
+ return $this->perform_request( $request );
433
+ }
434
+
435
+
436
+ /** Request/Response Methods **********************************************/
437
+
438
+
439
+ /**
440
+ * Perform a remote request using the Braintree SDK. Overriddes the standard
441
+ * wp_remote_request() as the SDK already provides a cURL implementation
442
+ *
443
+ * @since 3.0.0
444
+ * @see SV_WC_API_Base::do_remote_request()
445
+ * @param string $callback SDK static callback, e.g. `Braintree_ClientToken::generate`
446
+ * @param array $callback_params parameters to pass to the static callback
447
+ * @return \Exception|mixed
448
+ */
449
+ protected function do_remote_request( $callback, $callback_params ) {
450
+
451
+ // configure
452
+ if ( $this->is_braintree_auth() ) {
453
+
454
+ // configure with access token
455
+ $gateway_args = array(
456
+ 'accessToken' => $this->get_gateway()->get_auth_access_token(),
457
+ );
458
+
459
+ } else {
460
+
461
+ $gateway_args = array(
462
+ 'environment' => $this->get_gateway()->get_environment(),
463
+ 'merchantId' => $this->get_gateway()->get_merchant_id(),
464
+ 'publicKey' => $this->get_gateway()->get_public_key(),
465
+ 'privateKey' => $this->get_gateway()->get_private_key(),
466
+ );
467
+ }
468
+
469
+ $sdk_gateway = new Braintree\Gateway( $gateway_args );
470
+
471
+ $resource = $this->get_request()->get_resource();
472
+
473
+ try {
474
+
475
+ $response = call_user_func_array( array( $sdk_gateway->$resource(), $callback ), $callback_params );
476
+
477
+ } catch ( Exception $e ) {
478
+
479
+ $response = $e;
480
+ }
481
+
482
+ return $response;
483
+ }
484
+
485
+
486
+ /**
487
+ * Handle and parse the response
488
+ *
489
+ * @since 3.0.0
490
+ * @param mixed $response directly from Braintree SDK
491
+ * @return \WC_Braintree_API_Response
492
+ * @throws \SV_WC_API_Exception braintree errors
493
+ */
494
+ protected function handle_response( $response ) {
495
+
496
+ // check if Braintree response contains exception and convert to framework exception
497
+ if ( $response instanceof Exception ) {
498
+ throw new WC_Braintree_Framework\SV_WC_API_Exception( $this->get_braintree_exception_message( $response ), $response->getCode(), $response );
499
+ }
500
+
501
+ $handler_class = $this->get_response_handler();
502
+
503
+ // parse the response body and tie it to the request
504
+ $this->response = new $handler_class( $response, $this->get_gateway()->is_credit_card_gateway() ? 'credit-card' : 'paypal' );
505
+
506
+ // broadcast request
507
+ $this->broadcast_request();
508
+
509
+ return $this->response;
510
+ }
511
+
512
+
513
+
514
+ /**
515
+ * Get a human-friendly message from the Braintree exception object
516
+ *
517
+ * @link https://developers.braintreepayments.com/reference/general/exceptions/php
518
+ * @since 3.0.0
519
+ * @param \Exception $e
520
+ * @return string
521
+ */
522
+ protected function get_braintree_exception_message( $e ) {
523
+
524
+ switch ( get_class( $e ) ) {
525
+
526
+ case 'Braintree\Exception\Authentication':
527
+ $message = __( 'Invalid Credentials, please double-check your API credentials (Merchant ID, Public Key, Private Key, and Merchant Account ID) and try again.', 'woocommerce-gateway-paypal-powered-by-braintree' );
528
+ break;
529
+
530
+ case 'Braintree\Exception\Authorization':
531
+ $message = __( 'Authorization Failed, please verify the user for the API credentials provided can perform transactions and that the request data is correct.', 'woocommerce-gateway-paypal-powered-by-braintree' );
532
+ break;
533
+
534
+ case 'Braintree\Exception\DownForMaintenance':
535
+ $message = __( 'Braintree is currently down for maintenance, please try again later.', 'woocommerce-gateway-paypal-powered-by-braintree' );
536
+ break;
537
+
538
+ case 'Braintree\Exception\NotFound':
539
+ $message = __( 'The record cannot be found, please contact support.', 'woocommerce-gateway-paypal-powered-by-braintree' );
540
+ break;
541
+
542
+ case 'Braintree\Exception\ServerError':
543
+ $message = __( 'Braintree encountered an error when processing your request, please try again later or contact support.', 'woocommerce-gateway-paypal-powered-by-braintree' );
544
+ break;
545
+
546
+ case 'Braintree\Exception\SSLCertificate':
547
+ $message = __( 'Braintree cannot verify your server\'s SSL certificate. Please contact your hosting provider or try again later.', 'woocommerce-gateway-paypal-powered-by-braintree' );
548
+ break;
549
+
550
+ default:
551
+ $message = $e->getMessage();
552
+ }
553
+
554
+ return $message;
555
+ }
556
+
557
+
558
+ /**
559
+ * Override the standard request URI with the static callback instead, since
560
+ * the Braintree SDK handles the actual remote request
561
+ *
562
+ * @since 3.0.0
563
+ * @see SV_WC_API_Base::get_request_uri()
564
+ * @return string
565
+ */
566
+ protected function get_request_uri() {
567
+ return $this->get_request()->get_callback();
568
+ }
569
+
570
+
571
+ /**
572
+ * Override the standard request args with the static callback params instead,
573
+ * since the Braintree SDK handles the actual remote request
574
+ *
575
+ * @since 3.0.0
576
+ * @see SV_WC_API_Base::get_request_args()
577
+ * @return array
578
+ */
579
+ protected function get_request_args() {
580
+ return $this->get_request()->get_callback_params();
581
+ }
582
+
583
+
584
+ /**
585
+ * Alert other actors that a request has been performed, primarily for
586
+ * request/response logging.
587
+ *
588
+ * @see SV_WC_API_Base::broadcast_request()
589
+ * @since 3.0.0
590
+ */
591
+ protected function broadcast_request() {
592
+
593
+ $request_data = array(
594
+ 'environment' => $this->get_gateway()->get_environment(),
595
+ 'uri' => $this->get_request_uri(),
596
+ 'data' => $this->get_request()->to_string_safe(),
597
+ 'duration' => $this->get_request_duration() . 's', // seconds
598
+ );
599
+
600
+ $response_data = array(
601
+ 'data' => is_callable( array( $this->get_response(), 'to_string_safe' ) ) ? $this->get_response()->to_string_safe() : print_r( $this->get_response(), true ),
602
+ );
603
+
604
+ do_action( 'wc_' . $this->get_api_id() . '_api_request_performed', $request_data, $response_data, $this );
605
+ }
606
+
607
+
608
+ /**
609
+ * Builds and returns a new API request object
610
+ *
611
+ * @since 3.0.0
612
+ * @see SV_WC_API_Base::get_new_request()
613
+ * @param array $args
614
+ * @throws SV_WC_API_Exception for invalid request types
615
+ * @return \WC_Braintree_API_Client_Token_Request|\WC_Braintree_API_Transaction_Request|\WC_Braintree_API_Customer_Request|\WC_Braintree_API_Payment_Method_Request|\WC_Braintree_API_Payment_Method_Nonce_Request
616
+ */
617
+ protected function get_new_request( $args = array() ) {
618
+
619
+ $this->order = isset( $args['order'] ) && $args['order'] instanceof WC_Order ? $args['order'] : null;
620
+
621
+ switch ( $args['type'] ) {
622
+
623
+ case 'client-token':
624
+ $this->set_response_handler( 'WC_Braintree_API_Client_Token_Response' );
625
+ return new WC_Braintree_API_Client_Token_Request();
626
+ break;
627
+
628
+ case 'transaction':
629
+
630
+ $channel = ( $this->is_braintree_auth() ) ? self::BT_AUTH_CHANNEL : self::API_CHANNEL;
631
+
632
+ $this->set_response_handler( $this->get_gateway()->is_credit_card_gateway() ? 'WC_Braintree_API_Credit_Card_Transaction_Response' : 'WC_Braintree_API_PayPal_Transaction_Response' );
633
+ return new WC_Braintree_API_Transaction_Request( $this->order, $channel );
634
+
635
+ case 'customer':
636
+ $this->set_response_handler( 'WC_Braintree_API_Customer_Response' );
637
+ return new WC_Braintree_API_Customer_Request( $this->order );
638
+
639
+ case 'payment-method':
640
+ $this->set_response_handler( 'WC_Braintree_API_Payment_Method_Response' );
641
+ return new WC_Braintree_API_Payment_Method_Request( $this->order );
642
+
643
+ case 'payment-method-nonce':
644
+ $this->set_response_handler( 'WC_Braintree_API_Payment_Method_Nonce_Response' );
645
+ return new WC_Braintree_API_Payment_Method_Nonce_Request();
646
+
647
+ default:
648
+ throw new WC_Braintree_Framework\SV_WC_API_Exception( 'Invalid request type' );
649
+ }
650
+ }
651
+
652
+
653
+ /** Helper methods ********************************************************/
654
+
655
+
656
+ /**
657
+ * Determines if the gateway is configured with Braintree Auth or standard
658
+ * API keys.
659
+ *
660
+ * @since 2.0.0
661
+ *
662
+ * @return bool
663
+ */
664
+ protected function is_braintree_auth() {
665
+
666
+ return $this->get_gateway()->is_connected() && ! $this->get_gateway()->is_connected_manually();
667
+ }
668
+
669
+
670
+ /**
671
+ * Return the order associated with the request, if any
672
+ *
673
+ * @since 3.0.0
674
+ * @return \WC_Order
675
+ */
676
+ public function get_order() {
677
+
678
+ return $this->order;
679
+ }
680
+
681
+
682
+ /**
683
+ * Get the ID for the API, used primarily to namespace the action name
684
+ * for broadcasting requests
685
+ *
686
+ * @since 3.0.0
687
+ * @return string
688
+ */
689
+ protected function get_api_id() {
690
+
691
+ return $this->get_gateway()->get_id();
692
+ }
693
+
694
+
695
+ /**
696
+ * Return the gateway plugin
697
+ *
698
+ * @since 3.0.0
699
+ * @return \SV_WC_Payment_Gateway_Plugin
700
+ */
701
+ public function get_plugin() {
702
+
703
+ return $this->get_gateway()->get_plugin();
704
+ }
705
+
706
+
707
+ /**
708
+ * Returns the gateway class associated with the request
709
+ *
710
+ * @since 3.0.0
711
+ * @return \WC_Gateway_Braintree class instance
712
+ */
713
+ public function get_gateway() {
714
+
715
+ return $this->gateway;
716
+ }
717
+
718
+
719
+ }
includes/api/requests/abstract-wc-braintree-api-request.php ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Request
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Abstract Request Class
31
+ *
32
+ * Provides functionality common to all requests
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ abstract class WC_Braintree_API_Request implements WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Request {
37
+
38
+
39
+ /** @var string Braintree SDK resource for the request, e.g. `transaction` */
40
+ protected $resource;
41
+
42
+ /** @var string Braintree SDK callback for the request, e.g. `generate` */
43
+ protected $callback;
44
+
45
+ /** @var array request data passed to the static callback */
46
+ protected $request_data = array();
47
+
48
+ /** @var \WC_Order order associated with the request, if any */
49
+ protected $order;
50
+
51
+
52
+ /**
53
+ * Setup request
54
+ *
55
+ * @since 3.0.0
56
+ * @param \WC_Order|null $order order if available
57
+ */
58
+ public function __construct( $order = null ) {
59
+
60
+ $this->order = $order;
61
+ }
62
+
63
+
64
+ /**
65
+ * Sets the Braintree SDK resource for the request.
66
+ *
67
+ * @since 2.0.0
68
+ * @param string $resource, e.g. `transaction`
69
+ */
70
+ protected function set_resource( $resource ) {
71
+
72
+ $this->resource = $resource;
73
+ }
74
+
75
+
76
+ /**
77
+ * Gets the Braintree SDK resource for the request.
78
+ *
79
+ * @since 2.0.0
80
+ * @return string
81
+ */
82
+ public function get_resource() {
83
+
84
+ return $this->resource;
85
+ }
86
+
87
+
88
+ /**
89
+ * Set the static callback for the request
90
+ *
91
+ * @since 3.0.0
92
+ * @param string $callback, e.g. `Braintree_ClientToken::generate`
93
+ */
94
+ protected function set_callback( $callback ) {
95
+
96
+ $this->callback = $callback;
97
+ }
98
+
99
+
100
+ /**
101
+ * Get the static callback for the request
102
+ *
103
+ * @since 3.0.0
104
+ * @return string static callback
105
+ */
106
+ public function get_callback() {
107
+
108
+ return $this->callback;
109
+ }
110
+
111
+
112
+ /**
113
+ * Get the callback parameters for the request
114
+ *
115
+ * @since 3.0.0
116
+ * @return array
117
+ */
118
+ public function get_callback_params() {
119
+
120
+ switch ( $this->get_callback() ) {
121
+
122
+ // these API calls use 2 callback parameters
123
+ case 'submitForSettlement':
124
+ case 'refund':
125
+ case 'update':
126
+ return $this->get_request_data();
127
+
128
+ // all others use a single callback param
129
+ default:
130
+ return array( $this->get_request_data() );
131
+ }
132
+ }
133
+
134
+
135
+ /**
136
+ * Return the string representation of the request
137
+ *
138
+ * @since 3.0.0
139
+ * @return string
140
+ */
141
+ public function to_string() {
142
+
143
+ return print_r( $this->get_request_data(), true );
144
+ }
145
+
146
+
147
+ /**
148
+ * Return the string representation of the request, stripped of any
149
+ * confidential information
150
+ *
151
+ * @since 3.0.0
152
+ * @return string
153
+ */
154
+ public function to_string_safe() {
155
+
156
+ // no confidential info to mask...yet
157
+ return $this->to_string();
158
+ }
159
+
160
+
161
+ /**
162
+ * Get the request data which is the 1st parameter passed to the static callback
163
+ * set
164
+ *
165
+ * @since 3.0.0
166
+ * @return array
167
+ */
168
+ public function get_request_data() {
169
+
170
+ /**
171
+ * Braintree API Request Data.
172
+ *
173
+ * Allow actors to modify the request data before it's sent to Braintree
174
+ *
175
+ * @since 3.0.0
176
+ * @param array|mixed $data request data to be filtered
177
+ * @param \WC_Order $order order instance
178
+ * @param \WC_Braintree_API_Request $this, API request class instance
179
+ */
180
+ $this->request_data = apply_filters( 'wc_braintree_api_request_data', $this->request_data, $this );
181
+
182
+ $this->remove_empty_data();
183
+
184
+ return $this->request_data;
185
+ }
186
+
187
+
188
+ /**
189
+ * Remove null or blank string values from the request data (up to 2 levels deep)
190
+ *
191
+ * @TODO: this can be improved to traverse deeper and be simpler @MR 2015-10-23
192
+ *
193
+ * @since 3.0.0
194
+ */
195
+ protected function remove_empty_data() {
196
+
197
+ foreach ( (array) $this->request_data as $key => $value ) {
198
+
199
+ if ( is_array( $value ) ) {
200
+
201
+ if ( empty( $value ) ) {
202
+
203
+ unset( $this->request_data[ $key ] );
204
+
205
+ } else {
206
+
207
+ foreach ( $value as $inner_key => $inner_value ) {
208
+
209
+ if ( is_null( $inner_value ) || '' === $inner_value ) {
210
+ unset( $this->request_data[ $key ][ $inner_key ] );
211
+ }
212
+ }
213
+ }
214
+
215
+ } else {
216
+
217
+ if ( is_null( $value ) || '' === $value ) {
218
+ unset( $this->request_data[ $key ] );
219
+ }
220
+ }
221
+ }
222
+ }
223
+
224
+
225
+ /**
226
+ * Gets a property from the associated order.
227
+ *
228
+ * @since 2.0.0
229
+ * @param string $prop the desired order property
230
+ * @return mixed
231
+ */
232
+ public function get_order_prop( $prop ) {
233
+
234
+ return WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $this->get_order(), $prop );
235
+ }
236
+
237
+
238
+ /**
239
+ * Get the order associated with the request, if any
240
+ *
241
+ * @since 3.0.0
242
+ * @return \WC_Order|null
243
+ */
244
+ public function get_order() {
245
+
246
+ return $this->order;
247
+ }
248
+
249
+
250
+ /**
251
+ * Braintree requests do not require a method per request
252
+ *
253
+ * @since 3.0.0
254
+ * @return null
255
+ */
256
+ public function get_method() { }
257
+
258
+
259
+ /**
260
+ * Braintree requests do not require a path per request
261
+ *
262
+ * @since 3.0.0
263
+ * @return null
264
+ */
265
+ public function get_path() { }
266
+
267
+
268
+ }
includes/api/requests/abstract-wc-braintree-api-vault-request.php ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Vault
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree API Abstract Vault Request class
29
+ *
30
+ * Handles common methods for vault requests - Customers/Payment Methods
31
+ *
32
+ * @since 3.0.0
33
+ */
34
+ abstract class WC_Braintree_API_Vault_Request extends WC_Braintree_API_Request {
35
+
36
+
37
+ /**
38
+ * Return the billing address in the format required by Braintree
39
+ *
40
+ * @link https://developers.braintreepayments.com/reference/request/payment-method/create/php#billing_address
41
+ * @link https://developers.braintreepayments.com/reference/request/customer/create/php#credit_card.billing_address
42
+ *
43
+ * @since 3.0.0
44
+ * @return array
45
+ */
46
+ protected function get_billing_address() {
47
+
48
+ return array(
49
+ 'firstName' => $this->get_order_prop( 'billing_first_name' ),
50
+ 'lastName' => $this->get_order_prop( 'billing_last_name' ),
51
+ 'company' => $this->get_order_prop( 'billing_company' ),
52
+ 'streetAddress' => $this->get_order_prop( 'billing_address_1' ),
53
+ 'extendedAddress' => $this->get_order_prop( 'billing_address_2' ),
54
+ 'locality' => $this->get_order_prop( 'billing_city' ),
55
+ 'region' => $this->get_order_prop( 'billing_state' ),
56
+ 'postalCode' => $this->get_order_prop( 'billing_postcode' ),
57
+ 'countryCodeAlpha2' => $this->get_order_prop( 'billing_country' ),
58
+ );
59
+ }
60
+
61
+
62
+ /**
63
+ * Return the options used for creating a payment method, mostly for
64
+ * credit cards. This verifies the card by running CVV/AVS checks and prevents
65
+ * duplicate payment methods from being added.
66
+ *
67
+ * @since 3.0.0
68
+ * @return array
69
+ */
70
+ protected function get_credit_card_options() {
71
+
72
+ $options = array(
73
+ 'failOnDuplicatePaymentMethod' => true,
74
+ 'verifyCard' => true,
75
+ );
76
+
77
+ if ( ! empty( $this->get_order()->payment->merchant_account_id ) ) {
78
+ $options['verificationMerchantAccountId'] = $this->get_order()->payment->merchant_account_id;
79
+ }
80
+
81
+ return $options;
82
+ }
83
+
84
+
85
+ /**
86
+ * Add device data for advanced fraud handling, if it's present
87
+ *
88
+ * @since 3.0.0
89
+ */
90
+ protected function add_device_data() {
91
+
92
+ if ( $device_data = $this->get_order()->payment->device_data ) {
93
+
94
+ $this->request_data['deviceData'] = $device_data;
95
+ }
96
+ }
97
+
98
+
99
+ }
includes/api/requests/class-wc-braintree-api-client-token-request.php ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Client-Token
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree API Client Token Request class
29
+ *
30
+ * Handles building the request for a client token
31
+ *
32
+ * @since 3.0.0
33
+ */
34
+ class WC_Braintree_API_Client_Token_Request extends WC_Braintree_API_Request {
35
+
36
+
37
+ /**
38
+ * Get the client token
39
+ *
40
+ * @see https://developers.braintreepayments.com/javascript+php/reference/request/client-token/generate
41
+ *
42
+ * @since 3.0.0
43
+ * @param array $args token args
44
+ */
45
+ public function get_token( array $args ) {
46
+
47
+ $this->set_resource( 'clientToken' );
48
+ $this->set_callback( 'generate' );
49
+
50
+ $this->request_data = array( 'merchantAccountId' => $args['merchantAccountId'] );
51
+ }
52
+
53
+
54
+ }
includes/api/requests/class-wc-braintree-api-customer-request.php ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Customer
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Customer Request class
31
+ *
32
+ * Handles creating customers and retrieving their payment methods
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ class WC_Braintree_API_Customer_Request extends WC_Braintree_API_Vault_Request {
37
+
38
+
39
+ /**
40
+ * Create a new customer and associated payment method
41
+ *
42
+ * @link https://developers.braintreepayments.com/reference/request/customer/create/php
43
+ *
44
+ * @since 3.0.0
45
+ * @param \WC_Order $order
46
+ */
47
+ public function create_customer( WC_Order $order ) {
48
+
49
+ $this->order = $order;
50
+
51
+ $this->set_resource( 'customer' );
52
+ $this->set_callback( 'create' );
53
+
54
+ $this->request_data = array(
55
+ 'company' => WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $order, 'billing_company' ),
56
+ 'email' => WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $order, 'billing_email' ),
57
+ 'phone' => WC_Braintree_Framework\SV_WC_Helper::str_truncate( preg_replace( '/[^\d-().]/', '', WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $order, 'billing_phone' ) ), 14, '' ),
58
+ 'firstName' => WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $order, 'billing_first_name' ),
59
+ 'lastName' => WC_Braintree_Framework\SV_WC_Order_Compatibility::get_prop( $order, 'billing_last_name' ),
60
+ 'paymentMethodNonce' => $order->payment->nonce,
61
+ );
62
+
63
+ // add verification data for credit cards
64
+ if ( 'credit_card' === $order->payment->type ) {
65
+ $this->request_data['creditCard'] = array(
66
+ 'billingAddress' => $this->get_billing_address(),
67
+ 'cardholderName' => $order->get_formatted_billing_full_name(),
68
+ 'options' => $this->get_credit_card_options(),
69
+ );
70
+ }
71
+
72
+ // fraud data
73
+ $this->add_device_data();
74
+ }
75
+
76
+
77
+ /**
78
+ * Get the payment methods for a given customer
79
+ *
80
+ * @link https://developers.braintreepayments.com/reference/request/customer/find/php
81
+ *
82
+ * @since 3.0.0
83
+ * @param string $customer_id Braintree customer ID
84
+ */
85
+ public function get_payment_methods( $customer_id ) {
86
+
87
+ $this->set_resource( 'customer' );
88
+ $this->set_callback( 'find' );
89
+
90
+ $this->request_data = $customer_id;
91
+ }
92
+
93
+
94
+ }
includes/api/requests/class-wc-braintree-api-payment-method-nonce-request.php ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Payment-Nonce
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree API Payment Method Nonce Request class
29
+ *
30
+ * Handles creating and getting payment method nonces, generally for use with 3D Secure
31
+ * transactions
32
+ *
33
+ * @since 3.0.0
34
+ */
35
+ class WC_Braintree_API_Payment_Method_Nonce_Request extends WC_Braintree_API_Request {
36
+
37
+
38
+ /**
39
+ * Get the payment method associated with a nonce. This is used to retrieve
40
+ * 3D Secure information about a nonce server-side before processing the transaction.
41
+ *
42
+ * @link https://developers.braintreepayments.com/reference/request/payment-method-nonce/create/php
43
+ *
44
+ * @since 3.0.0
45
+ * @param string $nonce nonce from 3D secure verification
46
+ */
47
+ public function get_payment_method( $nonce ) {
48
+
49
+ $this->set_resource( 'paymentMethodNonce' );
50
+ $this->set_callback( 'find' );
51
+
52
+ $this->request_data = $nonce;
53
+ }
54
+
55
+
56
+ /**
57
+ * Create a nonce given an existing vaulted payment token. This is used to
58
+ * provide a nonce to the 3D Secure verification method client-side.
59
+ *
60
+ * @link https://developers.braintreepayments.com/reference/request/payment-method-nonce/find/php
61
+ *
62
+ * @since 3.0.0
63
+ * @param string $token vault token ID
64
+ */
65
+ public function create_nonce( $token ) {
66
+
67
+ $this->set_resource( 'paymentMethodNonce' );
68
+ $this->set_callback( 'create' );
69
+
70
+ $this->request_data = $token;
71
+ }
72
+
73
+
74
+ }
includes/api/requests/class-wc-braintree-api-payment-method-request.php ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Payment-Method
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree API Payment Method Request class
29
+ *
30
+ * Handles creating, updating, and deleting individual payment methods
31
+ *
32
+ * @since 3.0.0
33
+ */
34
+ class WC_Braintree_API_Payment_Method_Request extends WC_Braintree_API_Vault_Request {
35
+
36
+
37
+ /**
38
+ * Create a new payment method for an existing customer
39
+ *
40
+ * @link https://developers.braintreepayments.com/reference/request/payment-method/create/php
41
+ *
42
+ * @since 3.0.0
43
+ * @param \WC_Order $order
44
+ */
45
+ public function create_payment_method( WC_Order $order ) {
46
+
47
+ $this->order = $order;
48
+
49
+ $this->set_resource( 'paymentMethod' );
50
+ $this->set_callback( 'create' );
51
+
52
+ $this->request_data = array(
53
+ 'customerId' => $order->customer_id,
54
+ 'paymentMethodNonce' => $order->payment->nonce,
55
+ );
56
+
57
+ // add verification data for credit cards
58
+ if ( 'credit_card' === $order->payment->type ) {
59
+ $this->request_data['billingAddress'] = $this->get_billing_address();
60
+ $this->request_data['cardholderName'] = $order->get_formatted_billing_full_name();
61
+ $this->request_data['options'] = $this->get_credit_card_options();
62
+ }
63
+
64
+ // fraud data
65
+ $this->add_device_data();
66
+ }
67
+
68
+
69
+ /**
70
+ * Delete a customer's payment method
71
+ *
72
+ * @link https://developers.braintreepayments.com/reference/request/payment-method/delete/php
73
+ *
74
+ * @since 3.0.0
75
+ * @param string $token Braintree payment method token
76
+ */
77
+ public function delete_payment_method( $token ) {
78
+
79
+ $this->set_resource( 'paymentMethod' );
80
+ $this->set_callback( 'delete' );
81
+
82
+ $this->request_data = $token;
83
+ }
84
+
85
+
86
+ /**
87
+ * Verify the CSC for an existing saved payment method using the provided
88
+ * nonce
89
+ *
90
+ * @since 3.0.0
91
+ * @param string $token existing payment method token
92
+ * @param string $nonce nonce provided from client-side hosted fields
93
+ */
94
+ public function verify_csc( $token, $nonce ) {
95
+
96
+ $this->set_resource( 'paymentMethod' );
97
+ $this->set_callback( 'update' );
98
+
99
+ $update_data = array(
100
+ 'paymentMethodNonce' => $nonce,
101
+ 'billingAddress' => $this->get_billing_address(),
102
+ 'options' => array(
103
+ 'verifyCard' => true,
104
+ ),
105
+ );
106
+
107
+ $this->request_data = array( $token, $update_data );
108
+ }
109
+
110
+
111
+ }
includes/api/requests/class-wc-braintree-api-transaction-request.php ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Requests/Transaction
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Transaction Request Class
31
+ *
32
+ * Handles transaction requests (charges, auths, captures, refunds, voids)
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ class WC_Braintree_API_Transaction_Request extends WC_Braintree_API_Request {
37
+
38
+
39
+ /** auth and capture transaction type */
40
+ const AUTHORIZE_AND_CAPTURE = true;
41
+
42
+ /** authorize-only transaction type */
43
+ const AUTHORIZE_ONLY = false;
44
+
45
+ /** @var string Braintree partner ID */
46
+ protected $channel;
47
+
48
+
49
+ /**
50
+ * Constructs the class.
51
+ *
52
+ * @since 2.0.0
53
+ * @param \WC_Order|null $order order if available
54
+ * @param string $channel Braintree Partner ID/channel
55
+ */
56
+ public function __construct( $order = null, $channel = '' ) {
57
+
58
+ parent::__construct( $order );
59
+
60
+ $this->channel = $channel;
61
+ }
62
+
63
+
64
+ /**
65
+ * Creates a credit card charge request for the payment method / customer
66
+ *
67
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php
68
+ *
69
+ * @since 3.0.0
70
+ */
71
+ public function create_credit_card_charge() {
72
+
73
+ $this->create_transaction( self::AUTHORIZE_AND_CAPTURE );
74
+ }
75
+
76
+
77
+ /**
78
+ * Creates a credit card auth request for the payment method / customer
79
+ *
80
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php
81
+ *
82
+ * @since 3.0.0
83
+ */
84
+ public function create_credit_card_auth() {
85
+
86
+ $this->create_transaction( self::AUTHORIZE_ONLY );
87
+ }
88
+
89
+
90
+ /**
91
+ * Capture funds for a previous credit card authorization
92
+ *
93
+ * @link https://developers.braintreepayments.com/reference/request/transaction/submit-for-settlement/php
94
+ *
95
+ * @since 3.0.0
96
+ */
97
+ public function create_credit_card_capture() {
98
+
99
+ $this->set_resource( 'transaction' );
100
+ $this->set_callback( 'submitForSettlement' );
101
+
102
+ $this->request_data = array( $this->get_order()->capture->trans_id, $this->get_order()->capture->amount );
103
+ }
104
+
105
+
106
+ /**
107
+ * Refund funds from a previous transaction
108
+ *
109
+ * @link https://developers.braintreepayments.com/reference/request/transaction/refund/php
110
+ *
111
+ * @since 3.0.0
112
+ */
113
+ public function create_refund() {
114
+
115
+ $this->set_resource( 'transaction' );
116
+ $this->set_callback( 'refund' );
117
+
118
+ $this->request_data = array( $this->get_order()->refund->trans_id, $this->get_order()->refund->amount );
119
+ }
120
+
121
+
122
+ /**
123
+ * Void a previous transaction
124
+ *
125
+ * @link https://developers.braintreepayments.com/reference/request/transaction/void/php
126
+ *
127
+ * @since 3.0.0
128
+ */
129
+ public function create_void() {
130
+
131
+ $this->set_resource( 'transaction' );
132
+ $this->set_callback( 'void' );
133
+
134
+ $this->request_data = $this->get_order()->refund->trans_id;
135
+ }
136
+
137
+
138
+ /**
139
+ * Create a sale transaction with the given settlement type
140
+ *
141
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php
142
+ *
143
+ * @since 3.0.0
144
+ * @param bool $settlement_type true = auth/capture, false = auth-only
145
+ */
146
+ protected function create_transaction( $settlement_type ) {
147
+
148
+ $this->set_resource( 'transaction' );
149
+ $this->set_callback( 'sale' );
150
+
151
+ $this->request_data = array(
152
+ 'amount' => $this->get_order()->payment_total,
153
+ 'orderId' => $this->get_order()->get_order_number(),
154
+ 'merchantAccountId' => empty( $this->get_order()->payment->merchant_account_id ) ? null : $this->get_order()->payment->merchant_account_id,
155
+ 'shipping' => $this->get_shipping_address(),
156
+ 'options' => $this->get_options( $settlement_type ),
157
+ 'channel' => $this->get_channel(),
158
+ 'deviceData' => empty( $this->get_order()->payment->device_data ) ? null : $this->get_order()->payment->device_data,
159
+ 'taxAmount' => WC_Braintree_Framework\SV_WC_Helper::number_format( $this->get_order()->get_total_tax() ),
160
+ 'taxExempt' => $this->get_order()->get_user_id() > 0 && is_callable( array( WC()->customer, 'is_vat_exempt' ) ) ? WC()->customer->is_vat_exempt() : false,
161
+ );
162
+
163
+ // set customer data
164
+ $this->set_customer();
165
+
166
+ // set billing data
167
+ $this->set_billing();
168
+
169
+ // set payment method, either existing token or nonce
170
+ $this->set_payment_method();
171
+
172
+ // add dynamic descriptors
173
+ $this->set_dynamic_descriptors();
174
+
175
+ /**
176
+ * Filters the request data for new transactions.
177
+ *
178
+ * @since 2.0.0
179
+ * @param array $data The transaction/sale data
180
+ * @param \WC_Braintree_API_Transaction_Request $request the request object
181
+ */
182
+ $this->request_data = apply_filters( 'wc_braintree_transaction_data', $this->request_data, $this );
183
+ }
184
+
185
+
186
+ /**
187
+ * Set the customer data for the transaction
188
+ *
189
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#customer
190
+ *
191
+ * @since 3.0.0
192
+ */
193
+ protected function set_customer() {
194
+
195
+ if ( $this->get_order()->customer_id ) {
196
+
197
+ // use existing customer ID
198
+ $this->request_data['customerId'] = $this->get_order()->customer_id;
199
+
200
+ } else {
201
+
202
+ // set customer info
203
+ // a customer will only be created if tokenization is required and
204
+ // storeInVaultOnSuccess is set to true, see get_options() below
205
+ $this->request_data['customer'] = array(
206
+ 'firstName' => $this->get_order_prop( 'billing_first_name' ),
207
+ 'lastName' => $this->get_order_prop( 'billing_last_name' ),
208
+ 'company' => $this->get_order_prop( 'billing_company' ),
209
+ 'phone' => WC_Braintree_Framework\SV_WC_Helper::str_truncate( preg_replace( '/[^\d-().]/', '', $this->get_order_prop( 'billing_phone' ) ), 14, '' ),
210
+ 'email' => $this->get_order_prop( 'billing_email' ),
211
+ );
212
+ }
213
+ }
214
+
215
+
216
+ /**
217
+ * Get the billing address for the transaction
218
+ *
219
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#billing
220
+ *
221
+ * @since 3.0.0
222
+ * @return array
223
+ */
224
+ protected function set_billing() {
225
+
226
+ if ( ! empty( $this->get_order()->payment->billing_address_id ) ) {
227
+
228
+ // use the existing billing address when using a saved payment method
229
+ $this->request_data['billingAddressId'] = $this->get_order()->payment->billing_address_id;
230
+
231
+ } else {
232
+
233
+ // otherwise just set the billing address directly
234
+ $this->request_data['billing'] = array(
235
+ 'firstName' => $this->get_order_prop( 'billing_first_name' ),
236
+ 'lastName' => $this->get_order_prop( 'billing_last_name' ),
237
+ 'company' => $this->get_order_prop( 'billing_company' ),
238
+ 'streetAddress' => $this->get_order_prop( 'billing_address_1' ),
239
+ 'extendedAddress' => $this->get_order_prop( 'billing_address_2' ),
240
+ 'locality' => $this->get_order_prop( 'billing_city' ),
241
+ 'region' => $this->get_order_prop( 'billing_state' ),
242
+ 'postalCode' => $this->get_order_prop( 'billing_postcode' ),
243
+ 'countryCodeAlpha2' => $this->get_order_prop( 'billing_country' ),
244
+ );
245
+ }
246
+ }
247
+
248
+
249
+ /**
250
+ * Get the shipping address for the transaction
251
+ *
252
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#shipping
253
+ *
254
+ * @since 3.0.0
255
+ * @return array
256
+ */
257
+ protected function get_shipping_address() {
258
+
259
+ return array(
260
+ 'firstName' => $this->get_order_prop( 'shipping_first_name' ),
261
+ 'lastName' => $this->get_order_prop( 'shipping_last_name' ),
262
+ 'company' => $this->get_order_prop( 'shipping_company' ),
263
+ 'streetAddress' => $this->get_order_prop( 'shipping_address_1' ),
264
+ 'extendedAddress' => $this->get_order_prop( 'shipping_address_2' ),
265
+ 'locality' => $this->get_order_prop( 'shipping_city' ),
266
+ 'region' => $this->get_order_prop( 'shipping_state' ),
267
+ 'postalCode' => $this->get_order_prop( 'shipping_postcode' ),
268
+ 'countryCodeAlpha2' => $this->get_order_prop( 'shipping_country' ),
269
+ );
270
+ }
271
+
272
+
273
+ /**
274
+ * Set the payment method for the transaction, either a previously saved payment
275
+ * method (token) or a new payment method (nonce)
276
+ *
277
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#payment_method_nonce
278
+ *
279
+ * @since 3.0.0
280
+ */
281
+ protected function set_payment_method() {
282
+
283
+ if ( ! empty( $this->get_order()->payment->token ) && empty( $this->get_order()->payment->use_3ds_nonce ) ) {
284
+
285
+ // use saved payment method (token)
286
+ $this->request_data['paymentMethodToken'] = $this->get_order()->payment->token;
287
+
288
+ } else {
289
+
290
+ // use new payment method (nonce)
291
+ $this->request_data['paymentMethodNonce'] = $this->get_order()->payment->nonce;
292
+
293
+ // set cardholder name when adding a credit card, note this isn't possible
294
+ // when using a 3DS nonce
295
+ if ( 'credit_card' === $this->get_order()->payment->type && empty( $this->get_order()->payment->use_3ds_nonce ) ) {
296
+ $this->request_data['creditCard'] = array( 'cardholderName' => $this->get_order()->get_formatted_billing_full_name() );
297
+ }
298
+ }
299
+
300
+ // add recurring flag to PayPal transactions that are subscription renewals
301
+ if ( ! empty( $this->get_order()->payment->recurring ) ) {
302
+ $this->request_data['recurring'] = true;
303
+ }
304
+ }
305
+
306
+
307
+ /**
308
+ * Set the dynamic descriptors for the transaction, these are set by the
309
+ * admin in the gateway settings
310
+ *
311
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#descriptor
312
+ *
313
+ * @since 3.0.0
314
+ */
315
+ protected function set_dynamic_descriptors() {
316
+
317
+ // dynamic descriptors
318
+ if ( ! empty( $this->get_order()->payment->dynamic_descriptors ) ) {
319
+
320
+ $this->request_data['descriptor'] = array();
321
+
322
+ foreach ( array( 'name', 'phone', 'url' ) as $key ) {
323
+
324
+ if ( ! empty( $this->get_order()->payment->dynamic_descriptors->$key ) ) {
325
+ $this->request_data['descriptor'][ $key ] = $this->get_order()->payment->dynamic_descriptors->$key;
326
+ }
327
+ }
328
+ }
329
+ }
330
+
331
+
332
+ /**
333
+ * Get the options for the transaction
334
+ *
335
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#options
336
+ *
337
+ * @since 3.0.0
338
+ * @param bool $settlement_type, authorize or auth/capture
339
+ * @return array
340
+ */
341
+ protected function get_options( $settlement_type ) {
342
+
343
+ $options = array(
344
+ 'submitForSettlement' => $settlement_type,
345
+ 'storeInVaultOnSuccess' => $this->get_order()->payment->tokenize,
346
+ );
347
+
348
+ if ( ! empty( $this->get_order()->payment->is_3ds_required ) ) {
349
+ $options['three_d_secure'] = array( 'required' => true );
350
+ }
351
+
352
+ return $options;
353
+ }
354
+
355
+
356
+ /**
357
+ * Gets the channel ID for the transaction.
358
+ *
359
+ * @link https://developers.braintreepayments.com/reference/request/transaction/sale/php#channel
360
+ *
361
+ * @since 3.0.0
362
+ */
363
+ protected function get_channel() {
364
+
365
+ return $this->channel;
366
+ }
367
+
368
+
369
+ }
includes/api/responses/abstract-wc-braintree-api-response.php ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Response
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Abstract Response Class
31
+ *
32
+ * Provides functionality common to all responses
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ abstract class WC_Braintree_API_Response implements WC_Braintree_Framework\SV_WC_API_Response {
37
+
38
+
39
+ /** @var mixed raw response from the Braintree SDK */
40
+ protected $response;
41
+
42
+
43
+ /**
44
+ * Setup the response
45
+ *
46
+ * @since 3.0.0
47
+ * @param mixed $response response data from Braintree SDK
48
+ * @param string $response_type indicates whether the response is from a credit card or PayPal request
49
+ */
50
+ public function __construct( $response, $response_type ) {
51
+
52
+ $this->response = $response;
53
+ $this->response_type = $response_type;
54
+ }
55
+
56
+
57
+ /**
58
+ * Checks if the transaction was successful. Braintree's "success" attribute
59
+ * indicates _both_ that the request was successful *and* the transaction
60
+ * (if the request was a transaction) was successful. If a request/transaction
61
+ * isn't successful, it's due to one or more of the following 4 things:
62
+ *
63
+ * 1) Validation failure - invalid request data or the request itself was invalid
64
+ * 2) Gateway Rejection - the gateway rejected the transaction (duplicate check, AVS, CVV, fraud, 3dsecure)
65
+ * 3) Processor Declined - the merchant processor declined the transaction (soft/hard decline, depends on error code)
66
+ * 4) Exception - invalid API credentials, Braintree's servers are down or undergoing maintenance
67
+ *
68
+ * Note that exceptions are handled prior to response "parsing" so there's no
69
+ * handling for them here.
70
+ *
71
+ * @since 3.0.0
72
+ * @see SV_WC_Payment_Gateway_API_Response::transaction_approved()
73
+ * @return bool true if approved, false otherwise
74
+ */
75
+ public function transaction_approved() {
76
+
77
+ return $this->response->success;
78
+ }
79
+
80
+
81
+ /**
82
+ * Braintree does not support the concept of held requests/transactions, so this
83
+ * doesn not apply
84
+ *
85
+ * @since 3.0.0
86
+ * @return bool
87
+ */
88
+ public function transaction_held() {
89
+ return false;
90
+ }
91
+
92
+
93
+ /**
94
+ * Gets the transaction status code
95
+ *
96
+ * @since 3.0.0
97
+ * @see SV_WC_Payment_Gateway_API_Response::get_status_code()
98
+ * @return string status code
99
+ */
100
+ public function get_status_code() {
101
+
102
+ return $this->transaction_approved() ? $this->get_success_status_info( 'code' ) : $this->get_failure_status_info( 'code' );
103
+ }
104
+
105
+
106
+ /**
107
+ * Gets the transaction status message
108
+ *
109
+ * @since 3.0.0
110
+ * @see SV_WC_Payment_Gateway_API_Response::get_status_message()
111
+ * @return string status message
112
+ */
113
+ public function get_status_message() {
114
+
115
+ return $this->transaction_approved() ? $this->get_success_status_info( 'message' ) : $this->get_failure_status_info( 'message' );
116
+ }
117
+
118
+
119
+ /**
120
+ * Get the success status info for the given parameter, either code or message
121
+ *
122
+ * @since 3.0.0
123
+ * @param string $type status info type, either `code` or `message`
124
+ * @return string
125
+ */
126
+ public function get_success_status_info( $type ) {
127
+
128
+ // determine which type of response, transaction or credit card verification from adding customer/payment method
129
+ $transaction = ! empty( $this->response->transaction ) ? $this->response->transaction : $this->response->creditCardVerification;
130
+
131
+ if ( isset( $transaction->processorSettlementResponseCode ) ) {
132
+
133
+ // submitting a previously authorized charge for settlement
134
+ $status = array(
135
+ 'code' => $transaction->processorSettlementResponseCode,
136
+ 'message' => $transaction->processorSettlementResponseText,
137
+ );
138
+
139
+ } else {
140
+
141
+ // regular transactions
142
+ $status = array(
143
+ 'code' => $transaction->processorResponseCode,
144
+ 'message' => $transaction->processorResponseText,
145
+ );
146
+ }
147
+
148
+ return isset( $status[ $type ] ) ? $status[ $type ] : null;
149
+ }
150
+
151
+
152
+ /**
153
+ * Get the failure status info for the given parameter, either code or message
154
+ *
155
+ * @since 3.0.0
156
+ * @param string $type status info type, either `code` or `message`
157
+ * @return string
158
+ */
159
+ public function get_failure_status_info( $type ) {
160
+
161
+ // check for validation errors first
162
+ if ( $this->has_validation_errors() ) {
163
+
164
+ $errors = $this->get_validation_errors();
165
+
166
+ return implode( ', ', ( 'code' === $type ? array_keys( $errors ) : array_values( $errors ) ) );
167
+ }
168
+
169
+ // determine which type of response, transaction or credit card verification from adding customer/payment method
170
+ $transaction = ! empty( $this->response->transaction ) ? $this->response->transaction : $this->response->creditCardVerification;
171
+
172
+ // see https://developers.braintreepayments.com/reference/response/transaction/php#unsuccessful-result
173
+ switch ( $transaction->status ) {
174
+
175
+ // gateway rejections are due to CVV, AVS, fraud, etc
176
+ case 'gateway_rejected':
177
+
178
+ $status = array(
179
+ 'code' => $transaction->gatewayRejectionReason,
180
+ 'message' => $this->response->message,
181
+ );
182
+ break;
183
+
184
+ // soft/hard decline directly from merchant processor
185
+ case 'processor_declined':
186
+
187
+ $status = array(
188
+ 'code' => $transaction->processorResponseCode,
189
+ 'message' => $transaction->processorResponseText . ( ! empty( $transaction->additionalProcessorResponse ) ? ' (' . $transaction->additionalProcessorResponse . ')' : '' ),
190
+ );
191
+ break;
192
+
193
+ // only can occur when attempting to settle a previously authorized charge
194
+ case 'settlement_declined':
195
+
196
+ $status = array(
197
+ 'code' => $transaction->processorSettlementResponseCode,
198
+ 'message' => $transaction->processorSettlementResponseText,
199
+ );
200
+ break;
201
+
202
+ // this path shouldn't execute, but for posterity
203
+ default:
204
+ $status = array(
205
+ 'code' => $transaction->status,
206
+ 'message' => $this->response->message,
207
+ );
208
+ }
209
+
210
+ return isset( $status[ $type] ) ? $status[ $type ] : null;
211
+ }
212
+
213
+
214
+ /**
215
+ * Returns true if the response contains validation errors (API call
216
+ * cannot be processed because the request was invalid)
217
+ *
218
+ * @link https://developers.braintreepayments.com/reference/general/validation-errors/overview/php
219
+ *
220
+ * @since 3.0.0
221
+ * @return bool
222
+ */
223
+ public function has_validation_errors() {
224
+
225
+ return isset( $this->response->errors ) && $this->response->errors->deepSize();
226
+ }
227
+
228
+
229
+ /**
230
+ * Get an associative array of validation codes => messages
231
+ *
232
+ * @link https://developers.braintreepayments.com/reference/general/validation-errors/all/php
233
+ *
234
+ * @since 3.0.0
235
+ * @return array
236
+ */
237
+ public function get_validation_errors() {
238
+
239
+ $errors = array();
240
+
241
+ if ( $this->has_validation_errors() ) {
242
+
243
+ foreach ( $this->response->errors->deepAll() as $error ) {
244
+
245
+ $errors[ $error->code ] = $error->message;
246
+ }
247
+ }
248
+
249
+ return $errors;
250
+ }
251
+
252
+
253
+ /**
254
+ * Get the error message suitable for displaying to the customer. This should
255
+ * provide enough information to be helpful for correcting customer-solvable
256
+ * issues (e.g. invalid CVV) but not enough to help nefarious folks phishing
257
+ * for data
258
+ *
259
+ * @since 3.0.0
260
+ */
261
+ public function get_user_message() {
262
+
263
+ $helper = new WC_Braintree_API_Response_Message_Helper( $this );
264
+
265
+ return $helper->get_message();
266
+ }
267
+
268
+
269
+ /**
270
+ * Return the string representation of the response
271
+ *
272
+ * @since 3.0.0
273
+ * @return string
274
+ */
275
+ public function to_string() {
276
+
277
+ // TODO: print this nicer and with less irrelevant information (e.g. subscription attributes, etc) @MR 2015-11-05
278
+ return print_r( $this->response, true );
279
+ }
280
+
281
+
282
+ /**
283
+ * Return the string representation of the response, stripped of any
284
+ * confidential info
285
+ *
286
+ * @since 3.0.0
287
+ * @return string
288
+ */
289
+ public function to_string_safe() {
290
+
291
+ // no idea yet
292
+ return $this->to_string();
293
+ }
294
+
295
+
296
+ /**
297
+ * Return the response type, either `credit-card` or `paypal`
298
+ *
299
+ * @since 3.0.0
300
+ * @return string
301
+ */
302
+ protected function get_response_type() {
303
+
304
+ return $this->response_type;
305
+ }
306
+
307
+
308
+ /**
309
+ * Return the payment type for the response, either `credit-card` or `paypal`
310
+ *
311
+ * @since 3.2.0
312
+ * @return string
313
+ */
314
+ public function get_payment_type() {
315
+
316
+ return $this->get_response_type();
317
+ }
318
+
319
+
320
+ /**
321
+ * Return true if this response is from a credit card request
322
+ *
323
+ * @since 3.0.0
324
+ * @return bool
325
+ */
326
+ protected function is_credit_card_response() {
327
+ return 'credit-card' === $this->get_response_type();
328
+ }
329
+
330
+
331
+ }
includes/api/responses/abstract-wc-braintree-api-transaction-response.php ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Transaction
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Abstract Transaction Response Class
31
+ *
32
+ * Provides common functionality to Credit Card & PayPal transaction response classes
33
+ *
34
+ * @link https://developers.braintreepayments.com/javascript+php/reference/response/transaction
35
+ *
36
+ * @since 3.0.0
37
+ */
38
+ abstract class WC_Braintree_API_Transaction_Response extends WC_Braintree_API_Response implements WC_Braintree_Framework\SV_WC_Payment_Gateway_API_response, WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Authorization_Response, WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Create_Payment_Token_Response, WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Customer_Response {
39
+
40
+
41
+ /** Braintree's CSC match value */
42
+ const CSC_MATCH = 'M';
43
+
44
+
45
+ /**
46
+ * Gets the response transaction ID
47
+ *
48
+ * @since 3.0.0
49
+ * @see SV_WC_Payment_Gateway_API_Response::get_transaction_id()
50
+ * @return string transaction id
51
+ */
52
+ public function get_transaction_id() {
53
+
54
+ return ! empty( $this->response->transaction->id ) ? $this->response->transaction->id : null;
55
+ }
56
+
57
+
58
+ /**
59
+ * Returns the result of the AVS check
60
+ *
61
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#avs_error_response_code
62
+ *
63
+ * @since 3.0.0
64
+ * @see SV_WC_Payment_Gateway_API_Authorization_Response::get_avs_result()
65
+ * @return string result of the AVS check, if any
66
+ */
67
+ public function get_avs_result() {
68
+
69
+ if ( ! empty( $this->response->transaction->avsErrorResponseCode ) ) {
70
+
71
+ return 'error:' . $this->response->transaction->avsErrorResponseCode;
72
+
73
+ } else {
74
+
75
+ return $this->response->transaction->avsPostalCodeResponseCode . ':' . $this->response->transaction->avsStreetAddressResponseCode;
76
+ }
77
+ }
78
+
79
+
80
+ /**
81
+ * Returns the result of the CSC check
82
+ *
83
+ * @since 3.0.0
84
+ * @see SV_WC_Payment_Gateway_API_Authorization_Response::get_csc_result()
85
+ * @return string result of CSC check
86
+ */
87
+ public function get_csc_result() {
88
+
89
+ return ( ! empty( $this->response->transaction->cvvResponseCode ) ) ? $this->response->transaction->cvvResponseCode : null;
90
+ }
91
+
92
+
93
+ /**
94
+ * Returns true if the CSC check was successful
95
+ *
96
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#cvv_response_code
97
+ *
98
+ * @since 3.0
99
+ * @see SV_WC_Payment_Gateway_API_Authorization_Response::csc_match()
100
+ * @return boolean true if the CSC check was successful
101
+ */
102
+ public function csc_match() {
103
+
104
+ return $this->get_csc_result() === self::CSC_MATCH;
105
+ }
106
+
107
+
108
+ /**
109
+ * Return the customer ID for the request
110
+ *
111
+ * @since 3.0.0
112
+ * @return string|null
113
+ */
114
+ public function get_customer_id() {
115
+
116
+ return ! empty( $this->response->transaction->customerDetails->id ) ? $this->response->transaction->customerDetails->id : null;
117
+ }
118
+
119
+
120
+ /** Risk Data feature *****************************************************/
121
+
122
+
123
+ /**
124
+ * Returns true if the transaction has risk data present. If this is not
125
+ * present, advanced fraud tools are not enabled (and set to "show") in
126
+ * the merchant's Braintree account and/or not enabled within plugin settings
127
+ *
128
+ * @since 3.0.0
129
+ */
130
+ public function has_risk_data() {
131
+
132
+ return isset( $this->response->transaction->riskData );
133
+ }
134
+
135
+
136
+ /**
137
+ * Get the risk ID for this transaction
138
+ *
139
+ * @since 3.0.0
140
+ */
141
+ public function get_risk_id() {
142
+
143
+ return ! empty( $this->response->transaction->riskData->id ) ? $this->response->transaction->riskData->id : null;
144
+ }
145
+
146
+
147
+ /**
148
+ * Get the risk decision for this transaction, one of: 'not evaulated',
149
+ * 'approve', 'review', 'decline'
150
+ *
151
+ * @since 3.0.0
152
+ */
153
+ public function get_risk_decision() {
154
+
155
+ return ! empty( $this->response->transaction->riskData->decision ) ? $this->response->transaction->riskData->decision : null;
156
+ }
157
+
158
+
159
+ }
includes/api/responses/abstract-wc-braintree-api-vault-response.php ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Vault
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Vault Response Class
31
+ *
32
+ * Handles common methods for parsing vault responses (customers/payment methods)
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ abstract class WC_Braintree_API_Vault_Response extends WC_Braintree_API_Response {
37
+
38
+
39
+ /**
40
+ * Get the payment token data from the given payment method
41
+ *
42
+ * @since 3.0.0
43
+ * @param \Braintree\CreditCard|\Braintree\PayPalAccount $payment_method payment method object
44
+ * @return array
45
+ */
46
+ protected function get_payment_token_data( $payment_method ) {
47
+
48
+ if ( 'Braintree\CreditCard' === get_class( $payment_method ) ) {
49
+
50
+ // credit card
51
+ return array(
52
+ 'default' => false,
53
+ 'type' => WC_Braintree_Payment_Method::CREDIT_CARD_TYPE,
54
+ 'last_four' => $payment_method->last4,
55
+ 'card_type' => WC_Braintree_Framework\SV_WC_Payment_Gateway_Helper::card_type_from_account_number( $payment_method->bin ),
56
+ 'exp_month' => $payment_method->expirationMonth,
57
+ 'exp_year' => $payment_method->expirationYear,
58
+ 'billing_address_id' => ( isset( $payment_method->billingAddress ) && ! empty( $payment_method->billingAddress->id ) ) ? $payment_method->billingAddress->id : null,
59
+ );
60
+
61
+ } else {
62
+
63
+ // PayPal account
64
+ return array(
65
+ 'default' => false,
66
+ 'type' => WC_Braintree_Payment_Method::PAYPAL_TYPE,
67
+ 'payer_email' => $payment_method->email,
68
+ 'payer_id' => null, // not available when added outside of a transaction
69
+ );
70
+ }
71
+ }
72
+
73
+
74
+ }
includes/api/responses/class-wc-braintree-api-client-token-response.php ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Client-Token
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Client Token Response Class
31
+ *
32
+ * Handles retrieving the client token
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ class WC_Braintree_API_Client_Token_Response extends WC_Braintree_API_Response {
37
+
38
+
39
+ /**
40
+ * Return the client token string
41
+ *
42
+ * @since 3.0.0
43
+ * @return string a very long string (1000+ chars)
44
+ */
45
+ public function get_client_token() {
46
+
47
+ return ! empty( $this->response ) ? $this->response : '';
48
+ }
49
+
50
+
51
+ }
includes/api/responses/class-wc-braintree-api-credit-card-transaction-response.php ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Credit-Card-Transaction
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Credit Card Transaction Response Class
31
+ *
32
+ * Handles parsing credit card transaction responses
33
+ *
34
+ * @see https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details
35
+ *
36
+ * @since 3.0.0
37
+ */
38
+ class WC_Braintree_API_Credit_Card_Transaction_Response extends WC_Braintree_API_Transaction_Response {
39
+
40
+
41
+ /**
42
+ * Get the authorization code
43
+ *
44
+ * @since 3.0.0
45
+ * @see SV_WC_Payment_Gateway_API_Authorization_Response::get_authorization_code()
46
+ * @return string 6 character credit card authorization code
47
+ */
48
+ public function get_authorization_code() {
49
+
50
+ return ! empty( $this->response->transaction->processorAuthorizationCode ) ? $this->response->transaction->processorAuthorizationCode : null;
51
+ }
52
+
53
+
54
+ /**
55
+ * Get the credit card payment token created during this transaction
56
+ *
57
+ * @since 3.0.0
58
+ * @return \WC_Braintree_Payment_Method
59
+ * @throws \SV_WC_Payment_Gateway_Exception if token is missing
60
+ */
61
+ public function get_payment_token() {
62
+
63
+ if ( empty( $this->response->transaction->creditCardDetails->token ) ) {
64
+ throw new WC_Braintree_Framework\SV_WC_Payment_Gateway_Exception( __( 'Required credit card token is missing or empty!', 'woocommerce-gateway-paypal-powered-by-braintree' ) );
65
+ }
66
+
67
+ $data = array(
68
+ 'default' => false, // tokens created as part of a transaction can't be set as default
69
+ 'type' => WC_Braintree_Payment_Method::CREDIT_CARD_TYPE,
70
+ 'last_four' => $this->get_last_four(),
71
+ 'card_type' => $this->get_card_type(),
72
+ 'exp_month' => $this->get_exp_month(),
73
+ 'exp_year' => $this->get_exp_year(),
74
+ 'billing_address_id' => $this->get_billing_address_id(),
75
+ );
76
+
77
+ return new WC_Braintree_Payment_Method( $this->response->transaction->creditCardDetails->token, $data );
78
+ }
79
+
80
+
81
+ /**
82
+ * Get the card type used for this transaction
83
+ *
84
+ * @since 3.0.0
85
+ * @return string
86
+ */
87
+ public function get_card_type() {
88
+
89
+ // note that creditCardDetails->cardType is not used here as it is already prettified (e.g. American Express instead of amex)
90
+ return WC_Braintree_Framework\SV_WC_Payment_Gateway_Helper::card_type_from_account_number( $this->get_bin() );
91
+ }
92
+
93
+
94
+ /**
95
+ * Get the BIN (bank identification number), AKA the first 6 digits of the card
96
+ * number. Most useful for identifying the card type.
97
+ *
98
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details.bin
99
+ *
100
+ * @since 3.0.0
101
+ * @return string
102
+ */
103
+ public function get_bin() {
104
+
105
+ return ! empty( $this->response->transaction->creditCardDetails->bin ) ? $this->response->transaction->creditCardDetails->bin : null;
106
+ }
107
+
108
+
109
+ /**
110
+ * Get the masked card number, which is the first 6 digits followed by
111
+ * 6 asterisks then the last 4 digits. This complies with PCI security standards.
112
+ *
113
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details.masked_number
114
+ *
115
+ * @since 3.0.0
116
+ * @return string
117
+ */
118
+ public function get_masked_number() {
119
+
120
+ return ! empty( $this->response->transaction->creditCardDetails->maskedNumber ) ? $this->response->transaction->creditCardDetails->maskedNumber : null;
121
+ }
122
+
123
+
124
+ /**
125
+ * Get the last four digits of the card number used for this transaction
126
+ *
127
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details.last_4
128
+ *
129
+ * @since 3.0.0
130
+ * @return string
131
+ */
132
+ public function get_last_four() {
133
+
134
+ return ! empty( $this->response->transaction->creditCardDetails->last4) ? $this->response->transaction->creditCardDetails->last4 : null;
135
+ }
136
+
137
+
138
+ /**
139
+ * Get the expiration month (MM) of the card number used for this transaction
140
+ *
141
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details.expiration_month
142
+ *
143
+ * @since 3.0.0
144
+ * @return string
145
+ */
146
+ public function get_exp_month() {
147
+
148
+ return ! empty( $this->response->transaction->creditCardDetails->expirationMonth ) ? $this->response->transaction->creditCardDetails->expirationMonth : null;
149
+ }
150
+
151
+
152
+ /**
153
+ * Get the expiration year (YYYY) of the card number used for this transaction
154
+ *
155
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#credit_card_details.expiration_year
156
+ *
157
+ * @since 3.0.0
158
+ * @return string
159
+ */
160
+ public function get_exp_year() {
161
+
162
+ return ! empty( $this->response->transaction->creditCardDetails->expirationYear ) ? $this->response->transaction->creditCardDetails->expirationYear : null;
163
+ }
164
+
165
+
166
+ /**
167
+ * Get the billing address ID associated with the credit card token added
168
+ * during the transaction
169
+ *
170
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#billing_details.id
171
+ *
172
+ * @since 3.0.0
173
+ * @return string
174
+ */
175
+ public function get_billing_address_id() {
176
+
177
+ return ! empty( $this->response->transaction->billingDetails->id ) ? $this->response->transaction->billingDetails->id : null;
178
+ }
179
+
180
+
181
+ /** 3D Secure feature *****************************************************/
182
+
183
+
184
+ /**
185
+ * Returns true if 3D Secure information is present for the transaction
186
+ *
187
+ * @since 3.0.0
188
+ */
189
+ public function has_3d_secure_info() {
190
+
191
+ return isset( $this->response->transaction->threeDSecureInfo ) && ! empty( $this->response->transaction->threeDSecureInfo );
192
+ }
193
+
194
+
195
+ /**
196
+ * Returns the 3D secure statuses
197
+ *
198
+ * @link https://developers.braintreepayments.com/guides/3d-secure/server-side/php#server-side-details
199
+ *
200
+ * @since 3.0.0
201
+ * @return string
202
+ */
203
+ public function get_3d_secure_status() {
204
+
205
+ return $this->has_3d_secure_info() ? $this->response->transaction->threeDSecureInfo->status : null;
206
+ }
207
+
208
+
209
+ /**
210
+ * Returns true if liability was shifted for the 3D secure transaction
211
+ *
212
+ * @link https://developers.braintreepayments.com/guides/3d-secure/server-side/php#server-side-details
213
+ *
214
+ * @since 3.0.0
215
+ * @return bool
216
+ */
217
+ public function get_3d_secure_liability_shifted() {
218
+
219
+ return $this->has_3d_secure_info() ? $this->response->transaction->threeDSecureInfo->liabilityShifted : null;
220
+ }
221
+
222
+
223
+ /**
224
+ * Returns true if a liability shift was possible for the 3D secure transaction
225
+ *
226
+ * @link https://developers.braintreepayments.com/guides/3d-secure/server-side/php#server-side-details
227
+ *
228
+ * @since 3.0.0
229
+ * @return bool
230
+ */
231
+ public function get_3d_secure_liability_shift_possible() {
232
+
233
+ return $this->has_3d_secure_info() ? $this->response->transaction->threeDSecureInfo->liabilityShiftPossible : null;
234
+ }
235
+
236
+
237
+ /**
238
+ * Returns true if the card was enrolled in a 3D secure program
239
+ *
240
+ * @link https://developers.braintreepayments.com/guides/3d-secure/server-side/php#server-side-details
241
+ *
242
+ * @since 3.0.0
243
+ * @return bool
244
+ */
245
+ public function get_3d_secure_enrollment() {
246
+
247
+ return $this->has_3d_secure_info() && 'Y' === $this->response->transaction->threeDSecureInfo->enrolled;
248
+ }
249
+
250
+
251
+ }
includes/api/responses/class-wc-braintree-api-customer-response.php ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Customer
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Customer Response Class
31
+ *
32
+ * Handles parsing customer responses
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ class WC_Braintree_API_Customer_Response extends WC_Braintree_API_Vault_Response implements WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Create_Payment_Token_Response, WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Get_Tokenized_Payment_Methods_Response, WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Customer_Response {
37
+
38
+
39
+ /** @var \Braintree\CreditCard|\Braintree_PayPalAccount created payment method */
40
+ protected $payment_method;
41
+
42
+
43
+ /**
44
+ * Override the default constructor to set created payment method since
45
+ * Braintree simply provides a list of payment methods instead of an object
46
+ * containing the one just created ಠ_ಠ
47
+ *
48
+ * @since 3.0.0
49
+ * @param mixed $response response data from Braintree SDK
50
+ * @param string $response_type indicates whether the response is from a credit card or PayPal request
51
+ */
52
+ public function __construct( $response, $response_type ) {
53
+
54
+ parent::__construct( $response, $response_type );
55
+
56
+ // set created payment method when creating customer
57
+ if ( isset( $this->response->customer ) ) {
58
+ $this->payment_method = $this->get_created_payment_method();
59
+ }
60
+ }
61
+
62
+
63
+ /**
64
+ * Get the transaction ID, which is typically only present for create customer
65
+ * requests when verifying the associated credit card. PayPal
66
+ * requests (successful or unsuccessful) do not return a transaction ID
67
+ *
68
+ * @since 3.0.0
69
+ */
70
+ public function get_transaction_id() {
71
+
72
+ if ( ! $this->is_credit_card_response() || ! $this->payment_method ) {
73
+ return null;
74
+ }
75
+
76
+ return $this->payment_method->verification->id;
77
+ }
78
+
79
+
80
+ /**
81
+ * Get the single payment token from creating a new customer with a payment
82
+ * method
83
+ *
84
+ * @link https://developers.braintreepayments.com/reference/response/customer/php
85
+ *
86
+ * @since 3.0.0
87
+ * @return \WC_Braintree_Payment_Method
88
+ */
89
+ public function get_payment_token() {
90
+
91
+ return new WC_Braintree_Payment_Method( $this->payment_method->token, $this->get_payment_token_data( $this->payment_method ) );
92
+ }
93
+
94
+
95
+ /**
96
+ * Get the payment tokens for the customer
97
+ *
98
+ * @link https://developers.braintreepayments.com/reference/response/customer/php
99
+ *
100
+ * @since 3.0.0
101
+ * @return array associative array of token => WC_Braintree_Payment_Method objects
102
+ */
103
+ public function get_payment_tokens() {
104
+
105
+ $tokens = array();
106
+
107
+ foreach ( $this->response->paymentMethods() as $method ) {
108
+
109
+ // only credit cards or PayPal accounts
110
+ if ( ! in_array( get_class( $method ), array( 'Braintree\CreditCard', 'Braintree\PayPalAccount' ) ) ) {
111
+ continue;
112
+ }
113
+
114
+ $tokens[ $method->token ] = new WC_Braintree_Payment_Method( $method->token, $this->get_payment_token_data( $method ) );
115
+ }
116
+
117
+ return $tokens;
118
+ }
119
+
120
+
121
+ /**
122
+ * Get the customer ID generated by Braintree when creating a new customer
123
+ *
124
+ * @since 3.0.0
125
+ * @return string
126
+ */
127
+ public function get_customer_id() {
128
+
129
+ return isset( $this->response->customer ) ? $this->response->customer->id : null;
130
+ }
131
+
132
+
133
+ /** Risk Data feature *****************************************************/
134
+
135
+
136
+ /**
137
+ * Returns true if the transaction has risk data present. If this is not
138
+ * present, advanced fraud tools are not enabled (and set to "show") in
139
+ * the merchant's Braintree account and/or not enabled within plugin settings
140
+ *
141
+ * @since 3.0.0
142
+ */
143
+ public function has_risk_data() {
144
+
145
+ return isset( $this->payment_method->verification->riskData );
146
+ }
147
+
148
+
149
+ /**
150
+ * Get the risk ID for this transaction
151
+ *
152
+ * @since 3.0.0
153
+ */
154
+ public function get_risk_id() {
155
+
156
+ return $this->has_risk_data() ? $this->payment_method->verification->riskData->id : null;
157
+ }
158
+
159
+
160
+ /**
161
+ * Get the risk decision for this transaction, one of: 'not evaulated',
162
+ * 'approve', 'review', 'decline'
163
+ *
164
+ * @since 3.0.0
165
+ */
166
+ public function get_risk_decision() {
167
+
168
+ return $this->has_risk_data() ? $this->payment_method->verification->riskData->decision : null;
169
+ }
170
+
171
+
172
+ /** Helpers ***************************************************************/
173
+
174
+
175
+ /**
176
+ * Helper to return the payment method created along with the customer, can be
177
+ * either a credit card or PayPal account
178
+ *
179
+ * @since 3.0.0
180
+ * @return \Braintree_CreditCard|\Braintree_PayPalAccount
181
+ */
182
+ protected function get_created_payment_method() {
183
+
184
+ if ( $this->is_credit_card_response() ) {
185
+ return isset( $this->response->customer->creditCards ) && is_array( $this->response->customer->creditCards ) ? $this->response->customer->creditCards[0] : null;
186
+ } else {
187
+ return isset( $this->response->customer->paypalAccounts ) && is_array( $this->response->customer->creditCards ) ? $this->response->customer->paypalAccounts[0] : null;
188
+ }
189
+ }
190
+
191
+
192
+ }
includes/api/responses/class-wc-braintree-api-payment-method-nonce-response.php ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Payment-Nonce
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree API Payment Method Nonce Response Class
29
+ *
30
+ * Handles parsing payment method nonce responses
31
+ *
32
+ * @since 3.0.0
33
+ */
34
+ class WC_Braintree_API_Payment_Method_Nonce_Response extends WC_Braintree_API_Response {
35
+
36
+
37
+ /**
38
+ * Get the payment method nonce
39
+ *
40
+ * @link https://developers.braintreepayments.com/reference/response/payment-method-nonce/php
41
+ *
42
+ * @since 3.0.0
43
+ * @return mixed
44
+ */
45
+ public function get_nonce() {
46
+
47
+ return isset( $this->response->paymentMethodNonce ) ? $this->response->paymentMethodNonce->nonce : null;
48
+ }
49
+
50
+
51
+ /**
52
+ * Returns true if the payment method has 3D Secure information present
53
+ *
54
+ * @since 3.0.0
55
+ * @return bool
56
+ */
57
+ public function has_3d_secure_info() {
58
+
59
+ return isset( $this->response->paymentMethodNonce ) && isset( $this->response->paymentMethodNonce->threeDSecureInfo );
60
+ }
61
+
62
+
63
+ /**
64
+ * Returns the 3D secure statuses
65
+ *
66
+ * @link https://developers.braintreepayments.com/reference/response/payment-method-nonce/php#three_d_secure_info.status
67
+ *
68
+ * @since 3.0.0
69
+ * @return string
70
+ */
71
+ public function get_3d_secure_status() {
72
+
73
+ return $this->has_3d_secure_info() ? $this->response->paymentMethodNonce->threeDSecureInfo->status : null;
74
+ }
75
+
76
+
77
+ /**
78
+ * Returns true if liability was shifted for the 3D secure transaction
79
+ *
80
+ * @link https://developers.braintreepayments.com/reference/response/payment-method-nonce/php#three_d_secure_info.liability_shifted
81
+ *
82
+ * @since 3.0.0
83
+ * @return bool
84
+ */
85
+ public function get_3d_secure_liability_shifted() {
86
+
87
+ return $this->has_3d_secure_info() ? $this->response->paymentMethodNonce->threeDSecureInfo->liabilityShifted : null;
88
+ }
89
+
90
+
91
+ /**
92
+ * Returns true if a liability shift was possible for the 3D secure transaction
93
+ *
94
+ * @link https://developers.braintreepayments.com/reference/response/payment-method-nonce/php#three_d_secure_info.liability_shift_possible
95
+ *
96
+ * @since 3.0.0
97
+ * @return bool
98
+ */
99
+ public function get_3d_secure_liability_shift_possible() {
100
+
101
+ return $this->has_3d_secure_info() ? $this->response->paymentMethodNonce->threeDSecureInfo->liabilityShiftPossible : null;
102
+ }
103
+
104
+
105
+ /**
106
+ * Returns true if the card was enrolled in a 3D secure program
107
+ *
108
+ * @link https://developers.braintreepayments.com/reference/response/payment-method-nonce/php#three_d_secure_info.enrolled
109
+ *
110
+ * @since 3.0.0
111
+ * @return bool
112
+ */
113
+ public function get_3d_secure_enrollment() {
114
+
115
+ return $this->has_3d_secure_info() && 'Y' === $this->response->paymentMethodNonce->threeDSecureInfo->enrolled;
116
+ }
117
+
118
+
119
+ }
includes/api/responses/class-wc-braintree-api-payment-method-response.php ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/Payment-Method
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API Payment Method Response Class
31
+ *
32
+ * Handles parsing payment method responses
33
+ *
34
+ * @since 3.0.0
35
+ */
36
+ class WC_Braintree_API_Payment_Method_Response extends WC_Braintree_API_Vault_Response implements WC_Braintree_Framework\SV_WC_Payment_Gateway_API_Create_Payment_Token_Response {
37
+
38
+
39
+ /**
40
+ * Get the transaction ID, which is typically only present for create customer/
41
+ * payment method requests when verifying the associated credit card. PayPal
42
+ * requests (successful or unsuccessful) do not return a transaction ID
43
+ *
44
+ * @since 3.0.0
45
+ */
46
+ public function get_transaction_id() {
47
+
48
+ return $this->is_credit_card_response() && isset( $this->response->paymentMethod->verification ) ? $this->response->paymentMethod->verification->id : null;
49
+ }
50
+
51
+
52
+ /**
53
+ * Get the single payment token from a Braintree create payment method call
54
+ *
55
+ * @link https://developers.braintreepayments.com/reference/response/payment-method/php
56
+ *
57
+ * @since 3.0.0
58
+ * @return \WC_Braintree_Payment_Method
59
+ */
60
+ public function get_payment_token() {
61
+
62
+ return new WC_Braintree_Payment_Method( $this->response->paymentMethod->token, $this->get_payment_token_data( $this->response->paymentMethod ) );
63
+ }
64
+
65
+
66
+ /**
67
+ * Return true if the verification for this payment method has an AVS rejection from the gateway.
68
+ *
69
+ * @since 3.2.0
70
+ * @return bool
71
+ */
72
+ public function has_avs_rejection() {
73
+
74
+ return isset( $this->response->creditCardVerification ) && 'avs' === $this->response->creditCardVerification->gatewayRejectionReason;
75
+ }
76
+
77
+
78
+ /**
79
+ * Return true if the verification for this payment method has an CVV rejection from the gateway.
80
+ *
81
+ * @since 3.2.0
82
+ * @return bool
83
+ */
84
+ public function has_cvv_rejection() {
85
+
86
+ return isset( $this->response->creditCardVerification ) && 'cvv' === $this->response->creditCardVerification->gatewayRejectionReason;
87
+ }
88
+
89
+
90
+ /** Risk Data feature *****************************************************/
91
+
92
+
93
+ /**
94
+ * Returns true if the transaction has risk data present. If this is not
95
+ * present, advanced fraud tools are not enabled (and set to "show") in
96
+ * the merchant's Braintree account and/or not enabled within plugin settings
97
+ *
98
+ * @since 3.0.0
99
+ */
100
+ public function has_risk_data() {
101
+
102
+ return isset( $this->response->paymentMethod->verification->riskData );
103
+ }
104
+
105
+
106
+ /**
107
+ * Get the risk ID for this transaction
108
+ *
109
+ * @since 3.0.0
110
+ */
111
+ public function get_risk_id() {
112
+
113
+ return $this->has_risk_data() ? $this->response->paymentMethod->verification->riskData->id : null;
114
+ }
115
+
116
+
117
+ /**
118
+ * Get the risk decision for this transaction, one of: 'not evaulated',
119
+ * 'approve', 'review', 'decline'
120
+ *
121
+ * @since 3.0.0
122
+ */
123
+ public function get_risk_decision() {
124
+
125
+ return $this->has_risk_data() ? $this->response->paymentMethod->verification->riskData->decision : null;
126
+ }
127
+
128
+
129
+ }
includes/api/responses/class-wc-braintree-api-paypal-transaction-response.php ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/API/Responses/PayPal-Transaction
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree API PayPal Transaction Response Class
31
+ *
32
+ * Handles parsing PayPal transaction responses
33
+ *
34
+ * @see https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details
35
+ *
36
+ * @since 3.0.0
37
+ */
38
+ class WC_Braintree_API_PayPal_Transaction_Response extends WC_Braintree_API_Transaction_Response {
39
+
40
+
41
+ /**
42
+ * Get the authorization code
43
+ *
44
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details.authorization_id
45
+ *
46
+ * @since 3.0.0
47
+ * @see SV_WC_Payment_Gateway_API_Authorization_Response::get_authorization_code()
48
+ * @return string 6 character credit card authorization code
49
+ */
50
+ public function get_authorization_code() {
51
+
52
+ return ! empty( $this->response->transaction->paypalDetails->authorizationId ) ? $this->response->transaction->paypalDetails->authorizationId : null;
53
+ }
54
+
55
+
56
+ /**
57
+ * Get the PayPal payment token created during this transaction
58
+ *
59
+ * @since 3.0.0
60
+ * @return \WC_Braintree_Payment_Method
61
+ * @throws \SV_WC_Payment_Gateway_Exception if token is missing
62
+ */
63
+ public function get_payment_token() {
64
+
65
+ if ( empty( $this->response->transaction->paypalDetails->token ) ) {
66
+ throw new WC_Braintree_Framework\SV_WC_Payment_Gateway_Exception( __( 'Required PayPal token is missing or empty!', 'woocommerce-gateway-paypal-powered-by-braintree' ) );
67
+ }
68
+
69
+ $data = array(
70
+ 'default' => false, // tokens created as part of a transaction can't be set as default
71
+ 'type' => WC_Braintree_Payment_Method::PAYPAL_TYPE,
72
+ 'payer_email' => $this->get_payer_email(),
73
+ 'payer_id' => $this->get_payer_id(),
74
+ );
75
+
76
+ return new WC_Braintree_Payment_Method( $this->response->transaction->paypalDetails->token, $data );
77
+ }
78
+
79
+
80
+ /**
81
+ * Get the email address associated with the PayPal account used for this transaction
82
+ *
83
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details.payer_email
84
+ *
85
+ * @since 3.0.0
86
+ * @return string
87
+ */
88
+ public function get_payer_email() {
89
+
90
+ return ! empty( $this->response->transaction->paypalDetails->payerEmail ) ? $this->response->transaction->paypalDetails->payerEmail : null;
91
+ }
92
+
93
+
94
+ /**
95
+ * Get the payer ID associated with the PayPal account used for this transaction
96
+ *
97
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details.payer_id
98
+ *
99
+ * @since 3.0.0
100
+ * @return string
101
+ */
102
+ public function get_payer_id() {
103
+
104
+ return ! empty( $this->response->transaction->paypalDetails->payerId ) ? $this->response->transaction->paypalDetails->payerId : null;
105
+ }
106
+
107
+
108
+ /**
109
+ * Get the payment ID for this transaction
110
+ *
111
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details.payment_id
112
+ *
113
+ * @since 3.0.0
114
+ * @return string
115
+ */
116
+ public function get_payment_id() {
117
+
118
+ return ! empty( $this->response->transaction->paypalDetails->paymentId ) ? $this->response->transaction->paypalDetails->paymentId : null;
119
+ }
120
+
121
+
122
+ /**
123
+ * Get the debug ID for this transaction
124
+ *
125
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details
126
+ *
127
+ * @since 3.0.0
128
+ * @return string
129
+ */
130
+ public function get_debug_id() {
131
+
132
+ return ! empty( $this->response->transaction->paypalDetails->debugId ) ? $this->response->transaction->paypalDetails->debugId : null;
133
+ }
134
+
135
+
136
+ /**
137
+ * Get the refund ID for this transaction
138
+ *
139
+ * @link https://developers.braintreepayments.com/reference/response/transaction/php#paypal_details.refund_id
140
+ *
141
+ * @since 3.0.0
142
+ * @return string
143
+ */
144
+ public function get_refund_id() {
145
+
146
+ return ! empty( $this->response->transaction->paypalDetails->refundId ) ? $this->response->transaction->paypalDetails->refundId : null;
147
+ }
148
+
149
+
150
+ }
includes/class-wc-braintree-frontend.php ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/Payment-Method
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ defined( 'ABSPATH' ) or exit;
26
+
27
+ /**
28
+ * Braintree Frontend class
29
+ *
30
+ * Modifies the "My Payment Methods" table output from WC_Braintree_Framework files.
31
+ *
32
+ * TODO: This class can be removed if / when the SV Plugin Framework implements card icons in their own table cells.
33
+ * @see https://github.com/skyverge/wc-plugin-framework/issues/198
34
+ *
35
+ * @since 2.0.0
36
+ */
37
+ class WC_Braintree_Frontend {
38
+
39
+
40
+ /**
41
+ * WC_Braintree_Frontend constructor.
42
+ *
43
+ * @since 2.0.0
44
+ */
45
+ public function __construct() {
46
+
47
+ // add hooks to modify the payment table output
48
+ add_filter( 'wc_braintree_my_payment_methods_table_headers', array( $this, 'modify_table_headers' ) );
49
+ add_filter( 'wc_braintree_my_payment_methods_table_body_row_data', array( $this, 'add_card_icon_cell' ), 10, 2 );
50
+ add_filter( 'wc_braintree_my_payment_methods_table_method_title', array( $this, 'remove_card_icon_from_title' ), 10, 2 );
51
+ }
52
+
53
+
54
+ /**
55
+ * Modifies the "My Payment Methods" table headers.
56
+ *
57
+ * @since 2.0.0
58
+ *
59
+ * @param string[] $headers the table headers
60
+ * @return string[] updated headers
61
+ */
62
+ public function modify_table_headers( $headers ) {
63
+
64
+ // be sure the card icon is the first column in the row
65
+ $new_headers = array(
66
+ 'icon' => esc_html_x( 'Type', 'Payment Method Type', 'woocommerce-gateway-paypal-powered-by-braintree' ),
67
+ );
68
+
69
+ return array_merge( $new_headers, $headers );
70
+ }
71
+
72
+
73
+ /**
74
+ * Adds a new table cell for the card icon, e.g. an Amex logo.
75
+ *
76
+ * @since 2.0.0
77
+ *
78
+ * @param string[] $methods {
79
+ * @type string $title payment method title
80
+ * @type string $expiry payment method expiry
81
+ * @type string $actions actions for payment method
82
+ * }
83
+ * @param \SV_WC_Payment_Gateway_Payment_Token $token token
84
+ * @return string[] updated method data
85
+ */
86
+ public function add_card_icon_cell( $method, $token ) {
87
+
88
+ $method['icon'] = $this->get_payment_token_icon( $token );
89
+ return $method;
90
+ }
91
+
92
+
93
+ /**
94
+ * Since we want to remove the card image, we need to re-build the method title html.
95
+ *
96
+ * Note: the textdomain is intentionally different here, which allows for existing framework translations to remain.
97
+ *
98
+ * @since 2.0.0
99
+ *
100
+ * @param string $html the method title html
101
+ * @param \SV_WC_Payment_Gateway_Payment_Token $token token
102
+ * @return string updated html
103
+ */
104
+ public function remove_card_icon_from_title( $html, $token ) {
105
+
106
+ $last_four = $token->get_last_four();
107
+ $title = $token->get_type_full();
108
+
109
+ // add "ending in XXXX" if available
110
+ if ( $last_four ) {
111
+
112
+ /* translators: %s - last four digits of a card/account */
113
+ $title .= '&nbsp;' . sprintf( esc_html__( 'ending in %s', 'woocommerce-plugin-framework' ), $last_four );
114
+ }
115
+
116
+ // add "(default)" if token is set as default
117
+ if ( $token->is_default() ) {
118
+
119
+ $title .= ' ' . esc_html__( '(default)', 'woocommerce-plugin-framework' );
120
+ }
121
+
122
+ return $title;
123
+ }
124
+
125
+
126
+ /**
127
+ * Get the payment method icon for a given token, e.g.: the Amex logo.
128
+ *
129
+ * @since 2.0.0
130
+ *
131
+ * @param \SV_WC_Payment_Gateway_Payment_Token $token token
132
+ * @return string payment method icon html
133
+ */
134
+ protected function get_payment_token_icon( $token ) {
135
+
136
+ $image_url = $token->get_image_url();
137
+ $type = $token->get_type_full();
138
+
139
+ if ( $image_url ) {
140
+
141
+ // format like "<Amex logo image> American Express"
142
+ $image_html = sprintf( '<img src="%1$s" alt="%2$s" title="%2$s" width="40" height="25" />', esc_url( $image_url ), $type );
143
+
144
+ } else {
145
+
146
+ // missing payment method image, format like "American Express"
147
+ $image_html = $type;
148
+ }
149
+
150
+ /**
151
+ * My Payment Methods Table Method Icon Filter.
152
+ *
153
+ * Allow actors to modify the table payment method icon.
154
+ *
155
+ * @since 2.0.0
156
+ * @param string $image_html payment method icon html
157
+ * @param \SV_WC_Payment_Gateway_Payment_Token $token token object
158
+ */
159
+ return apply_filters( 'wc_braintree_my_payment_methods_table_method_icon', $image_html, $token );
160
+ }
161
+
162
+
163
+ }
includes/class-wc-braintree-payment-method-handler.php ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/Payment-Method-Handler
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree Payment Method Handler Class
31
+ *
32
+ * Extends the framework payment tokens handler class to provide Braintree-specific
33
+ * functionality
34
+ *
35
+ * @since 3.2.0
36
+ */
37
+ class WC_Braintree_Payment_Method_Handler extends WC_Braintree_Framework\SV_WC_Payment_Gateway_Payment_Tokens_Handler {
38
+
39
+
40
+ /**
41
+ * Return a custom payment token class instance
42
+ *
43
+ * @since 3.0.0
44
+ * @see SV_WC_Payment_Gateway_Payment_Tokens_Handler::build_token()
45
+ * @param string $token_id token ID
46
+ * @param array $data token data
47
+ * @return \WC_Braintree_Payment_Method
48
+ */
49
+ public function build_token( $token_id, $data ) {
50
+
51
+ return new WC_Braintree_Payment_Method( $token_id, $data );
52
+ }
53
+
54
+
55
+ /**
56
+ * When retrieving payment methods via the Braintree API, it returns both
57
+ * credit/debit card *and* PayPal methods from a single call. Overriding
58
+ * the core framework update method ensures that PayPal accounts are not saved to
59
+ * the credit card token meta entry, and vice versa.
60
+ *
61
+ * @since 3.0.0
62
+ * @param int $user_id WP user ID
63
+ * @param array $tokens array of tokens
64
+ * @param string $environment_id optional environment id, defaults to plugin current environment
65
+ * @return string updated user meta id
66
+ */
67
+ public function update_tokens( $user_id, $tokens, $environment_id = null ) {
68
+
69
+ foreach ( $tokens as $token_id => $token ) {
70
+
71
+ if ( ( $this->get_gateway()->is_credit_card_gateway() && ! $token->is_credit_card() ) || ( $this->get_gateway()->is_paypal_gateway() && ! $token->is_paypal_account() ) ) {
72
+ unset( $tokens[ $token_id ] );
73
+ }
74
+ }
75
+
76
+ return parent::update_tokens( $user_id, $tokens, $environment_id );
77
+ }
78
+
79
+
80
+ }
includes/class-wc-braintree-payment-method.php ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/Payment-Method
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree Payment Method Class
31
+ *
32
+ * Extends the framework Payment Token class to provide Braintree-specific
33
+ * functionality like billing addresses and PayPal support
34
+ *
35
+ * @since 3.0.0
36
+ */
37
+ class WC_Braintree_Payment_Method extends WC_Braintree_Framework\SV_WC_Payment_Gateway_Payment_Token {
38
+
39
+
40
+ /** credit card payment method type */
41
+ const CREDIT_CARD_TYPE = 'credit_card';
42
+
43
+ /** paypal payment method type */
44
+ const PAYPAL_TYPE = 'paypal';
45
+
46
+
47
+ /**
48
+ * Bootstrap the payment method
49
+ *
50
+ * @since 3.0.0
51
+ * @param string $id token ID
52
+ * @param array $data token data
53
+ */
54
+ public function __construct( $id, array $data ) {
55
+
56
+ parent::__construct( $id, $data );
57
+ }
58
+
59
+
60
+ /** Credit Card methods ***************************************************/
61
+
62
+
63
+ /**
64
+ * Get the billing address ID associated with this credit card
65
+ *
66
+ * @since 3.0.0
67
+ * @return string|null
68
+ */
69
+ public function get_billing_address_id() {
70
+
71
+ return ! empty( $this->data['billing_address_id'] ) ? $this->data['billing_address_id'] : null;
72
+ }
73
+
74
+
75
+ /** PayPal account methods ************************************************/
76
+
77
+
78
+ /**
79
+ * Returns true if this payment method is for PayPal account
80
+ *
81
+ * @since 3.0.0
82
+ * @return bool
83
+ */
84
+ public function is_paypal_account() {
85
+
86
+ return self::PAYPAL_TYPE === $this->data['type'];
87
+ }
88
+
89
+
90
+ /**
91
+ * Override the standard type full method to change the type text to the
92
+ * email address associated with the PayPal account
93
+ *
94
+ * @since 3.0.0
95
+ * @return string|void
96
+ */
97
+ public function get_type_full() {
98
+
99
+ return $this->is_paypal_account() ? $this->get_payer_email() : parent::get_type_full();
100
+ }
101
+
102
+
103
+ /**
104
+ * Get the email associated with the PayPal account
105
+ *
106
+ * @since 3.0.0
107
+ * @return string|null
108
+ */
109
+ public function get_payer_email() {
110
+
111
+ return ! empty( $this->data['payer_email'] ) ? $this->data['payer_email'] : null;
112
+ }
113
+
114
+
115
+ /**
116
+ * Get the payer ID associated with the PayPal account
117
+ *
118
+ * @since 3.0.0
119
+ * @return string|null
120
+ */
121
+ public function get_payer_id() {
122
+
123
+ return ! empty( $this->data['payer_id'] ) ? $this->data['payer_id'] : null;
124
+ }
125
+
126
+
127
+ }
includes/class-wc-braintree-paypal-cart.php ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * The PayPal cart handler class.
31
+ *
32
+ * Sets up the actions & filters for handling PayPal's cart functionality.
33
+ *
34
+ * @since 2.0.0
35
+ */
36
+ class WC_Braintree_PayPal_Cart {
37
+
38
+
39
+ /** @var \WC_Gateway_Braintree_PayPal $gateway the PayPal gateway object */
40
+ protected $gateway;
41
+
42
+
43
+ /**
44
+ * Constructs the class.
45
+ *
46
+ * @since 2.0.0
47
+ * @param \WC_Gateway_Braintree_PayPal $gateway the PayPal gateway object
48
+ */
49
+ public function __construct( WC_Gateway_Braintree_PayPal $gateway ) {
50
+
51
+ $this->gateway = $gateway;
52
+
53
+ $this->add_hooks();
54
+ }
55
+
56
+
57
+ /**
58
+ * Adds the necessary actions & filters.
59
+ *
60
+ * @since 2.0.0
61
+ */
62
+ protected function add_hooks() {
63
+
64
+ // add the PayPal button below "Proceed to Checkout"
65
+ add_action( 'woocommerce_proceed_to_checkout', array( $this, 'render' ), 50 );
66
+
67
+ // handle the PayPal token generated by Braintree JS
68
+ add_action( 'woocommerce_api_' . strtolower( get_class( $this->get_gateway() ) ), array( $this, 'handle_wc_api' ) );
69
+
70
+ // set the checkout address value if it's available from the PayPal session
71
+ add_filter( 'woocommerce_checkout_get_value', array( $this, 'set_checkout_value' ), 10, 2 );
72
+
73
+ // set the "Ship to different address" checkbox based on PayPal session data
74
+ add_filter( 'woocommerce_ship_to_different_address_checked', array( $this, 'set_ship_to_different_address' ) );
75
+
76
+ // disable all other gateways at checkout when confirming payment
77
+ add_action( 'woocommerce_available_payment_gateways', array( $this, 'disable_other_gateways' ) );
78
+
79
+ // add styles for the cart & confirmation page
80
+ add_action( 'wp_head', array( $this, 'enqueue_styles' ) );
81
+
82
+ // add a "Cancel" link below the order button at checkout confirmation
83
+ add_action( 'woocommerce_review_order_after_submit', array( $this, 'render_cancel_link' ) );
84
+
85
+ // clear the session data when the cart is emptied
86
+ add_action( 'woocommerce_cart_emptied', array( $this, 'clear_session_data' ) );
87
+ }
88
+
89
+
90
+ /**
91
+ * Renders the PayPal button markup and related JS data.
92
+ *
93
+ * @since 2.0.0
94
+ */
95
+ public function render() {
96
+
97
+ $this->clear_session_data();
98
+
99
+ // if there are subscriptions or pre-orders in the cart and the user
100
+ // already has some stored tokens, then we can halt the cart checkout
101
+ // feature since the customer will likely have a better experience
102
+ // choosing a stored payment method using our standard checkout flow.
103
+ if ( ! $this->is_single_use() && ( ! $this->get_gateway()->tokenization_enabled() || $this->user_has_tokens() ) ) {
104
+ return;
105
+ }
106
+
107
+ $this->render_button();
108
+
109
+ $this->render_js();
110
+ }
111
+
112
+
113
+ /**
114
+ * Renders the PayPal button markup.
115
+ *
116
+ * @since 2.0.0
117
+ */
118
+ public function render_button() {
119
+
120
+ $total = WC()->cart->total;
121
+
122
+ ?>
123
+
124
+ <div id="wc_braintree_paypal_container"></div>
125
+ <input type="hidden" name="wc_braintree_paypal_amount" value="<?php echo esc_attr( WC_Braintree_Framework\SV_WC_Helper::number_format( $total, 2 ) ); ?>" />
126
+ <input type="hidden" name="wc_braintree_paypal_currency" value="<?php echo esc_attr( get_woocommerce_currency() ); ?>" />
127
+ <input type="hidden" name="wc_braintree_paypal_locale" value="<?php echo esc_attr( $this->get_gateway()->get_safe_locale() ); ?>" />
128
+ <input type="hidden" name="wc_braintree_paypal_single_use" value="<?php echo (int) $this->is_single_use(); ?>" />
129
+
130
+ <?php
131
+ }
132
+
133
+
134
+ /**
135
+ * Renders the PayPal button JS.
136
+ *
137
+ * @since 2.0.0
138
+ */
139
+ public function render_js() {
140
+
141
+ $params = array(
142
+ 'id' => $this->get_gateway()->get_id(),
143
+ 'id_dasherized' => $this->get_gateway()->get_id_dasherized(),
144
+ 'debug' => $this->get_gateway()->debug_checkout(),
145
+ );
146
+
147
+ wc_enqueue_js( sprintf( 'window.wc_%1$s_handler = new WC_Braintree_PayPal_Cart_Handler( %2$s );', esc_js( $this->get_gateway()->get_id() ), json_encode( $params ) ) );
148
+ }
149
+
150
+
151
+ /**
152
+ * Handles the request made to the WC API after the JS has generated a token.
153
+ *
154
+ * @since 2.0.0
155
+ */
156
+ public function handle_wc_api() {
157
+
158
+ if ( ! wp_verify_nonce( WC_Braintree_Framework\SV_WC_Helper::get_post( 'wp_nonce' ), 'wc_' . $this->get_gateway()->get_id() . '_cart_set_payment_method' ) ) {
159
+ return;
160
+ }
161
+
162
+ WC()->session->set( 'wc_braintree_paypal_cart_nonce', WC_Braintree_Framework\SV_WC_Helper::get_post( 'nonce' ) );
163
+
164
+ if ( ! empty( $_POST['details'] ) ) {
165
+ $this->set_customer_data( $_POST['details'] );
166
+ }
167
+
168
+ wp_send_json( array(
169
+ 'redirect_url' => WC()->cart->get_checkout_url(),
170
+ ) );
171
+ }
172
+
173
+
174
+ /**
175
+ * Sets the customer address session data from a PayPal token request.
176
+ *
177
+ * @since 2.0.0
178
+ * @param array $data the customer data
179
+ */
180
+ protected function set_customer_data( $data = array() ) {
181
+
182
+ // if there is no data to set, bail
183
+ if ( ! is_array( $data ) || empty( $data ) ) {
184
+ return;
185
+ }
186
+
187
+ $data = wp_parse_args( $data, array(
188
+ 'email' => '',
189
+ 'payerId' => '',
190
+ 'firstName' => '',
191
+ 'lastName' => '',
192
+ 'phone' => '',
193
+ 'countryCode' => '',
194
+ 'shippingAddress' => array(),
195
+ 'billingAddress' => array(),
196
+ ) );
197
+
198
+ $address_defaults = array(
199
+ 'streetAddress' => '',
200
+ 'extendedAddress' => '',
201
+ 'locality' => '',
202
+ 'region' => '',
203
+ 'postalCode' => '',
204
+ 'countryCodeAlpha2' => '',
205
+ );
206
+
207
+ $billing_address = wp_parse_args( $data['billingAddress'], $address_defaults );
208
+ $shipping_address = wp_parse_args( $data['shippingAddress'], $address_defaults );
209
+
210
+ $details = array(
211
+ 'billing' => array(
212
+ 'first_name' => $data['firstName'],
213
+ 'last_name' => $data['lastName'],
214
+ 'email' => $data['email'],
215
+ 'phone' => $data['phone'],
216
+ 'country' => $billing_address['countryCodeAlpha2'],
217
+ 'address_1' => $billing_address['streetAddress'],
218
+ 'address_2' => $billing_address['extendedAddress'],
219
+ 'city' => $billing_address['locality'],
220
+ 'state' => $billing_address['region'],
221
+ 'postcode' => $billing_address['postalCode'],
222
+ ),
223
+ 'shipping' => array(
224
+ 'first_name' => $data['firstName'],
225
+ 'last_name' => $data['lastName'],
226
+ 'country' => $shipping_address['countryCodeAlpha2'],
227
+ 'address_1' => $shipping_address['streetAddress'],
228
+ 'address_2' => $shipping_address['extendedAddress'],
229
+ 'city' => $shipping_address['locality'],
230
+ 'state' => $shipping_address['region'],
231
+ 'postcode' => $shipping_address['postalCode'],
232
+ ),
233
+ );
234
+
235
+ WC()->session->set( 'wc_braintree_paypal_cart_customer_details', $details );
236
+ }
237
+
238
+
239
+ /**
240
+ * Sets the checkout address value if it's available from the PayPal session.
241
+ *
242
+ * @since 2.0.0
243
+ * @param null $value
244
+ * @param string $key the checkout field key
245
+ * @return string|null
246
+ */
247
+ public function set_checkout_value( $value, $key ) {
248
+
249
+ $details = WC()->session->get( 'wc_braintree_paypal_cart_customer_details' );
250
+
251
+ if ( WC_Braintree_Framework\SV_WC_Helper::str_starts_with( $key, 'billing' ) ) {
252
+
253
+ $type = 'billing';
254
+ $key = str_replace( 'billing_', '', $key );
255
+
256
+ } elseif ( WC_Braintree_Framework\SV_WC_Helper::str_starts_with( $key, 'shipping' ) ) {
257
+
258
+ $type = 'shipping';
259
+ $key = str_replace( 'shipping_', '', $key );
260
+
261
+ } else {
262
+
263
+ return $value;
264
+ }
265
+
266
+ if ( ! empty( $details[ $type ][ $key ] ) ) {
267
+ $value = $details[ $type ][ $key ];
268
+ }
269
+
270
+ return $value;
271
+ }
272
+
273
+
274
+ /**
275
+ * Sets the "Ship to different address" checkbox based on PayPal session data.
276
+ *
277
+ * @since 2.0.0
278
+ * @param bool $checked
279
+ * @return bool
280
+ */
281
+ public function set_ship_to_different_address( $checked ) {
282
+
283
+ $details = WC()->session->get( 'wc_braintree_paypal_cart_customer_details', array() );
284
+
285
+ if ( ! empty( $details ) ) {
286
+
287
+ unset( $details['billing']['email'] );
288
+ unset( $details['billing']['phone'] );
289
+
290
+ if ( empty( $details['shipping'] ) ) {
291
+ $checked = false;
292
+ } elseif ( empty( $details['billing'] ) || $details['billing'] !== $details['shipping'] ) {
293
+ $checked = true;
294
+ }
295
+ }
296
+
297
+ return $checked;
298
+ }
299
+
300
+
301
+ /**
302
+ * Disables all other gateways at checkout when confirming payment.
303
+ *
304
+ * @since 2.0.0
305
+ * @param array $gateways
306
+ * @return array
307
+ */
308
+ public function disable_other_gateways( $gateways ) {
309
+
310
+ if ( ! $this->is_checkout_confirmation() ) {
311
+ return $gateways;
312
+ }
313
+
314
+ foreach ( $gateways as $id => $gateway ) {
315
+
316
+ if ( $id !== $this->get_gateway()->get_id() ) {
317
+ unset( $gateways[ $id ] );
318
+ }
319
+ }
320
+
321
+ return $gateways;
322
+ }
323
+
324
+
325
+ /**
326
+ * Adds styles for the cart & confirmation page.
327
+ *
328
+ * @since 2.0.0
329
+ */
330
+ public function enqueue_styles() {
331
+
332
+ if ( ! is_cart() && ! $this->is_checkout_confirmation() ) {
333
+ return;
334
+ }
335
+
336
+ ?>
337
+
338
+ <style>
339
+ .payment_box.payment_method_braintree_paypal {
340
+ padding: 0;
341
+ }
342
+ .payment_box.payment_method_braintree_paypal fieldset {
343
+ display: none;
344
+ }
345
+ .wc-braintree-paypal-cancel {
346
+ display: block;
347
+ text-align: center;
348
+ padding: 15px;
349
+ }
350
+ </style>
351
+
352
+ <?php
353
+ }
354
+
355
+
356
+ /**
357
+ * Renders a "Cancel" link.
358
+ *
359
+ * @since 2.0.0
360
+ */
361
+ public function render_cancel_link() {
362
+
363
+ if ( ! $this->is_checkout_confirmation() ) {
364
+ return;
365
+ }
366
+
367
+ printf(
368
+ '<a href="%1$s" class="wc-' . sanitize_html_class( $this->get_gateway()->get_id_dasherized() ) . '-cancel">%2$s</a>',
369
+ esc_url( add_query_arg( array( 'wc_' . $this->get_gateway()->get_id() . '_clear_session' => true ), WC()->cart->get_cart_url() ) ),
370
+ esc_html__( 'Cancel', 'woocommerce-gateway-paypal-powered-by-braintree' )
371
+ );
372
+ }
373
+
374
+
375
+ /**
376
+ * Determines if the current view is at Checkout, confirming the cart PayPal
377
+ * purchase.
378
+ *
379
+ * @since 2.0.0
380
+ * @return bool
381
+ */
382
+ public function is_checkout_confirmation() {
383
+
384
+ return is_checkout() && $this->get_gateway()->is_available() && $this->get_cart_nonce();
385
+ }
386
+
387
+
388
+ /**
389
+ * Gets the cart nonce from the session, if any.
390
+ *
391
+ * @since 2.0.0
392
+ * @return string
393
+ */
394
+ public function get_cart_nonce() {
395
+
396
+ return WC()->session->get( 'wc_braintree_paypal_cart_nonce', '' );
397
+ }
398
+
399
+
400
+ /**
401
+ * Clears any PayPal cart session data.
402
+ *
403
+ * @since 2.0.0
404
+ */
405
+ public function clear_session_data() {
406
+
407
+ unset( WC()->session->wc_braintree_paypal_cart_nonce );
408
+ unset( WC()->session->wc_braintree_paypal_cart_customer_details );
409
+ }
410
+
411
+
412
+ /**
413
+ * Determines if the PayPal token should be considered "single use".
414
+ *
415
+ * This is primarily dependent on if there are subscriptions or Pre-Orders
416
+ * present in the cart.
417
+ *
418
+ * @since 2.0.0
419
+ * @return bool
420
+ */
421
+ public function is_single_use() {
422
+
423
+ $single_use = true;
424
+
425
+ if ( $this->get_gateway()->get_plugin()->is_pre_orders_active() && \WC_Pre_Orders_Cart::cart_contains_pre_order() && \WC_Pre_Orders_Product::product_is_charged_upon_release( \WC_Pre_Orders_Cart::get_pre_order_product() ) ) {
426
+ $single_use = false;
427
+ }
428
+
429
+ if ( $this->get_gateway()->get_plugin()->is_subscriptions_active() && ( \WC_Subscriptions_Cart::cart_contains_subscription() || wcs_cart_contains_renewal() ) ) {
430
+ $single_use = false;
431
+ }
432
+
433
+ return $single_use;
434
+ }
435
+
436
+
437
+ /**
438
+ * Determines if the current user has any saved tokens.
439
+ *
440
+ * @since 2.0.0
441
+ * @return bool
442
+ */
443
+ protected function user_has_tokens() {
444
+
445
+ $token_count = 0;
446
+
447
+ if ( $this->get_gateway()->tokenization_enabled() && is_user_logged_in() ) {
448
+
449
+ foreach ( $this->get_gateway()->get_payment_tokens_handler()->get_tokens( get_current_user_id() ) as $token ) {
450
+
451
+ // skip this token if it's not a PayPal account
452
+ if ( ! $token->is_paypal_account() ) {
453
+ continue;
454
+ }
455
+
456
+ $token_count++;
457
+ }
458
+ }
459
+
460
+ return $token_count > 0;
461
+ }
462
+
463
+
464
+ /**
465
+ * Gets the PayPal gateway object.
466
+ *
467
+ * @since 2.0.0
468
+ * @return \WC_Gateway_Braintree_PayPal
469
+ */
470
+ protected function get_gateway() {
471
+
472
+ return $this->gateway;
473
+ }
474
+
475
+
476
+ }
includes/class-wc-gateway-braintree-credit-card.php ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * WooCommerce Braintree Gateway
4
+ *
5
+ * This source file is subject to the GNU General Public License v3.0
6
+ * that is bundled with this package in the file license.txt.
7
+ * It is also available through the world-wide-web at this URL:
8
+ * http://www.gnu.org/licenses/gpl-3.0.html
9
+ * If you did not receive a copy of the license and are unable to
10
+ * obtain it through the world-wide-web, please send an email
11
+ * to license@woocommerce.com so we can send you a copy immediately.
12
+ *
13
+ * DISCLAIMER
14
+ *
15
+ * Do not edit or add to this file if you wish to upgrade WooCommerce Braintree Gateway to newer
16
+ * versions in the future. If you wish to customize WooCommerce Braintree Gateway for your
17
+ * needs please refer to http://docs.woocommerce.com/document/braintree/
18
+ *
19
+ * @package WC-Braintree/Gateway/Credit-Card
20
+ * @author WooCommerce
21
+ * @copyright Copyright: (c) 2016-2017, Automattic, Inc.
22
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
23
+ */
24
+
25
+ use \SkyVerge\Plugin_Framework as WC_Braintree_Framework;
26
+
27
+ defined( 'ABSPATH' ) or exit;
28
+
29
+ /**
30
+ * Braintree Credit Card Gateway Class
31
+ *
32
+ * @since 3.0.0
33
+ */
34
+ class WC_Gateway_Braintree_Credit_Card extends WC_Gateway_Braintree {
35
+
36
+
37
+ /** @var string require CSC field */
38
+ protected $require_csc;
39
+
40
+ /** @var string fraud tool to use */
41
+ protected $fraud_tool;
42
+
43
+ /** @var string kount merchant ID */
44
+ protected $kount_merchant_id;
45
+
46
+ /** @var string 3D Secure enabled */
47
+ protected $threed_secure_enabled;
48
+
49
+
50
+ /**
51
+ * Initialize the gateway
52
+ *
53
+ * @since 3.0.0
54
+ */
55
+ public function __construct() {
56
+
57
+ parent::__construct(
58
+ WC_Braintree::CREDIT_CARD_GATEWAY_ID,
59
+ wc_braintree(),
60
+ array(
61
+ 'method_title' => __( 'Braintree (Credit Card)', 'woocommerce-gateway-paypal-powered-by-braintree' ),
62
+ 'method_description' => __( 'Allow customers to securely pay using their credit card via Braintree.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
63
+ 'supports' => array(
64
+ self::FEATURE_PRODUCTS,
65
+ self::FEATURE_CARD_TYPES,
66
+ self::FEATURE_PAYMENT_FORM,
67
+ self::FEATURE_TOKENIZATION,
68
+ self::FEATURE_CREDIT_CARD_CHARGE,
69
+ self::FEATURE_CREDIT_CARD_CHARGE_VIRTUAL,
70
+ self::FEATURE_CREDIT_CARD_AUTHORIZATION,
71
+ self::FEATURE_CREDIT_CARD_CAPTURE,
72
+ self::FEATURE_DETAILED_CUSTOMER_DECLINE_MESSAGES,
73
+ self::FEATURE_REFUNDS,
74
+ self::FEATURE_VOIDS,
75
+ self::FEATURE_CUSTOMER_ID,
76
+ self::FEATURE_ADD_PAYMENT_METHOD,
77
+ self::FEATURE_TOKEN_EDITOR,
78
+ ),
79
+ 'payment_type' => self::PAYMENT_TYPE_CREDIT_CARD,
80
+ 'environments' => $this->get_braintree_environments(),
81
+ 'shared_settings' => $this->shared_settings_names,
82
+ 'card_types' => array(
83
+ 'VISA' => 'Visa',
84
+ 'MC' => 'MasterCard',
85
+ 'AMEX' => 'American Express',
86
+ 'DISC' => 'Discover',
87
+ 'DINERS' => 'Diners',
88
+ 'MAESTRO' => 'Maestro',
89
+ 'JCB' => 'JCB',
90
+ ),
91
+ )
92
+ );
93
+
94
+ // sanitize admin options before saving
95
+ add_filter( 'woocommerce_settings_api_sanitized_fields_braintree_credit_card', array( $this, 'filter_admin_options' ) );
96
+ }
97
+
98
+
99
+ /**
100
+ * Enqueue credit card method specific scripts, currently:
101
+ *
102
+ * + Fraud tool library
103
+ *
104
+ * @since 3.0.0
105
+ * @see SV_WC_Payment_Gateway::enqueue_gateway_assets()
106
+ * @return bool
107
+ */
108
+ public function enqueue_gateway_assets() {
109
+
110
+ parent::enqueue_gateway_assets();
111
+
112
+ // advanced/kount fraud tool
113
+ if ( $this->is_payment_form_page() && $this->is_advanced_fraud_tool_enabled() ) {
114
+
115
+ // enqueue braintree-data.js library
116
+ wp_enqueue_script( 'braintree-data', 'https://js.braintreegateway.com/v1/braintree-data.js', array( 'braintree-js' ), WC_Braintree::VERSION, true );
117
+
118
+ // adjust the script tag to add async attribute
119
+ add_filter( 'clean_url', array( $this, 'adjust_fraud_script_tag' ) );
120
+
121
+ // this script must be rendered to the page before the braintree-data.js library, hence priority 1
122
+ add_action( 'wp_print_footer_scripts', array( $this, 'render_fraud_js' ), 1 );
123
+ }
124
+ }
125
+
126
+
127
+ /**
128
+ * Return the credit card payment form instance
129
+ *
130
+ * @since 3.0.0
131
+ * @return \WC_Braintree_Hosted_Fields_Payment_Form
132
+ */
133
+ public function get_payment_form_instance() {
134
+
135
+ return new WC_Braintree_Hosted_Fields_Payment_Form( $this );
136
+ }
137
+
138
+
139
+ /**
140
+ * Add credit card method specific form fields, currently:
141
+ *
142
+ * + Fraud tool settings
143
+ *
144
+ * @since 3.0.0
145
+ * @see WC_Gateway_Braintree::get_method_form_fields()
146
+ * @return array
147
+ */
148
+ protected function get_method_form_fields() {
149
+
150
+ $fraud_tool_options = array(
151
+ 'basic' => __( 'Basic', 'woocommerce-gateway-paypal-powered-by-braintree' ),
152
+ 'advanced' => __( 'Advanced', 'woocommerce-gateway-paypal-powered-by-braintree' ),
153
+ );
154
+
155
+ // Kount is only available for manual API connections
156
+ if ( $this->is_connected_manually() ) {
157
+ $fraud_tool_options['kount_direct'] = __( 'Kount Direct', 'woocommerce-gateway-paypal-powered-by-braintree' );
158
+ }
159
+
160
+ $fields = array(
161
+
162
+ // fraud tools
163
+ 'fraud_settings_title' => array(
164
+ 'title' => __( 'Fraud Settings', 'woocommerce-gateway-paypal-powered-by-braintree' ),
165
+ 'type' => 'title',
166
+ ),
167
+ 'fraud_tool' => array(
168
+ 'title' => __( 'Fraud Tool', 'woocommerce-gateway-paypal-powered-by-braintree' ),
169
+ 'type' => 'select',
170
+ 'class' => 'js-fraud-tool',
171
+ 'desc_tip' => __( 'Select the fraud tool you want to use. Basic is enabled by default and requires no additional configuration. Advanced requires you to enable advanced fraud tools in your Braintree control panel. To use Kount Direct you must contact Braintree support.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
172
+ 'options' => $fraud_tool_options,
173
+ ),
174
+ 'kount_merchant_id' => array(
175
+ 'title' => __( 'Kount merchant ID', 'woocommerce-gateway-paypal-powered-by-braintree' ),
176
+ 'type' => 'text',
177
+ 'class' => 'js-kount-merchant-id',
178
+ 'desc_tip' => __( 'Speak with your account management team at Braintree to get this.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
179
+ ),
180
+
181
+ // 3D Secure
182
+ 'threed_secure_title' => array(
183
+ 'title' => __( '3D Secure (Verified by Visa, MasterCard SecureCode)', 'woocommerce-gateway-paypal-powered-by-braintree' ),
184
+ 'type' => 'title',
185
+ 'description' => sprintf( __( '3D Secure benefits cardholders and merchants by providing an additional layer of verification. %1$sLearn more about 3D Secure%2$s.', 'woocommerce-gateway-paypal-powered-by-braintree' ), '<a href="' . esc_url( $this->get_plugin()->get_documentation_url() ) . '#3d-secure' . '">', '</a>' ),
186
+ ),
187
+ 'threed_secure_enabled' => array(
188
+ 'title' => __( '3D Secure', 'woocommerce-gateway-paypal-powered-by-braintree' ),
189
+ 'type' => 'checkbox',
190
+ 'label' => __( 'Enable 3D Secure (Visa and MasterCard cards only)', 'woocommerce-gateway-paypal-powered-by-braintree' ),
191
+ 'description' => __( 'You must contact Braintree support to add this feature to your Braintree account before enabling this option.', 'woocommerce-gateway-paypal-powered-by-braintree' ),
192
+ 'default' => 'no',
193
+ ),
194
+ );
195
+
196
+ return array_merge( parent::get_method_form_fields(), $fields );
197
+ }
198
+
199
+
200
+ /**
201
+ * Override the standard CSC setting to instead indicate that it's a combined
202
+ * Display & Require CSC setting. Braintree doesn't allow the CSC field to be
203
+ * present without also requiring it to be populated.
204
+ *
205
+ * @since 3.0.0
206
+ * @param array $form_fields gateway form fields
207
+ * @return array $form_fields gateway form fields
208
+ */
209
+ protected function add_csc_form_fields( $form_fields ) {
210
+
211
+ $form_fields['require_csc'] = array(
212
+ 'title' => __( 'Card Verification (CSC)', 'woocommerce-gateway-paypal-powered-by-braintree' ),
213
+ 'label' => __( 'Display and Require the Card Security Code (CVV/CID) field on checkout', 'woocommerce-gateway-paypal-powered-by-braintree' ),
214
+ 'type' => 'checkbox',
215
+ 'default' => 'yes',
216
+ );
217
+
218
+ return $form_fields;
219
+ }
220
+
221
+
222
+ /**
223
+ * Returns true if the CSC field should be displayed and required at checkout
224
+ *
225
+ * @since 3.0.0
226
+ */
227
+ public function is_csc_required() {
228
+
229
+ return 'yes' === $this->require_csc;
230
+ }
231
+
232
+
233
+ /**
234
+ * Override the standard CSC enabled method to return the value of the csc_required()
235
+ * check since enabled/required is the same for Braintree
236
+ *
237
+ * @since 3.0.0
238
+ * @return bool
239
+ */
240
+ public function csc_enabled() {
241
+
242
+ return $this->is_csc_required();
243
+ }
244
+
245
+
246
+ /**
247
+ * Render credit card method specific JS to the settings page, currently:
248
+ *
249
+ * + Hide/show Fraud tool kount merchant ID setting
250
+ *
251
+ * @since 3.0.0
252
+ * @see WC_Gateway_Braintree::admin_options()
253
+ */
254
+ public function admin_options() {
255
+
256
+ parent::admin_options();
257
+
258
+ ob_start();
259
+ ?>
260
+ // show/hide the kount merchant ID field based on the fraud tools selection
261
+ $( 'select.js-fraud-tool' ).change( function() {
262
+
263
+ var $kount_id_row = $( '.js-kount-merchant-id' ).closest( 'tr' );
264
+
265
+ if ( 'kount_direct' === $( this ).val() ) {
266
+ $kount_id_row.show();
267
+ } else {
268
+ $kount_id_row.hide();
269
+ }
270
+ } ).change();
271
+ <?php
272
+
273
+ wc_enqueue_js( ob_get_clean() );
274
+ }
275
+
276
+
277
+ /**
278
+ * Returns true if the payment nonce is provided when not using a saved
279
+ * payment token. Note this can't be moved to the parent class because
280
+ * validation is payment-type specific.
281
+ *
282
+ * @since 3.0.0
283
+ * @param boolean $is_valid true if the fields are valid, false otherwise
284
+ * @return boolean true if the fields are valid, false otherwise
285
+ */
286
+ protected function validate_credit_card_fields( $is_valid ) {
287
+
288
+ return $this->validate_payment_nonce( $is_valid );
289
+ }
290
+
291
+
292
+ /**
293
+ * Returns true if the payment nonce is provided when using a saved payment method
294
+ * and CSC is required.
295
+ *
296
+ * @since 3.2.0
297
+ * @param string $csc
298
+ * @return bool
299
+ */
300
+ protected function validate_csc( $csc ) {
301
+
302
+ return $this->validate_payment_nonce( true );
303
+ }
304
+
305
+
306
+ /**
307
+ * Add credit card specific data to the order, primarily for 3DS support
308
+ *
309
+ * 1) $order->payment->is_3ds_required - require 3DS for every transaction
310
+ * 2) $order->payment->use_3ds_nonce - use nonce instead of token for transaction
311
+ *
312
+ * @since 3.0.0
313
+ * @param \WC_Order|int $order order
314
+ * @return \WC_Order
315
+ */
316
+ public function get_order( $order ) {
317
+
318
+ $order = parent::get_order( $order );
319
+
320
+ // add information for 3DS transactions, note that server-side verification
321
+ // has already been checked in validate_fields() and passed
322
+ if ( $this->is_3d_secure_enabled() ) {
323
+
324
+ // indicate if 3DS should be required for every transaction -- note
325
+ // this will result in a gateway rejection for *every* transaction
326
+ // that doesn't have a liability shift
327
+ $order->payment->is_3ds_required = $this->is_3d_secure_liability_shift_always_required();
328
+
329
+ // when using a saved payment method for a transaction that has been
330
+ // 3DS verified, indicate the nonce should be used instead, which
331
+ // passes the 3DS verification details to Braintree
332
+ if ( WC_Braintree_Framework\SV_WC_Helper::get_post( 'wc_braintree_credit_card_3d_secure_verified' ) && ! empty( $order->payment->token ) && ! empty( $order->payment->nonce ) ) {
333
+ $order->payment->use_3ds_nonce = true;
334
+ }
335
+ }
336
+
337
+ return $order;
338
+ }
339
+
340
+
341
+ /**
342
+ * Overrides the parent method to set the $order->payment members that are
343
+ * usually set prior to payment with a direct gateway. Because Braintree uses
344
+ * a nonce, we don't have access to the card info (last four, expiry date, etc)
345
+ * until after the transaction is processed.
346
+ *
347
+ * @since 3.0.0
348
+ * @see SV_WC_Payment_Gateway_Direct::do_credit_card_transaction()
349
+ * @param WC_Order $order the order object
350
+ * @param \WC_Braintree_API_Credit_Card_Transaction_Response $response optional credit card transaction response
351
+ * @return \WC_Braintree_API_Credit_Card_Transaction_Response
352
+ */
353
+ protected function do_credit_card_transaction( $order, $response = null ) {
354
+
355
+ if ( is_null( $response ) ) {
356
+
357
+ $response = $this->perform_credit_card_charge( $order ) ? $this->get_api()->credit_card_charge( $order ) : $this->get_api()->credit_card_authorization( $order );
358
+
359
+ if ( $response->transaction_approved() ) {
360
+ $order->payment->account_number = $response->get_masked_number();
361
+ $order->payment->last_four = $response->get_last_four();
362
+ $order->payment->card_type = WC_Braintree_Framework\SV_WC_Payment_Gateway_Helper::card_type_from_account_number( $response->get_masked_number() );
363
+ $order->payment->exp_month = $response->get_exp_month();
364
+ $order->payment->exp_year = $response->get_exp_year();
365
+ }
366
+ }
367
+
368
+ return parent::do_credit_card_transaction( $order, $response );
369
+ }
370
+
371
+
372
+ /**
373
+ * Adds any gateway-specific transaction data to the order, for credit cards
374
+ * this is:
375
+ *
376
+ * + risk data (if available)
377
+ * + 3D Secure data (if available)
378
+ *
379
+ * @since 3.0.0
380
+ * @see SV_WC_Payment_Gateway_Direct::add_transaction_data()
381
+ * @param \WC_Order $order the order object
382
+ * @param \WC_Braintree_API_Credit_Card_Transaction_Response $response transaction response
383
+ */
384
+ public function add_payment_gateway_transaction_data( $order, $response ) {
385
+
386
+ // add risk data
387
+ if ( $this->is_advanced_fraud_tool_enabled() && $response->has_risk_data() ) {
388
+ $this->update_order_meta( $order, 'risk_id', $response->get_risk_id() );
389
+ $this->update_order_meta( $order, 'risk_decision', $response->get_risk_decision() );
390
+ }
391
+
392
+ // add 3D secure data
393
+ if ( $this->is_3d_secure_enabled() && $response->has_3d_secure_info() ) {
394
+ $this->update_order_meta( $order, 'threeds_status', $response->get_3d_secure_status() );
395
+ }
396
+ }
397
+
398
+
399
+ /** Refund/Void feature ***************************************************/
400
+
401
+
402
+ /**
403
+ * Void a transaction instead of refunding when it has a submitted for settlement
404
+ * status. Note that only credit card transactions are eligible for this, as
405
+ * PayPal transactions are settled immediately
406
+ *
407
+ * @since 3.0.0
408
+ * @param \WC_Order $order order
409
+ * @param \WC_Braintree_API_Response $response refund response
410
+ * @return bool true if the transaction should be transaction
411
+ */
412
+ protected function maybe_void_instead_of_refund( $order, $response ) {
413
+
414
+ // Braintree conveniently returns a validation error code that indicates a void can be performed instead of refund
415
+ return $response->has_validation_errors() && in_array( Braintree_Error_Codes::TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED, array_keys( $response->get_validation_errors() ) );
416
+ }
417
+
418
+
419
+ /** Add Payment Method feature ********************************************/
420
+
421
+
422
+ /**
423
+ * Save verification transactional data when a customer
424
+ * adds a new credit via the add payment method flow
425
+ *
426
+ * @since 3.0.0
427
+ * @param \WC_Braintree_API_Customer_Response|\WC_Braintree_API_Payment_Method_Response $response
428
+ * @return array
429
+ */
430
+ protected function get_add_payment_method_payment_gateway_transaction_data( $response ) {
431
+
432
+ $data = array();
433
+
434
+ // transaction ID
435
+ if ( $response->get_transaction_id() ) {
436
+ $data['trans_id'] = $response->get_transaction_id();
437
+ }
438
+
439
+ if ( $this->is_advanced_fraud_tool_enabled() && $response->has_risk_data() ) {
440
+ $data['risk_id'] = $response->get_risk_id();
441
+ $data['risk_decision'] = $response->get_risk_decision();
442
+ }
443
+
444
+ return $data;
445
+ }
446
+
447
+
448
+ /** Fraud Tool feature ****************************************************/
449
+
450
+
451
+ /**
452
+ * Render the fraud tool JS, note this is hooked into wp_print_footer_scripts
453
+ * at priority 1 so that it's rendered prior to the braintree.js/braintree-data.js
454
+ * scripts being loaded
455
+ *
456
+ * @link https://developers.braintreepayments.com/guides/advanced-fraud-tools/overview
457
+ * @since 3.0.0
458
+ */
459
+ public function render_fraud_js() {
460
+
461
+ $environment = 'BraintreeData.environments.' . ( $this->is_test_environment() ? 'sandbox' : 'production' );
462
+
463
+ if ( $this->is_kount_direct_enabled() ) {
464
+ $environment .= '.withId' . $this->get_kount_merchant_id();
465
+ }
466
+
467
+ // TODO: consider moving this to it's own file
468
+
469
+ ?>
470
+ <script>
471
+ jQuery( function ( $ ) {
472
+
473
+ var form_id;
474
+
475
+ if ( $( 'form.checkout' ).length ) {
476
+
477
+ // checkout page
478
+ // WC does not set a form ID, use an existing one if available
479
+ form_id = $( 'form.checkout' ).attr( 'id' ) || 'checkout';
480
+
481
+ // otherwise set it ourselves
482
+ if ( 'checkout' === form_id ) {
483
+ $( 'form.checkout' ).attr( 'id', form_id );
484
+ }
485
+
486
+ } else if ( $( 'form#order_review' ).length ) {
487
+
488
+ // checkout > pay page
489
+ form_id = 'order_review'
490
+
491
+ } else if ( $( 'form#add_payment_method' ).length ) {
492
+
493
+ // add payment method page
494
+ form_id = 'add_payment_method'
495
+ }
496
+
497
+ if ( !form_id ) {
498
+ return;
499
+ }
500
+
501
+ window.onBraintreeDataLoad = function () {
502
+ BraintreeData.setup( '<?php echo esc_js( $this->get_merchant_id() ); ?>', form_id, <?php echo esc_js( $environment ); ?> );
503
+ }
504
+ } );
505
+ </script>
506
+ <?php
507
+ }
508
+
509
+
510
+ /**
511
+ * Add an async attribute to the braintree-data.js script tag, there's no
512
+ * way to do this when enqueing so it must be done manually here
513
+ *
514
+ * @since 3.0.0
515
+ * @param string $url cleaned URL from esc_url()
516
+ * @return string
517
+ */
518
+ public function adjust_fraud_script_tag( $url ) {
519
+
520
+ if ( WC_Braintree_Framework\SV_WC_Helper::str_exists( $url, 'braintree-data.js' ) ) {
521
+
522
+ $url = "{$url}' async='true";
523
+ }
524
+
525
+ return $url;
526
+ }
527
+
528
+
529
+ /**
530
+ * Return the enabled fraud tool setting, either 'basic', 'advanced', or
531
+ * 'kount_direct'
532
+ *
533
+ * @since 3.0.0
534
+ * @return string
535
+ */
536
+ public function get_fraud_tool() {
537
+
538
+ return $this->fraud_tool;
539
+ }
540
+
541
+
542
+ /**
543
+ * Return true if advanced fraud tools are enabled (either advanced or
544
+ * kount direct)
545
+ *
546
+ * @since 3.0.0
547
+ * @return bool
548
+ */
549
+ public function is_advanced_fraud_tool_enabled() {
550
+
551
+ return 'advanced' === $this->get_fraud_tool() || 'kount_direct' === $this->get_fraud_tool();
552
+ }
553
+
554
+
555
+ /**
556
+ * Return true if the Kount Direct fraud tool is enabled
557
+ *
558
+ * @since 3.0.0
559
+ * @return bool
560
+ */
561
+ public function is_kount_direct_enabled() {
562
+
563
+ return 'kount_direct' === $this->get_fraud_tool();
564
+ }
565
+
566
+
567
+ /**
568
+ * Get the Kount merchant ID, only used when the Kount Direct fraud tool
569
+ * is ena