• Namespace
  • Class
  • Tree
  • Deprecated
  • Hook Reference

Namespaces

  • None
  • PaymentPlugins

Classes

  • Braintree_Gateway_Manager
  • PaymentPlugins\WC_Braintree_Admin_Meta_Box_Product_Data
  • PaymentPlugins\WC_Braintree_Constants
  • WC_Braintree_3ds_Validation
  • WC_Braintree_Admin_Assets
  • WC_Braintree_Admin_List_Table_Subscriptions
  • WC_Braintree_Admin_Menus
  • WC_Braintree_Admin_Order_Metaboxes
  • WC_Braintree_Admin_Settings
  • WC_Braintree_Admin_User_Edit
  • WC_Braintree_Advanced_Fraud_Settings
  • WC_Braintree_Advanced_Settings_API
  • WC_Braintree_Alipay_Payment_Gateway
  • WC_Braintree_API_Settings
  • WC_Braintree_ApplePay_Payment_Gateway
  • WC_Braintree_Bancontact_Payment_Gateway
  • WC_Braintree_CC_Payment_Gateway
  • WC_Braintree_Condition_Evaluator
  • WC_Braintree_Context_Stack
  • WC_Braintree_Controller_3ds
  • WC_Braintree_Controller_ApplePay
  • WC_Braintree_Controller_Cart
  • WC_Braintree_Controller_Checkout
  • WC_Braintree_Controller_Client_Token
  • WC_Braintree_Controller_Data_Migration
  • WC_Braintree_Controller_Frontend
  • WC_Braintree_Controller_GooglePay
  • WC_Braintree_Controller_Kount
  • WC_Braintree_Controller_Local_Payment
  • WC_Braintree_Controller_Merchant_Accounts
  • WC_Braintree_Controller_Order_Actions
  • WC_Braintree_Controller_Payment_Tokens
  • WC_Braintree_Controller_PayPal
  • WC_Braintree_Controller_Plan
  • WC_Braintree_Controller_Product
  • WC_Braintree_Controller_Settings
  • WC_Braintree_Controller_Webhook
  • WC_Braintree_Customer_Manager
  • WC_Braintree_Deprecated_Filter_Hooks
  • WC_Braintree_Descriptor_Settings
  • WC_Braintree_EPS_Payment_Gateway
  • WC_Braintree_Fee_Settings
  • WC_Braintree_Field_Manager
  • WC_Braintree_Form_Handler
  • WC_Braintree_Frontend_Scripts
  • WC_Braintree_Giropay_Payment_Gateway
  • WC_Braintree_GooglePay_Payment_Gateway
  • WC_Braintree_IDEAL_Payment_Gateway
  • WC_Braintree_Install
  • WC_Braintree_Local_Payment_Gateway
  • WC_Braintree_Manager
  • WC_Braintree_Merchant_Account_Settings
  • WC_Braintree_Meta_Box_Coupons
  • WC_Braintree_Meta_Box_Subscription_Order_Data
  • WC_Braintree_MyBank_Payment_Gateway
  • WC_Braintree_P24_Payment_Gateway
  • WC_Braintree_Payment_Gateway
  • WC_Braintree_Payment_Method_Conversion
  • WC_Braintree_PayPal_Payment_Gateway
  • WC_Braintree_Post_Types
  • WC_Braintree_Product_Gateway_Option
  • WC_Braintree_Query
  • WC_Braintree_Rest_API
  • WC_Braintree_Rest_Controller
  • WC_Braintree_Rest_Webook_Authentication
  • WC_Braintree_Sepa_Payment_Gateway
  • WC_Braintree_Settings_API
  • WC_Braintree_Shortcode_Payment_Buttons
  • WC_Braintree_Shortcodes
  • WC_Braintree_Sofort_Payment_Gateway
  • WC_Braintree_Subscription
  • WC_Braintree_Subscription_Data_Store_CPT
  • WC_Braintree_Subscription_Settings
  • WC_Braintree_Subscriptions_Cart
  • WC_Braintree_Subscriptions_Checkout
  • WC_Braintree_Update
  • WC_Braintree_Venmo_Payment_Gateway
  • WC_Braintree_WeChat_Payment_Gateway
  • WC_Meta_Box_Braintree_Subscription_Data
  • WC_Payment_Token_Braintree
  • WC_Payment_Token_Braintree_ApplePay
  • WC_Payment_Token_Braintree_CC
  • WC_Payment_Token_Braintree_GooglePay
  • WC_Payment_Token_Braintree_Local_Payment
  • WC_Payment_Token_Braintree_PayPal
  • WC_Payment_Token_Braintree_Venmo
  • WC_Product_Braintree_Subscription
  • WC_Product_Braintree_Subscription_Variation
  • WC_Product_Braintree_Variable_Subscription
  • WCS_Braintree_Subscription_Controller

Traits

  • WC_Braintree_Controller_Cart_Trait
  • WC_Braintree_Settings_Trait

Functions

  • bfwc_add_body_class
  • bfwc_billing_periods_string
  • bfwc_can_delete_payment_method
  • bfwc_copy_address_from_order
  • bfwc_error_code_type_nicename
  • bfwc_get_combined_error_messages
  • bfwc_get_error_message
  • bfwc_get_error_messages
  • bfwc_get_gateway_timezone
  • bfwc_get_product_descriptors
  • bfwc_get_subscription_status_name
  • bfwc_get_subscription_statuses
  • bfwc_get_template
  • bfwc_get_timezones
  • bfwc_register_subscription_status
  • bfwc_subscription_length_string
  • bfwc_subscription_user_actions
  • bfwcs_billing_interval_string
  • bfwcs_billing_intervals
  • bfwcs_calculate_end_date
  • bfwcs_calculate_first_payment_date
  • bfwcs_calculate_next_payment_date
  • bfwcs_calculate_order_total
  • bfwcs_calculate_start_date
  • bfwcs_can_combine_subscriptions
  • bfwcs_cart_contains_subscriptions
  • bfwcs_cart_formatted_date
  • bfwcs_cart_recurring_total_html
  • bfwcs_cart_shipping_total
  • bfwcs_cart_subtotal_string
  • bfwcs_cart_tax_total_html
  • bfwcs_copy_order_meta
  • bfwcs_create_order_from_subscription
  • bfwcs_create_renewal_order
  • bfwcs_create_subscription
  • bfwcs_frontend_interval_string
  • bfwcs_get_currency_symbol
  • bfwcs_get_interval_string
  • bfwcs_get_length_string
  • bfwcs_get_period_string
  • bfwcs_get_plan_from_product
  • bfwcs_get_price_string
  • bfwcs_get_product_price_html
  • bfwcs_get_related_orders
  • bfwcs_get_subscription
  • bfwcs_get_subscription_actions
  • bfwcs_get_subscription_statuses
  • bfwcs_get_subscriptions_for_order
  • bfwcs_get_subscriptions_for_user
  • bfwcs_is_change_payment_method
  • bfwcs_is_pay_for_subscription_request
  • bfwcs_order_contains_subscription
  • bfwcs_order_is_subscription
  • bfwcs_product_is_subscription
  • bfwcs_subscription_link_active
  • braintree
  • braintree_delete_user_payment_method
  • braintree_delete_user_payment_methods
  • braintree_device_data_field
  • braintree_get_customer_id
  • braintree_get_default_method
  • braintree_get_method_uris
  • braintree_get_method_url
  • braintree_get_payment_method_formats
  • braintree_get_payment_method_from_token
  • braintree_get_payment_method_title_from_array
  • braintree_get_payment_method_title_from_method
  • braintree_get_payment_method_title_from_method_details
  • braintree_get_payment_method_title_from_transaction
  • braintree_get_payment_title_from_token
  • braintree_get_payment_token_from_transaction
  • braintree_get_user_payment_methods
  • braintree_hidden_field
  • braintree_nonce_field
  • braintree_payment_method_to_array
  • braintree_payment_token_field
  • braintree_save_payment_method_from_transaction
  • braintree_save_user_payment_method
  • braintree_save_user_payment_methods
  • bt_manager
  • bwc_3ds_no_action_needed
  • bwc_3ds_verify_vaulted_methods
  • bwc_add_allowed_html
  • bwc_add_notice
  • bwc_applepay_cart_checkout_enabled
  • bwc_applepay_checkout_banner_enabled
  • bwc_applepay_get_line_items
  • bwc_applepay_product_checkout_enabled
  • bwc_calculate_fee
  • bwc_can_refund_order
  • bwc_card_payments_enabled
  • bwc_custom_form_text
  • bwc_cvv_field_enabled
  • bwc_display_icons_on_payment_methods_page
  • bwc_display_save_payment_method
  • bwc_dropin_v2_enabled
  • bwc_dropin_v3_enabled
  • bwc_enable_signup_from_checkout
  • bwc_execute_conditional_statement
  • bwc_fail_on_duplicate
  • bwc_fee_enabled_for_gateway
  • bwc_fees_enabled
  • bwc_get_3_0_0_deprecated_order_prop
  • bwc_get_3_0_0_updated_props
  • bwc_get_3ds_modal_html
  • bwc_get_billing_agreement_desc
  • bwc_get_comma_separated_product_names
  • bwc_get_conditional_values
  • bwc_get_custom_form
  • bwc_get_custom_form_fields
  • bwc_get_custom_forms
  • bwc_get_default_method
  • bwc_get_enclosed_icon_url
  • bwc_get_fees_for_gateway
  • bwc_get_gateway_fees
  • bwc_get_gateway_id
  • bwc_get_googlepay_methods
  • bwc_get_loader_file
  • bwc_get_merchant_account
  • bwc_get_merchant_accounts
  • bwc_get_option_text
  • bwc_get_order_property
  • bwc_get_payment_gateways
  • bwc_get_paypal_button
  • bwc_get_paypal_credit_button
  • bwc_get_paypal_credit_html
  • bwc_get_paypal_html
  • bwc_get_product_property
  • bwc_get_save_method_template
  • bwc_get_smartbutton_style
  • bwc_get_template
  • bwc_get_template_html
  • bwc_get_user_applepay_payment_methods
  • bwc_get_user_payment_methods
  • bwc_get_user_paypal_payment_methods
  • bwc_googlepay_enabled
  • bwc_is_3ds_active
  • bwc_is_3ds_enabled
  • bwc_is_admin_webhook_request
  • bwc_is_advanced_fraud_tools
  • bwc_is_applepay_enabled
  • bwc_is_checkout
  • bwc_is_custom_form
  • bwc_is_descriptors_enabled
  • bwc_is_dynamic_card_display
  • bwc_is_paypal_enabled
  • bwc_is_wc_3_0_0_or_more
  • bwc_kount_enabled
  • bwc_kount_send_processing_email
  • bwc_locate_template
  • bwc_output_checkout_error
  • bwc_payment_icons_enclosed_type
  • bwc_payment_icons_outside
  • bwc_payment_icons_type
  • bwc_payment_loader_enabled
  • bwc_payment_method_token_field
  • bwc_payment_token_field
  • bwc_paypal_cart_checkout_enabled
  • bwc_paypal_checkout_banner_enabled
  • bwc_paypal_checkout_flow
  • bwc_paypal_credit_active
  • bwc_paypal_credit_conditions
  • bwc_paypal_credit_enabled
  • bwc_paypal_credit_send_shipping
  • bwc_paypal_send_shipping
  • bwc_postal_code_enabled
  • bwc_refresh_payment_fragments
  • bwc_saved_payment_method_style
  • bwc_saved_payment_methods_list
  • bwc_set_checkout_error
  • bwc_smart_buttons_enabled
  • bwc_use_admin_text_for_custom_form
  • bwcs_braintree_subscriptions_active
  • bwcs_calculate_order_total
  • bwcs_can_combine_subscriptions
  • bwcs_can_delete_payment_method
  • bwcs_cart_item_contains_subscription
  • bwcs_get_cart_item_key
  • bwcs_get_current_date_time
  • bwcs_get_num_of_billing_cycles
  • bwcs_get_plan_from_product
  • bwcs_get_product_from_subscription
  • bwcs_get_start_date_in_utc
  • bwcs_get_subscription_date
  • bwcs_is_braintree_subscription
  • bwcs_is_change_payment_method
  • bwcs_is_paid_for_failed_renewal_request
  • bwcs_is_woocommerce_change_payment
  • bwcs_order_contains_subscription
  • bwcs_order_has_coupon
  • bwcs_order_is_subscription
  • bwcs_product_is_subscription
  • bwcs_retry_after_exception
  • bwcs_start_date_in_site_timezone
  • bwcs_subscription_has_trial
  • bwcs_subscription_is_synched
  • bwcs_subscriptions_active
  • wc_braintree_add_allowed_html
  • wc_braintree_add_body_class
  • wc_braintree_banner_checkout_template
  • wc_braintree_card_loader_options
  • wc_braintree_cart_checkout_template
  • wc_braintree_connection_settings
  • wc_braintree_create_payment_token
  • wc_braintree_create_payment_token_from_transaction
  • wc_braintree_custom_form_active
  • wc_braintree_custom_form_options
  • wc_braintree_delete_customer
  • wc_braintree_deprecated_template_check
  • wc_braintree_device_data_field
  • wc_braintree_display_prices_including_tax
  • wc_braintree_enqueue_local_payments
  • wc_braintree_environment
  • wc_braintree_errors_from_object
  • wc_braintree_evaluate_condition
  • wc_braintree_filter_customer_payment_tokens
  • wc_braintree_filter_payment_tokens
  • wc_braintree_generate_client_token
  • wc_braintree_get_3ds_actions
  • wc_braintree_get_card_type_icons
  • wc_braintree_get_checkout_fields
  • wc_braintree_get_conditional_values
  • wc_braintree_get_currency
  • wc_braintree_get_custom_form
  • wc_braintree_get_customer_id
  • wc_braintree_get_error_messages
  • wc_braintree_get_fee_gateways
  • wc_braintree_get_file_data
  • wc_braintree_get_local_gateways
  • wc_braintree_get_merchant_account
  • wc_braintree_get_merchant_accounts
  • wc_braintree_get_order_environment
  • wc_braintree_get_order_for_payment_id
  • wc_braintree_get_payment_method_format
  • wc_braintree_get_payment_tokens
  • wc_braintree_get_products_for_conditions
  • wc_braintree_get_response_code_message
  • wc_braintree_get_template
  • wc_braintree_get_template_html
  • wc_braintree_hidden_field
  • wc_braintree_local_payment_completed
  • wc_braintree_local_payment_params
  • wc_braintree_log
  • wc_braintree_log_error
  • wc_braintree_log_info
  • wc_braintree_merchant_id
  • wc_braintree_merge_order_statuses
  • wc_braintree_move_translations
  • wc_braintree_nonce_field
  • wc_braintree_order_statuses
  • wc_braintree_order_statuses_for_registration
  • wc_braintree_output_checkout_error
  • wc_braintree_parse_xml_contents
  • wc_braintree_payment_complete_order_status
  • wc_braintree_payment_gateways
  • wc_braintree_payment_method_formats
  • wc_braintree_payment_method_title
  • wc_braintree_payment_token_field
  • wc_braintree_pre_orders_active
  • wc_braintree_private_key
  • wc_braintree_process_scheduled_local_payment
  • wc_braintree_production_active
  • wc_braintree_public_key
  • wc_braintree_save_cc_enabled
  • wc_braintree_save_customer
  • wc_braintree_set_checkout_error
  • wc_braintree_show_product_checkout_gateways
  • wc_braintree_spam_bot_field
  • wc_braintree_subscriptions_active
  • wc_braintree_update_customer_location
  • wc_braintree_webhook_check
  • wc_braintree_woocommerce_payment_token_deleted
  • wcs_braintree_account_menu_items
  • wcs_braintree_active
  • wcs_braintree_before_delete_order_item
  • wcs_braintree_billing_interval_string
  • wcs_braintree_billing_intervals
  • wcs_braintree_billing_periods
  • wcs_braintree_billing_periods_string
  • wcs_braintree_calculate_end_date
  • wcs_braintree_calculate_first_payment_date
  • wcs_braintree_calculate_next_payment_date
  • wcs_braintree_calculate_start_date
  • wcs_braintree_cart_contains_subscription
  • wcs_braintree_cart_formatted_date
  • wcs_braintree_cart_recurring_tax_html
  • wcs_braintree_cart_recurring_total_html
  • wcs_braintree_cart_shipping_total
  • wcs_braintree_cart_subtotal_string
  • wcs_braintree_cart_tax_total_html
  • wcs_braintree_cart_totals_coupon_html
  • wcs_braintree_change_payment_method_template
  • wcs_braintree_copy_address_from_order
  • wcs_braintree_copy_order_meta
  • wcs_braintree_create_order_from_subscription
  • wcs_braintree_create_renewal_order
  • wcs_braintree_create_subscription
  • wcs_braintree_frontend_interval_string
  • wcs_braintree_get_billing_schedule_string
  • wcs_braintree_get_interval_string
  • wcs_braintree_get_length_string
  • wcs_braintree_get_period_string
  • wcs_braintree_get_plan_from_product
  • wcs_braintree_get_plan_options
  • wcs_braintree_get_plans
  • wcs_braintree_get_price_string
  • wcs_braintree_get_product_price_html
  • wcs_braintree_get_recurring_cart_key
  • wcs_braintree_get_recurring_total_text
  • wcs_braintree_get_related_orders
  • wcs_braintree_get_subscription
  • wcs_braintree_get_subscription_actions
  • wcs_braintree_get_subscription_from_recurring_cart_key
  • wcs_braintree_get_subscription_status_name
  • wcs_braintree_get_subscription_statuses
  • wcs_braintree_get_subscription_statuses_for_registration
  • wcs_braintree_get_subscriptions_for_order
  • wcs_braintree_get_subscriptions_for_user
  • wcs_braintree_is_change_payment_method_request
  • wcs_braintree_localize_scripts
  • wcs_braintree_order_contains_subscription
  • wcs_braintree_order_details
  • wcs_braintree_product_is_subscription
  • wcs_braintree_subscription_cancelled
  • wcs_braintree_subscription_length_string
  • wcs_braintree_subscription_user_actions
  • wcs_braintree_subscriptions_template
  • wcs_braintree_sync_subscription_with_gateway
  • wcs_braintree_view_subscription_template
  • wcs_braintree_webhook_subscription_cancelled
  • wcs_braintree_webhook_subscription_charged_successfully
  • wcs_braintree_webhook_subscription_expired
  • wcs_braintree_webhook_subscription_past_due
   1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99  100  101  102  103  104  105  106  107  108  109  110  111  112  113  114  115  116  117  118  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134  135  136  137  138  139  140  141  142  143  144  145  146  147  148  149  150  151  152  153  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185  186  187  188  189  190  191  192  193  194  195  196  197  198  199  200  201  202  203  204  205  206  207  208  209  210  211  212  213  214  215  216  217  218  219  220  221  222  223  224  225  226  227  228  229  230  231  232  233  234  235  236  237  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269  270  271  272  273  274  275  276  277  278  279  280  281  282  283  284  285  286  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302  303  304  305  306  307  308  309  310  311  312  313  314  315  316  317  318  319  320  321  322  323  324  325  326  327  328  329  330  331  332  333  334  335  336  337  338  339  340  341  342  343  344  345  346  347  348  349  350  351  352  353  354  355  356  357  358  359  360  361  362  363  364  365  366  367  368  369  370  371  372  373  374  375  376  377  378  379  380  381  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413  414  415  416  417  418  419  420  421  422  423  424  425  426  427  428  429  430  431  432  433  434  435  436  437  438  439  440  441  442  443  444  445  446  447  448  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480  481  482  483  484  485  486  487  488  489  490  491  492  493  494  495  496  497  498  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530  531  532  533  534  535  536  537  538  539  540  541  542  543  544  545  546  547  548  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596  597  598  599  600  601  602  603  604  605  606  607  608  609  610  611  612  613  614  615  616  617  618  619  620  621  622  623  624  625  626  627  628  629  630  631  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679  680  681  682  683  684  685  686  687  688  689  690  691  692  693  694  695  696  697  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713  714  715  716  717  718  719  720  721  722  723  724  725  726  727  728  729  730  731  732  733  734  735  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751  752  753  754  755  756  757  758  759  760  761  762  763  764  765  766  767  768  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816  817  818  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  865  866  867  868  869  870  871  872  873  874  875  876  877  878  879  880  881  882  883  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931  932  933  934  935  936  937  938  939  940  941  942  943  944  945  946  947  948  949  950  951  952  953  954  955  956  957  958  959  960  961  962  963  964  965  966  967  968  969  970  971  972  973  974  975  976  977  978  979  980  981  982  983  984  985  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 
<?php

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
    return;
}

use \PaymentPlugins\WC_Braintree_Constants as Constants;

/**
 * Abstract class that is meant to be extended by Braintree payment methods.
 *
 * @version 3.0.0
 * @package Braintree/Abstracts
 */
abstract class WC_Braintree_Payment_Gateway extends WC_Payment_Gateway {

    use WC_Braintree_Settings_Trait;

    public $nonce_key;

    public $token_key;

    public $device_data_key;

    public $save_method_key;

    public $payment_type_key;

    public $config_key = '';

    /**
     * The token type used to create WC_Payment_Token objects.
     *
     * @var string
     */
    protected $token_type;

    protected $deprecated_id = '';

    /**
     *
     * @var array
     */
    protected $client_token = '';

    /**
     * Token that represents a vaulted payment method in Braintree.
     * Example: cby23j
     *
     * @var string
     */
    protected $payment_method_token = null;

    /**
     * Nonce that represents a once time use payment method.
     *
     * @var string
     */
    protected $payment_method_nonce = null;

    protected $update_payment_method_request = false;

    protected $tab_title = '';

    /**
     * Template that points to where the gateway's html is rendered.
     *
     * @var string
     */
    public $template = '';

    /**
     *
     * @var bool Indicator for when payment is being processed.
     */
    public $processing_payment;

    /**
     * @var array
     * @since 3.2.3
     */
    protected $order_totals
        = array(
            'item'     => array(
                'subtotal'  => 0,
                'tax_total' => 0
            ),
            'discount' => array(
                'subtotal'  => 0,
                'tax_total' => 0
            ),
            'fee'      => array(
                'subtotal'  => 0,
                'tax_total' => 0
            ),
            'shipping' => array(
                'subtotal'  => 0,
                'tax_total' => 0
            ),
            'tax'      => array(
                'subtotal'  => 0,
                'tax_total' => 0
            )
        );

    /**
     * @var int[]
     * @since 3.2.4
     */
    protected $line_item_validations
        = array(
            'commodityCode'  => 12,
            'description'    => 127,
            'discountAmount' => 2,
            'name'           => 35,
            'productCode'    => 12,
            'taxAmount'      => 2,
            'totalAmount'    => 2,
            'unitAmount'     => 4,
            'unitOfMeasure'  => 12,
            'unitTaxAmount'  => 2
        );

    /**
     * @var bool
     * @since 3.2.5
     */
    protected $has_digital_wallet = false;

    /**
     * @var WC_Braintree_Product_Gateway_Option
     * @since 3.2.7
     */
    public $product_gateway_option;

    /**
     * Initialize static functions
     */
    public static function init() {
        add_action( 'woocommerce_order_status_completed', array( __CLASS__, 'capture_transaction_from_status' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled', array( __CLASS__, 'void_transaction_from_status' ), 10, 2 );
        add_filter( 'woocommerce_available_payment_gateways', array( __CLASS__, 'available_payment_gateways' ) );
        add_action( 'woocommerce_process_shop_subscription_meta', array( __CLASS__, 'process_shop_subscription_meta' ), 10, 2 );
        add_action( 'woocommerce_scheduled_subscription_payment', array( __CLASS__, 'deprecated_subscription_check' ), - 1000 );
    }

    /**
     *
     * @var \Braintree\Gateway
     */
    public $gateway;

    /**
     * WC_Braintree_Payment_Gateway constructor.
     */
    public function __construct() {
        $this->set_supports();
        $this->init_form_fields();
        $this->init_settings();
        $this->add_hooks();
        $this->connect();
        $this->has_fields       = true;
        $this->nonce_key        = $this->id . '_nonce_key';
        $this->token_key        = $this->id . '_token_key';
        $this->device_data_key  = $this->id . '_device_data';
        $this->save_method_key  = $this->id . '_save_method';
        $this->payment_type_key = $this->id . '_payment_type';
        $this->config_key       = $this->id . '_config_data';
        $this->title            = $this->get_option( 'title_text' );
        $this->description      = $this->get_option( 'description' );
    }

    /**
     * Add all standard filters
     */
    public function add_hooks() {
        add_action( 'woocommerce_settings_checkout_' . $this->id, array( $this, 'enqueue_admin_scripts' ) );
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
        add_action( 'woocommerce_subscriptions_pre_update_payment_method', array( $this, 'pre_update_payment_method' ), 10, 2 );
        add_action( 'wc_braintree_payment_token_deleted_' . $this->id, array( $this, 'delete_payment_method' ), 10, 2 );
        add_filter( 'woocommerce_subscription_payment_meta', array( $this, 'subscription_payment_meta' ), 10, 2 );
        add_action( 'woocommerce_scheduled_subscription_payment_' . $this->id, array( $this, 'process_subscription_payment' ), 10, 2 );
        add_action( 'woocommerce_subscription_failing_payment_method_updated_' . $this->id, array( $this, 'update_failing_payment_method' ), 10, 2 );
        add_filter( 'wc_braintree_admin_settings_tabs', array( $this, 'admin_settings_tabs' ) );
        add_action( 'wc_braintree_before_process_order_' . $this->id, array( $this, 'pre_order_before_process_order' ) );
        add_action( 'wc_braintree_before_process_order_' . $this->id, array( $this, 'wcs_before_process_order' ) );
        add_action( 'wc_braintree_before_process_order_' . $this->id, array( $this, 'wcs_braintree_before_process_order' ) );
        /**
         *
         * @since 3.0.6
         */
        add_action( 'wc_pre_orders_process_pre_order_completion_payment_' . $this->id, array( $this, 'process_pre_order_payment' ) );
    }

    public function set_supports() {
        $this->supports = array(
            'tokenization',
            'subscriptions',
            'products',
            'add_payment_method',
            'subscription_cancellation',
            'multiple_subscriptions',
            'subscription_amount_changes',
            'subscription_date_changes',
            'default_credit_card_form',
            'refunds',
            'pre-orders',
            'subscription_payment_method_change_admin',
            'subscription_reactivation',
            'subscription_suspension',
            'subscription_payment_method_change_customer',
            'wc_braintree_fees',
            'wc_braintree_subscriptions',
            'wc_braintree_subscriptions_change_payment_method',
        );
    }

    /**
     * Wrapper for the WC_Payment_Gateway::is_available function. A filter is added so merchants
     * can add custom logic for determining when the gateway should be available.
     *
     * @return bool|mixed|void
     */
    public function is_available() {
        /**
         * @param bool
         * @param WC_Braintree_Payment_Gateway
         *
         * @since 3.2.19
         */
        return apply_filters( 'wc_braintree_gateway_is_available', parent::is_available(), $this );
    }

    /**
     *
     * @param string $env
     */
    public function connect( $env = '' ) {
        try {
            $this->gateway = new \Braintree\Gateway( wc_braintree_connection_settings( $env ) );
        } catch ( \Braintree\Exception $e ) {
            wc_braintree_log_info( sprintf( __( 'Error setting up %1$s. Reason: %2$s', 'woo-payment-gateway' ), $this->method_title,
                $e->getMessage() ) );
        }
    }

    public function payment_fields() {
        $methods = is_add_payment_method_page() ? array() : $this->get_tokens();
        $this->output_display_items( 'checkout' );
        $this->enqueue_frontend_scripts( braintree()->scripts() );
        wc_braintree_get_template(
            'checkout/braintree-payment-method.php',
            array(
                'methods'     => $methods,
                'has_methods' => (bool) $methods,
                'gateway'     => $this,
            )
        );
    }

    /**
     * Delete a payment method in the Braintree gateway.
     *
     * @param int              $token_id
     * @param WC_Payment_Token $token
     */
    public function delete_payment_method( $token_id, $token ) {
        try {
            $this->connect( $token->get_meta( 'environment' ) );
            $response = $this->gateway->paymentMethod()->delete( $token->get_token() );
            if ( ! $response->success ) {
                wc_braintree_log_error( sprintf( __( 'Braintree payment token %1$s not deleted in Braintree gateway. Reason: %2$s',
                    'woo-payment-gateway' ), $token->get_token(), wc_braintree_errors_from_object( $response ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            wc_braintree_log_error( sprintf( __( 'Braintree payment token %1$s not deleted in Braintree gateway. Reason: %2$s',
                'woo-payment-gateway' ), $token->get_token(), wc_braintree_errors_from_object( $e ) ) );
        }
        $this->connect();
    }

    /**
     *
     * @param WC_Subscription $subscription
     * @param string          $new_payment_method
     */
    public function pre_update_payment_method( $subscription, $new_payment_method ) {
        if ( $new_payment_method === $this->id ) {
            $this->update_payment_method_request = true;
        }
    }

    /**
     *
     * @param array           $payment_meta
     * @param WC_Subscription $subscription
     */
    public function subscription_payment_meta( $payment_meta, $subscription ) {
        $payment_meta[ $this->id ] = array(
            'post_meta' => array(
                Constants::PAYMENT_METHOD_TOKEN => array(
                    'value' => $this->get_order_meta_data( Constants::PAYMENT_METHOD_TOKEN, $subscription ),
                    'label' => __( 'Payment Method Token', 'woo-payment-gateway' ),
                ),
            ),
        );

        return $payment_meta;
    }

    public function generate_button_demo_html( $key, $data ) {
        $field_key = $this->get_field_key( $key );
        $data      = wp_parse_args(
            $data,
            array(
                'title'       => '',
                'class'       => '',
                'style'       => '',
                'description' => '',
                'desc_tip'    => false,
                'id'          => 'wc-braintree-button-demo',
            )
        );
        ob_start();
        include braintree()->plugin_path() . 'includes/admin/views/button-demo.php';

        return ob_get_clean();
    }

    public function admin_options() {
        $this->output_settings_nav();
        do_action( 'wc_braintree_admin_options', $this );
        printf( '<input type="hidden" id="wc_braintree_prefix" name="wc_braintree_prefix" value="%1$s"/>', $this->get_prefix() );
        echo '<div class="wc-braintree-settings-container ' . $this->id . '">';
        parent::admin_options();
        echo '</div>';
    }

    public function enqueue_admin_scripts() {
    }

    /**
     *
     * @param WC_Braintree_Frontend_Scripts $scripts
     */
    public function enqueue_frontend_scripts( $scripts ) {
        global $wp;
        if ( is_checkout() && ! is_order_received_page() ) {
            $this->enqueue_checkout_scripts( $scripts );
        }
        if ( is_add_payment_method_page() && ! isset( $wp->query_vars['payment-methods'] ) ) {
            $this->enqueue_add_payment_method_scripts( $scripts );
        }
        if ( is_cart() ) {
            $this->enqueue_cart_scripts( $scripts );
        }
        if ( is_product() ) {
            $this->enqueue_product_scripts( $scripts );
        }
        if ( wc_braintree_subscriptions_active() && wcs_braintree_is_change_payment_method_request() ) {
            $this->enqueue_checkout_scripts( $scripts );
        }
    }

    /**
     *
     * @param WC_Braintree_Frontend_Scripts $scripts
     */
    public function enqueue_checkout_scripts( $scripts ) {
    }

    /**
     *
     * @param WC_Braintree_Frontend_Scripts $scripts
     */
    public function enqueue_add_payment_method_scripts( $scripts ) {
        $this->enqueue_checkout_scripts( $scripts );
    }

    /**
     *
     * @param WC_Braintree_Frontend_Scripts $scripts
     */
    public function enqueue_cart_scripts( $scripts ) {
    }

    /**
     *
     * @param WC_Braintree_Frontend_Scripts $scripts
     */
    public function enqueue_product_scripts( $scripts ) {
    }

    /**
     * @param WC_Braintree_Frontend_Scripts $scripts
     *
     * @since 3.2.5
     */
    public function enqueue_mini_cart_scripts( $scripts ) {
        if ( ! wp_script_is( $scripts->get_handle( 'mini-cart' ) ) ) {
            $scripts->enqueue_script( 'mini-cart', $scripts->assets_url( 'js/frontend/mini-cart.js' ),
                apply_filters( 'wc_braintree_mini_cart_deps', array(
                    $scripts->get_handle( 'client-manager' ),
                    $scripts->get_handle( 'data-collector-v3' )
                ), $scripts ) );
        }
        wp_localize_script( $scripts->get_handle( 'mini-cart' ), "wc_{$this->id}_mini_cart_params", $this->get_localized_standard_params() );
    }

    public function init_form_fields() {
        $this->form_fields = apply_filters(
            'wc_' . $this->id . '_form_fields',
            include WC_BRAINTREE_PATH . 'includes/gateways/settings/' .
                    str_replace( 'braintree_', '', $this->id ) . '-settings.php',
            $this
        );
        if ( wcs_braintree_active() && $this->supports( 'subscriptions' ) ) {
            $this->form_fields = array_merge(
                $this->form_fields,
                apply_filters(
                    'wcs_braintree_subscription_form_fields',
                    include WC_BRAINTREE_PATH .
                            '/includes/gateways/settings/subscription-settings.php',
                    $this
                )
            );
        }
    }

    /**
     * Generate a client token
     *
     * @return string
     */
    public function generate_client_token() {
        $client_token = '';
        $args         = array();
        try {
            $merchant_account = wc_braintree_get_merchant_account();
            if ( ! empty( $merchant_account ) ) {
                $args['merchantAccountId'] = $merchant_account;
            }
            $client_token = $this->gateway->clientToken()->generate( $args );
        } catch ( \Braintree\Exception $e ) {
            wc_braintree_log_error( sprintf( __( 'Error creating client token. Exception: %1$s', 'woo-payment-gateway', get_class( $e ) ) ) );
        }

        return $client_token;
    }

    public function process_payment( $order_id ) {
        $order = wc_get_order( $order_id );
        if ( $this->update_payment_method_request && wcs_braintree_active() && wcs_is_subscription( $order ) ) {
            return $this->process_change_payment_request( $order );
        }
        do_action( 'wc_braintree_before_process_order_' . $this->id, $order );

        if ( wc_notice_count( 'error' ) > 0 ) {
            return array( 'result' => 'failure' );
        }

        $this->processing_payment = true;

        if ( $order->get_total() == 0 || $this->pre_order_with_payment_later( $order ) ) {
            $this->save_zero_total_order_meta( $order );
            if ( $this->pre_order_with_payment_later( $order ) ) {
                WC_Pre_Orders_Order::mark_order_as_pre_ordered( $order );
            } else {
                $order->payment_complete();
            }
            WC()->cart->empty_cart();
            $this->remove_session_checkout_vars();
            $this->do_post_payment_processing( $order );

            return $this->order_success_result( $order );
        }

        $this->add_order_general_args( $args, $order )
             ->add_order_options( $args, $order )
             ->add_order_descriptors( $args, $order )
             ->add_order_device_data( $args, $order )
             ->add_order_customer_id( $args, $order );

        if ( $this->use_saved_method() ) {
            $args['paymentMethodToken'] = $this->get_payment_method_token();
        } else {
            $args['paymentMethodNonce'] = $this->get_payment_method_nonce();
        }

        $args = apply_filters( 'wc_braintree_order_transaction_args', $args, $order, $this->id );

        $result = array();
        wc_braintree_log_info( sprintf( __( 'Processing payment for order %1$s. Transaction args: %2$s', 'woo-payment-gateway' ), $order_id,
            print_r( $args, true ) ) );
        try {
            $response = $this->gateway->transaction()->sale( $args );
            if ( $response->success ) {
                $this->save_order_meta( $response->transaction, $order );
                $this->record_transaction();
                if ( isset( $args['options']['storeInVaultOnSuccess'] ) && $args['options']['storeInVaultOnSuccess'] == true ) {
                    $token = $this->get_payment_token( $this->get_payment_method_from_transaction( $response->transaction ) );
                    $token->set_user_id( $order->get_customer_id() );
                    $token->save();
                    // set token in case downstream processes need access to it.
                    $this->payment_method_token = $token->get_token();
                    WC_Payment_Tokens::set_users_default( $order->get_customer_id(), $token->get_id() );
                }
                if ( braintree()->fraud_settings->is_active( 'kount_enabled' ) && isset( $response->transaction->riskData ) ) {
                    $this->perform_kount_actions( $order, $response->transaction, $args );
                } else {
                    $this->payment_complete_actions( $order, $response->transaction, $args );
                }
                $this->remove_session_checkout_vars();
                WC()->cart->empty_cart();
                $this->do_post_payment_processing( $order );
                $result = $this->order_success_result( $order );
            } else {
                throw new Exception( wc_braintree_errors_from_object( $response ) );
            }
        } catch ( Exception $e ) {
            if ( $e instanceof \Braintree\Exception ) {
                wc_braintree_log_error( sprintf( __( 'Error processing payment for order %1$s. Exception: %2$s. Transaction args: %3$s',
                    'woo-payment-gateway' ), $order->get_id(), get_class( $e ), print_r( $args, true ) ) );
                $msg = wc_braintree_errors_from_object( $e );
            } else {
                $msg = $e->getMessage();
            }
            $notice = sprintf( __( 'There was an error processing your payment. Reason: %1$s', 'woo-payment-gateway' ), $msg );
            $order->add_order_note( sprintf( __( 'Error processing payment. Reason: %1$s', 'woo-payment-gateway' ), $msg ) );
            $order->update_status( 'failed' );
            wc_braintree_set_checkout_error();
            wc_add_notice( $notice, 'error' );
            $result = $this->order_error_result( $notice );
        }

        return $result;
    }

    /**
     * Handles order status once payment has been captured or authorized.
     *
     * @param WC_Order               $order
     * @param \Braintree\Transaction $transaction
     * @param array                  $args
     *
     * @since 3.0.8
     */
    public function payment_complete_actions( $order, $transaction, $args ) {
        if ( $args['options']['submitForSettlement'] ) {
            // payment was captured, so call payment complete.
            $order->payment_complete( $transaction->id );
        } else {
            // payment is authorized only. Must be captured at a later time.
            $order_status = $this->get_option( 'order_status' );
            $order->update_status( apply_filters( 'wc_braintree_authorized_order_status', 'default' === $order_status ? 'on-hold' : $order_status,
                $order, $this ) );
        }
        if ( apply_filters( 'wc_braintree_add_order_success_note', true, $order, $transaction, $this ) ) {
            $order->add_order_note( sprintf( __( 'Order %1$s in Braintree: Transaction ID: %2$s. Payment method: %3$s', 'woo-payment-gateway' ),
                $args['options']['submitForSettlement'] ? __( 'captured', 'woo-payment-gateway' ) : __( 'authorized', 'woo-payment-gateway' ),
                $order->get_transaction_id(), $order->get_payment_method_title() ) );
        }
    }

    /**
     * If the payment_method_token has been set then return it.
     * If not look for the token in the $_POST.
     */
    public function get_payment_method_token() {
        if ( $this->payment_method_token ) {
            return $this->payment_method_token;
        }
        if ( ! empty( $_POST[ $this->token_key ] ) ) {
            return wc_clean( $_POST[ $this->token_key ] );
        }
    }

    /**
     * If the payment_method_nonce has been set, then return it.
     * If not look for the nonce in the $_POST.
     */
    public function get_payment_method_nonce() {
        if ( $this->payment_method_nonce ) {
            return $this->payment_method_nonce;
        }

        return ! empty( $_POST[ $this->nonce_key ] ) ? wc_clean( $_POST[ $this->nonce_key ] ) : '';
    }

    /**
     *
     * @param string $value
     */
    public function set_payment_method_nonce( $value ) {
        $this->payment_method_nonce = $value;
    }

    /**
     *
     * @param string $value
     */
    public function set_payment_method_token( $value ) {
        $this->payment_method_token = $value;
    }

    /**
     *
     * @param WC_Order $order
     */
    public function get_customer_attributes( $order ) {
        return array(
            'firstName' => $order->get_billing_first_name(),
            'lastName'  => $order->get_billing_last_name(),
            'phone'     => $order->get_billing_phone(),
            'email'     => $order->get_billing_email(),
            'company'   => $order->get_billing_company(),
        );
    }

    /**
     *
     * @param WC_Order $order
     */
    public function get_order_id( $order ) {
        return sprintf( '%1$s%2$s%3$s', $this->get_option( 'order_prefix' ), $order->get_order_number(), $this->get_option( 'order_suffix' ) );
    }

    /**
     *
     * @deprecated
     */
    public function get_descriptors() {
        $args = braintree()->descriptor_settings->is_active( 'enabled' ) ? array(
            'name'  => braintree()->descriptor_settings->get_option( 'descriptor_name' ),
            'phone' => braintree()->descriptor_settings->get_option( 'descriptor_phone' ),
            'url'   => braintree()->descriptor_settings->get_option( 'descriptor_url' ),
        ) : array();
        foreach ( $args as $k => $v ) {
            if ( empty( $v ) ) {
                unset( $args[ $k ] );
            }
        }

        return $args;
    }

    /**
     *
     * @param array    $args
     * @param WC_Order $order
     *
     * @since 3.2.1
     */
    public function add_order_descriptors( &$args, $order ) {
        $descriptors = braintree()->descriptor_settings->is_active( 'enabled' ) ? array(
            'name'  => braintree()->descriptor_settings->get_option( 'descriptor_name' ),
            'phone' => braintree()->descriptor_settings->get_option( 'descriptor_phone' ),
            'url'   => braintree()->descriptor_settings->get_option( 'descriptor_url' ),
        ) : array();
        foreach ( $descriptors as $k => $v ) {
            if ( empty( $v ) ) {
                unset( $args[ $k ] );
            }
        }
        $args['descriptor'] = $descriptors;

        return $this;
    }

    /**
     *
     * @param WC_Order $order
     */
    public function get_order_options( $order ) {
        $options = array(
            'submitForSettlement'   => apply_filters( 'wc_braintree_transaction_submit_for_settlement',
                $this->get_option( 'charge_type' ) === 'capture', $this ),
            'storeInVaultOnSuccess' => $this->should_save_payment_method(),
        );

        return $options;
    }

    public function add_order_options( &$args, $order ) {
        $args['options'] = array(
            'submitForSettlement'   => apply_filters( 'wc_braintree_transaction_submit_for_settlement',
                $this->get_option( 'charge_type' ) === 'capture', $this ),
            'storeInVaultOnSuccess' => $this->should_save_payment_method(),
        );

        return $this;
    }

    public function get_device_data() {
        if ( ! empty( $_POST[ $this->device_data_key ] ) ) {
            return stripslashes( $_POST[ $this->device_data_key ] );
        }
    }

    /**
     * @param $args
     * @param $order
     *
     * @since 3.2.1
     *
     * @return $this
     */
    public function add_order_device_data( &$args, $order ) {
        if ( ( $data = $this->get_device_data() ) ) {
            $args['deviceData'] = $data;
        }

        return $this;
    }

    /**
     * Return true if the payment method used on the checkout page should be saved.
     * Payment methods
     * should only be saved if the customer's wants to save the method or a new method is being used and
     * there are subscriptions associated with the order.
     */
    public function should_save_payment_method() {
        if ( ! empty( $_POST["wc-{$this->id}-new-payment-method"] ) ) {
            return true;
        }

        return ( ! empty( $_POST[ $this->save_method_key ] ) && ! $this->use_saved_method() )
               || ( wcs_braintree_active() && ! $this->use_saved_method()
                    && ( WC_Subscriptions_Cart::cart_contains_subscription() || wcs_cart_contains_renewal() )
                    && $this->supports( 'subscriptions' ) );
    }

    /**
     * Return true if a saved payment method should be used.
     */
    public function use_saved_method() {
        if ( ! empty( $_POST["wc-{$this->id}-payment-token"] ) ) {
            $token = WC_Payment_Tokens::get( wc_clean( $_POST["wc-{$this->id}-payment-token"] ) );

            if ( $token ) {
                $this->payment_method_token = $token->get_token();
            }
        }

        return ( ! empty( $_POST[ $this->payment_type_key ] ) && $_POST[ $this->payment_type_key ] === 'token' ) || $this->payment_method_token;
    }

    public function order_error_result( $msg = '' ) {
        return array(
            'result'                => 'failure',
            'redirect'              => '',
            'braintreeErrorMessage' => $msg
        );
    }

    /**
     *
     * @param WC_Order $order
     */
    public function order_success_result( $order ) {
        return array(
            'result'   => 'success',
            'redirect' => $this->get_return_url( $order ),
        );
    }

    /**
     * Save transaction data as meta data of the order.
     *
     * @param \Braintree\Transaction $transaction
     * @param WC_Order               $order
     */
    public function save_order_meta( $transaction, $order ) {
        $token = $this->get_payment_token( $this->get_payment_method_from_transaction( $transaction ) );
        $token->add_meta_data_to_order( $order );
        $order->set_payment_method_title( $token->get_payment_method_title() );
        $order->set_transaction_id( $transaction->id );
        $order->add_meta_data( Constants::VERSION, braintree()->version, true );
        $order->add_meta_data( Constants::MERCHANT_ACCOUNT_ID, $transaction->merchantAccountId, true );
        $order->add_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token->get_token(), true );
        $order->add_meta_data( Constants::ENVIRONMENT, wc_braintree_environment(), true );
        $order->add_meta_data( Constants::TRANSACTION_STATUS, $transaction->status, true );
        if ( $transaction->status === \Braintree\Transaction::AUTHORIZED ) {
            $order->add_meta_data( Constants::AUTH_EXP, $transaction->authorizationExpiresAt->getTimestamp(), true );
        }

        if ( wcs_braintree_active() && wcs_order_contains_subscription( $order ) ) {
            $subscriptions = wcs_get_subscriptions_for_order( $order );
            foreach ( $subscriptions as $subscription ) {
                $this->save_order_meta( $transaction, $subscription );
            }
        }
        if ( wc_braintree_subscriptions_active() && wcs_braintree_order_contains_subscription( $order ) ) {
            $subscriptions = wcs_braintree_get_subscriptions_for_order( $order );
            foreach ( $subscriptions as $subscription ) {
                $this->save_order_meta( $transaction, $subscription );
            }
        }

        /**
         * @param WC_Order                     $order
         * @param \Braintree\Transaction       $transaction
         * @param WC_Braintree_Payment_Gateway $this
         *
         * @since 3.2.11
         */
        do_action( 'wc_braintree_save_order_meta', $order, $transaction, $this );

        $order->save();
    }

    /**
     * Return the payment method details from the tranaction.
     *
     * @param \Braintree\Transaction $transaction
     */
    abstract public function get_payment_method_from_transaction( $transaction );

    /**
     *
     * @param mixed $method
     *
     * @return WC_Payment_Token_Braintree
     */
    public function get_payment_token( $method ) {
        $class_name = 'WC_Payment_Token_Braintree_' . $this->get_token_type();
        if ( class_exists( $class_name ) ) {
            /**
             *
             * @var WC_Payment_Token_Braintree $token
             */
            $token = new $class_name();
            $token->init_from_payment_method( $method );
            $token->set_gateway_id( $this->id );
            $token->set_user_id( get_current_user_id() );
            $token->set_format( $this->get_option( 'method_format' ) );
            $token->set_environment( wc_braintree_environment() );

            return $token;
        }
    }

    public function get_token_type() {
        return apply_filters( 'wc_braintree_gateway_token_type', $this->token_type );
    }

    /**
     *
     * @param WC_Order $order
     */
    public function save_zero_total_order_meta( $order ) {
        $token = $this->get_token( $this->get_payment_method_token(), $order->get_customer_id() );
        $order->add_meta_data( Constants::VERSION, braintree()->version, true );
        $order->add_meta_data( Constants::MERCHANT_ACCOUNT_ID, wc_braintree_get_merchant_account( $order->get_currency() ), true );
        $order->add_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token->get_token(), true );
        $order->add_meta_data( '_wc_braintree_environment', wc_braintree_environment(), true );
        $order->set_payment_method_title( $token->get_payment_method_title() );

        if ( wcs_braintree_active() ) {
            $subscriptions = wcs_get_subscriptions_for_order( $order );
            foreach ( $subscriptions as $subscription ) {
                $this->save_zero_total_order_meta( $subscription );
            }
        }
        if ( wc_braintree_subscriptions_active() && wcs_braintree_order_contains_subscription( $order ) ) {
            $subscriptions = wcs_braintree_get_subscriptions_for_order( $order );
            foreach ( $subscriptions as $subscription ) {
                $this->save_zero_total_order_meta( $subscription );
            }
        }
        /**
         * @param WC_Order                     $order
         * @param \Braintree\Transaction       $transaction
         * @param WC_Braintree_Payment_Gateway $this
         *
         * @since 3.2.11
         */
        do_action( 'wc_braintree_save_zero_total_order_meta', $order, $this );

        $order->save();
    }

    public function process_refund( $order_id, $amount = null, $reason = '' ) {
        $order   = wc_get_order( $order_id );
        $id      = $order->get_transaction_id();
        $message = __( 'Error processing refund. Reason: %1$s', 'woo-payment-gateway' );
        try {
            if ( empty( $id ) ) {
                throw new InvalidArgumentException( sprintf( __( 'The transaction ID for order %1$s is blank. A refund cannot be processed unless there is a valid transaction associated with the order.',
                    'woo-payment-gateway' ), $order_id ) );
            }
            $this->connect( wc_braintree_get_order_environment( $order ) );
            $response = $this->gateway->transaction()->refund( $id, $amount );
            if ( $response->success ) {
                $transaction = $response->transaction;
                $order->update_meta_data( Constants::TRANSACTION_STATUS, $transaction->status );
                $order->add_order_note(
                    sprintf(
                        __( 'Refund successful in Braintree. Amount: %1$s. Refund ID: %2$s', 'woo-payment-gateway' ),
                        wc_price( $amount, array( 'currency' => $order->get_currency() ) ), $response->transaction->id
                    )
                );
                $order->save();

                return true;
            } else {
                $errors = $response->errors->forKey( 'transaction' );
                if ( $errors ) {
                    foreach ( $errors->shallowAll() as $error ) {
                        if ( $error->code === '91506' ) {
                            $message .= ' ' . __( 'If you wish to cancel the transaction you can set the order\'s status to cancelled or use the void option.',
                                    'woo-payment-gateway' );
                        }
                    }
                }

                return new WP_Error( 'refund-error', sprintf( $message, wc_braintree_errors_from_object( $response ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            return new WP_Error( 'refund-error', sprintf( $message, wc_braintree_errors_from_object( $e ) ) );
        } catch ( Exception $e ) {
            return new WP_Error( 'refund-error',
                sprintf( __( 'Exception thrown while issuing refund. Reason: %1$s Exception class: %2$s', 'woo-payment-gateway' ), $e->getMessage(),
                    get_class( $e ) ) );
        }
    }

    /**
     * Capture the provided amount.
     *
     * @param float    $amount
     * @param WC_Order $order
     *
     * @return bool|WP_Error
     */
    public function capture_charge( $amount, $order ) {
        $id = $order->get_transaction_id();
        try {
            $response = $this->gateway->transaction()->submitForSettlement( $id, $amount );
            if ( $response->success ) {
                $this->save_order_meta( $response->transaction, $order );

                // we don't want order_status option to be called here since capture is happening via admin.'
                remove_filter( 'woocommerce_payment_complete_order_status', 'wc_braintree_payment_complete_order_status', 99 );

                $order->payment_complete( $id );
                $order->add_order_note(
                    sprintf(
                        __( 'Transaction submitted for settlement in Braintree. Amount %1$s', 'woo-payment-gateway' ),
                        wc_price(
                            $amount,
                            array(
                                'currency' => $order->get_currency(),
                            )
                        )
                    )
                );

                return true;
            } else {
                return new WP_Error( 'capture-error', sprintf( __( 'There was an error capturing the charge. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            return new WP_Error( 'capture-error', sprintf( __( 'There was an error capturing the charge. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ) );
        }
    }

    /**
     *
     * @param WC_Order $order
     *
     * @return bool|WP_Error
     */
    public function void_charge( $order ) {
        $id = $order->get_transaction_id();
        try {
            $response = $this->gateway->transaction()->void( $id );
            if ( $response->success ) {
                $this->save_order_meta( $response->transaction, $order );
                $order->update_status( 'cancelled' );
                $order->add_order_note( sprintf( __( 'Transaction %1$s has been voided in Braintree.', 'woo-payment-gateway' ), $id ) );

                return true;
            } else {
                return new WP_Error( 'capture-error',
                    sprintf( __( 'There was an error voiding the transaction. Reason: %1$s', 'woo-payment-gateway' ),
                        wc_braintree_errors_from_object( $response ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            return new WP_Error( 'capture-error', sprintf( __( 'There was an error voiding the transaction. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ) );
        }
    }

    /**
     * @param array         $args
     * @param WC_Order|flse $order
     *
     * @return array|string[]
     */
    public function add_payment_method( $args = array(), $order = false ) {
        $nonce    = isset( $_POST[ $this->nonce_key ] ) ? wc_clean( $_POST[ $this->nonce_key ] ) : $this->payment_method_nonce;
        $user_id  = $order ? $order->get_customer_id() : get_current_user_id();
        $customer = new WC_Customer( $user_id );
        if ( ! $nonce ) {
            return array( 'result' => 'error' );
        }
        try {
            /**
             * Action added so other plugins can throw errors before add payment method starts.
             *
             * Example: plugin validates captcha and throws exception if invalid.
             *
             * @since 3.0.6
             */
            do_action( 'wc_braintree_before_add_payment_method', $this );

            // first check that the customer has a braintree vault ID.
            if ( ! ( $customer_id = wc_braintree_get_customer_id( $user_id ) ) ) {
                $customer_id = $this->create_customer( $customer );
                if ( is_wp_error( $customer_id ) ) {
                    throw new Exception( $customer_id->get_error_message() );
                }
            }
            $args     = array_merge(
                array(
                    'customerId'         => $customer_id,
                    'paymentMethodNonce' => $nonce,
                    'deviceData'         => $this->get_device_data(),
                    'options'            => array(
                        'failOnDuplicatePaymentMethod'  => $this->is_active( 'fail_on_duplicate' ),
                        'verificationMerchantAccountId' => wc_braintree_get_merchant_account( $order ? $order->get_currency() : '' ),
                        'makeDefault'                   => true,
                        'verifyCard'                    => true,
                    ),
                    'cardholderName'     => sprintf( '%1$s %2$s', $customer->get_first_name(), $customer->get_last_name() ),
                    'billingAddress'     => isset( $_POST['billing_address_1'] ) ? array( 'streetAddress' => wc_clean( $_POST['billing_address_1'] ) ) : array(),
                ),
                $args
            );
            $args     = apply_filters( 'wc_braintree_add_payment_method_args', $args, $this );
            $response = $this->gateway->paymentMethod()->create( $args );
            if ( $response->success ) {
                $token = $this->get_payment_token( $response->paymentMethod );
                $token->save();
                WC_Payment_Tokens::set_users_default( $user_id, $token->get_id() );
                $this->payment_method_token = $token->get_token();
                /**
                 * Perform address cleanup in Braintree.
                 * Address can build up over time and if they exceed gateway limit, can cause errors.
                 */
                if ( @isset( $response->paymentMethod->billingAddress ) ) {
                    if ( ! is_null( ( $response->paymentMethod->billingAddress->id ) ) ) {
                        try {
                            $this->gateway->address()->delete( $customer_id, $response->paymentMethod->billingAddress->id );
                        } catch ( \Braintree\Exception $e ) {
                            wc_braintree_log_error(
                                sprintf(
                                    __(
                                        'Error deleting payment method address. This error was caught gracefully
                                and not shown to the customer. You can delete address %1$s in your Braintree gateway.',
                                        'woo-payment-gateway'
                                    ),
                                    $response->paymentMethod->billingAddress->id
                                )
                            );
                        }
                    }
                }

                return array(
                    'result'   => 'success',
                    'redirect' => wc_get_account_endpoint_url( 'payment-methods' ),
                );
            } else {
                wc_add_notice( sprintf( __( 'There was an error saving your payment method. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ), 'error' );

                return array( 'result' => 'error' );
            }
        } catch ( \Braintree\Exception $e ) {
            wc_add_notice( sprintf( __( 'There was an error saving your payment method. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ), 'error' );

            return array( 'result' => 'error' );
        } catch ( Exception $e ) {
            wc_add_notice( sprintf( __( 'There was an error saving your payment method. Reason: %1$s', 'woo-payment-gateway' ), $e->getMessage() ),
                'error' );

            return array( 'result' => 'error' );
        }
    }

    /**
     *
     * @param string $id
     *
     * @return WP_Error|\Braintree\Transaction
     */
    public function fetch_transaction( $id, $env = '' ) {
        try {
            $this->connect( $env );
            $transaction = $this->gateway->transaction()->find( $id );

            return $transaction;
        } catch ( \Braintree\Exception $e ) {
            return new WP_Error( 'transaction-error',
                sprintf( 'Error fetching transaction. Exception: %s. Message: %s', get_class( $e ), $e->getMessage() ) );
        } catch ( Exception $e ) {
            return new WP_Error( 'transaction-error',
                sprintf( 'Error fetching transaction. Exception: %s. Message: %s', get_class( $e ), $e->getMessage() ) );
        }
        $this->connect();
    }

    /**
     *
     * @param int      $order_id
     * @param WC_Order $order
     */
    public static function capture_transaction_from_status( $order_id, $order ) {
        if ( $order->get_meta( Constants::TRANSACTION_STATUS ) === \Braintree\Transaction::AUTHORIZED ) {
            $payment_method   = $order->get_payment_method();
            $payment_gateways = WC()->payment_gateways()->payment_gateways();
            $gateway          = isset( $payment_gateways[ $payment_method ] ) ? $payment_gateways[ $payment_method ] : null;
            if ( $gateway && ( $gateway instanceof WC_Braintree_Payment_Gateway ) && ! $gateway->processing_payment ) {
                $gateway->capture_charge( $order->get_total(), $order );
            }
        }
    }

    /**
     *
     * @param int      $order_id
     * @param WC_Order $order
     */
    public static function void_transaction_from_status( $order_id, $order ) {
        $statuses = array(
            \Braintree\Transaction::AUTHORIZED,
            \Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT,
            \Braintree\Transaction::SETTLEMENT_PENDING,
        );
        if ( in_array( $order->get_meta( Constants::TRANSACTION_STATUS ), $statuses ) ) {
            $payment_method   = $order->get_payment_method();
            $payment_gateways = WC()->payment_gateways()->payment_gateways();
            $gateway          = isset( $payment_gateways[ $payment_method ] ) ? $payment_gateways[ $payment_method ] : null;
            if ( $gateway && ( $gateway instanceof WC_Braintree_Payment_Gateway ) ) {
                $gateway->void_charge( $order );
            }
        }
    }

    public function get_localized_standard_params() {
        return array(
            'gateway'                     => $this->id,
            'environment'                 => wc_braintree_environment(),
            'advanced_fraud'              => array( 'enabled' => braintree()->fraud_settings->is_active( 'enabled' ) ),
            'token_selector'              => $this->token_key,
            'nonce_selector'              => $this->nonce_key,
            'device_data_selector'        => $this->device_data_key,
            'payment_type_selector'       => $this->payment_type_key,
            'tokenized_response_selector' => $this->id . '_tokenized_response',
            'roles'                       => array( 'admin' => current_user_can( 'administrator' ) ),
            '_wp_rest_nonce'              => wp_create_nonce( 'wp_rest' ),
            'user_id'                     => get_current_user_id(),
            'messages'                    => array(
                'terms'          => __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' ),
                'required_field' => __( 'Please fill out all required fields.', 'woo-payment-gateway' ),
            ),
            'locale'                      => $this->get_locale(),
            'routes'                      => array(
                'checkout'         => WC_Braintree_Rest_API::get_endpoint( braintree()->rest_api->checkout->rest_uri() . '/checkout' ),
                'add_to_cart'      => WC_Braintree_Rest_API::get_endpoint( braintree()->rest_api->cart->rest_uri() . '/cart' ),
                'shipping'         => WC_Braintree_Rest_API::get_endpoint( braintree()->rest_api->cart->rest_uri() . '/cart/shipping' ),
                'shipping_address' => WC_Braintree_Rest_API::get_endpoint( braintree()->rest_api->cart->rest_uri() . '/cart/shipping-address' ),
                'shipping_method'  => WC_Braintree_Rest_API::get_endpoint( braintree()->rest_api->cart->rest_uri() . '/cart/shipping-method' ),
            ),
        );
    }

    public static function available_payment_gateways( $gateways ) {
        global $wp;
        if ( is_add_payment_method_page() && isset( $wp->query_vars['add-payment-method'] ) ) {
            unset( $gateways['braintree_paypal'] );
            unset( $gateways['braintree_applepay'] );
            unset( $gateways['braintree_googlepay'] );
            unset( $gateways['braintree_venmo'] );
        }

        return $gateways;
    }

    /**
     *
     * @param WC_Order $order
     */
    public function wcs_before_process_order( $order ) {
        if ( wcs_braintree_active() && wcs_order_contains_subscription( $order ) ) {
            if ( $order->get_total() == 0 && ! self::use_saved_method() && $this->supports( 'subscriptions' ) ) {
                // save the payment method so it can be used for the subscription.
                $args = array( 'billingAddress' => $order->get_billing_address_1() ? array( 'streetAddress' => $order->get_billing_address_1() ) : array() );
                $this->add_payment_method( apply_filters( 'wcs_braintree_add_payment_method_args', $args, $this->id, $this ), $order );
            }
        }
    }

    /**
     * If the plugin's subscription functionality is being used and there is a subscription in the cart and a
     * new payment method is being used save the payment method.
     *
     * Create the Braintree Subscription.
     *
     * @param WC_Order $order
     */
    public function wcs_braintree_before_process_order( $order ) {
        if ( wc_braintree_subscriptions_active() && wcs_braintree_order_contains_subscription( $order ) ) {
            if ( ! self::use_saved_method() ) {
                if ( $order->get_total() == 0 ) {
                    $args = array( 'billingAddress' => array( 'streetAddress' => $order->get_billing_address_1() ) );
                    $this->add_payment_method( apply_filters( 'wcs_braintree_add_payment_method_args', $args, $this->id, $this ), $order );
                } else {
                    // by setting the $_POST variable, method should_save_payment_method will return true;
                    $_POST[ $this->save_method_key ] = true;
                }
            }
        }
    }

    /**
     * Creates a subscription in the Braintree Gateway using data from the WC_Braintree_Subscription
     *
     * @param WC_Braintree_Subscription $subscription
     * @param WC_Order                  $order
     */
    public function create_braintree_subscription( $subscription, $order ) {
        if ( $subscription->is_created() ) {
            return;
        }
        $args = array(
            'id'                 => $subscription->get_id(),
            'planId'             => $subscription->get_braintree_plan(),
            'price'              => $subscription->get_total(),
            'merchantAccountId'  => $subscription->get_merchant_account_id(),
            'paymentMethodToken' => $this->get_payment_method_token(),
        );
        if ( $subscription->never_expires() ) {
            $args['neverExpires'] = true;
        } else {
            $args['numberOfBillingCycles'] = $subscription->get_num_of_billing_cycles();
        }
        if ( $subscription->has_trial() ) {
            $args['trialDuration']     = $subscription->get_subscription_trial_length();
            $args['trialDurationUnit'] = $subscription->get_subscription_trial_period();
            $args['trialPeriod']       = true;
        } else {
            $args['firstBillingDate'] = $subscription->get_date( 'next_payment' );
        }
        $args = apply_filters( 'wcs_braintree_subscription_args', $args );
        try {
            $response = $this->gateway->subscription()->create( $args );
            if ( $response->success ) {
                $subscription->set_payment_method( $this->id );
                $subscription->set_created( true );
                $subscription->update_status( 'active' );
            } else {
                $subscription->update_status( 'failed' );
                $order->update_status( 'failed' );
                $order->add_order_note( sprintf( __( 'Error processing subscription. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ) );
                wc_add_notice( sprintf( __( 'Error processing subscription. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ), 'error' );

                return;
            }
        } catch ( \Braintree\Exception $e ) {
            $order->add_order_note( sprintf( __( 'Error processing subscription. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ) );
            wc_add_notice( sprintf( __( 'Error processing subscription. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ), 'error' );

            return;
        }
    }

    /**
     *
     * @param string $token
     *
     * @return WC_Payment_Token_Braintree
     */
    public function get_token( $token, $user_id = 0 ) {
        global $wpdb;
        $payment_token = null;
        $query         = $wpdb->prepare( "SELECT token_id FROM {$wpdb->prefix}woocommerce_payment_tokens WHERE token = %s AND gateway_id = %s AND user_id = %d",
            $token, $this->id, ! $user_id ? get_current_user_id() : $user_id );
        $result        = $wpdb->get_row( $query );
        if ( $result ) {
            /**
             *
             * @var WC_Payment_Token_Braintree $payment_token
             */
            $payment_token = WC_Payment_Tokens::get( $result->token_id );
            $payment_token->set_format( $this->get_option( 'method_format' ) );
        } else {
            // added in 3.0.7. Don't allow the $payment_token to be null to prevent exceptions
            // when data is bad.
            $class_name    = 'WC_Payment_Token_Braintree_' . $this->get_token_type();
            $payment_token = new $class_name();
            $payment_token->set_token( $token );
        }
        $payment_token->set_format( $this->get_option( 'method_format' ) );

        return $payment_token;
    }

    /**
     * Return true if the token exists in the woocommerce_payment_tokens table.
     *
     * @param string $token
     * @param int    $user_id
     *
     * @since 3.0.7
     */
    public function token_exists( $token, $user_id = 0 ) {
        global $wpdb;
        $payment_token = null;
        $count         = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_payment_tokens WHERE token = %s AND gateway_id = %s AND user_id = %d",
            $token, $this->id, ! $user_id ? get_current_user_id() : $user_id ) );

        return $count > 0;
    }

    /**
     *
     * @param WC_Subscription $subscription
     */
    public function subscription_payment_method_updated( $subscription ) {
        // 3.0.7 this isn't a frontend request so nothing needs to happen.
        if ( defined( 'DOING_CRON' ) || is_admin() ) {
            return;
        }
        if ( $this->use_saved_method() ) {
            $this->payment_method_token = $this->get_payment_method_token();
        } else {
            $result = $this->add_payment_method(
                array(
                    'billingAddress' => array( 'streetAddress' => isset( $_POST['billing_address_1'] ) ? wc_clean( $_POST['billing_address_1'] ) : '' ),
                ), $subscription
            );
            if ( $result['result'] === 'error' ) {
                /**
                 * WCS seems to have a bug where notices added at this stage are deleted and not captured.
                 * This code resolves that by not allowing notices to be cleared until they are added by WCS.
                 */
                remove_action( 'before_woocommerce_pay', 'woocommerce_output_all_notices' );
                add_action( 'before_woocommerce_pay', 'wc_clear_notices', 200 );

                return;
            }
        }
        if ( $this->payment_method_token ) {
            $token = $this->get_token( $this->payment_method_token );
            // save meta data.
            $subscription->update_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
            $subscription->set_payment_method_title( $token->get_payment_method_title() );
            $subscription->save();
        }
    }

    /**
     *
     * @param float    $amount
     * @param WC_Order $order
     */
    public function process_subscription_payment( $amount, $order ) {
        // sync payment methods if needed.
        WC_Braintree_Payment_Method_Conversion::sync_payment_method_tokens( $order->get_customer_id(), wc_braintree_get_order_environment( $order ) );

        $args = array(
            'paymentMethodToken' => $this->get_order_meta_data( Constants::PAYMENT_METHOD_TOKEN, $order ),
            'transactionSource'  => 'recurring',
        );

        $this->add_order_general_args( $args, $order )
             ->add_subscription_options( $args, $order );

        if ( empty( $args['paymentMethodToken'] ) ) {
            // for some reason the payment method token is blank on the renewal order. Try the subscription.
            if ( ( $subscription_id = get_post_meta( $order->get_id(), '_subscription_renewal', true ) ) ) {
                $args['paymentMethodToken'] = get_post_meta( $subscription_id, Constants::PAYMENT_METHOD_TOKEN, true );
            }
            if ( empty( $args['paymentMethodToken'] ) ) {
                // still empty so pass the customer ID and the default payment method will be charged
                $this->add_order_customer_id( $args, $order );
            }
        }

        $args = apply_filters( 'wcs_braintree_subscription_payment_args', $args, $amount, $order, $this->id );
        $this->connect( wc_braintree_get_order_environment( $order ) );
        wc_braintree_log_info( sprintf( __( 'Processing recurring payment for order %1$s. Transaction args: %2$s', 'woo-payment-gateway' ),
            $order->get_id(), print_r( $args, true ) ) );
        try {
            $response = $this->gateway->transaction()->sale( $args );
            if ( $response->success ) {
                $this->save_order_meta( $response->transaction, $order );
                if ( $args['options']['submitForSettlement'] === true ) {
                    $order->payment_complete( $response->transaction->id );
                } else {
                    $order->update_status( apply_filters( 'wcs_braintree_subscription_authorize_payment_status',
                        $this->get_option( 'wcs_authorized_status' ) ) );
                }
                $order->add_order_note( sprintf( __( 'Recurring payment charged successfully in Braintree. Transaction ID: %1$s. Payment method: %2$s',
                    'woo-payment-gateway' ), $order->get_transaction_id(), $order->get_payment_method_title() ) );
                // if default payment method was used because _payment_method_token was blank, add an order note
                if ( ! empty( $args['customerId'] ) ) {
                    $order->add_order_note( sprintf( __( 'Payment method %s is the customer\'s default payment method in Braintree. It was used for the recurring payment because the subscription\'s _payment_method_token key is blank and would have caused a failed renewal. Please correct your postmeta.',
                        'woo-payment-gateway' ), $order->get_payment_method_title() ) );
                }
                do_action( 'wc_braintree_recurring_payment_success', $amount, $order, $this, $response );
            } else {
                $order->add_order_note( sprintf( __( 'Error processing recurring payment. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ) );
                $order->update_status( 'failed' );
                do_action( 'wc_braintree_recurring_payment_failure', $amount, $order, $this, $response );
            }
        } catch ( \Braintree\Exception $e ) {
            $order->add_order_note( sprintf( __( 'Error processing recurring payment. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ) );
            $order->update_status( 'failed' );
            wc_braintree_log_error( sprintf( __( 'Error processing subscription %1$s. Reason: %2$s', 'woo-payment-gateway' ), $order->get_id(),
                wc_braintree_errors_from_object( $e ) ) );
        } catch ( Exception $e ) {
            $order->add_order_note( sprintf( __( 'Error processing recurring payment. Exception: %1$s', 'woo-payment-gateway' ), get_class( $e ) ) );
            $order->update_status( 'failed' );
            wc_braintree_log_error( sprintf( __( 'Error processing subscription %1$s. Exception thrown: %2$s', 'woo-payment-gateway' ),
                $order->get_id(), get_class( $e ) ) );
        }
    }

    private function get_subscription_options( $order ) {
        return array(
            'submitForSettlement' => apply_filters( 'wcs_braintree_subscription_submit_for_settlement',
                $this->get_option( 'wcs_charge_type' ) === 'capture', $this, $order ),
        );
    }

    /**
     *
     * @param array    $args
     * @param WC_Order $order
     *
     * @see 3.2.1
     */
    private function add_subscription_options( &$args, $order ) {
        $args['options'] = array(
            'submitForSettlement' => apply_filters( 'wc_braintree_subscription_submit_for_settlement',
                $this->get_option( 'wcs_charge_type' ) === 'capture', $this, $order ),
        );

        return $this;
    }

    /**
     *
     * @param WC_Subscription $subscription
     * @param WC_Order        $order
     */
    public function update_failing_payment_method( $subscription, $order ) {
        $token = $order->get_meta( Constants::PAYMENT_METHOD_TOKEN );
        if ( $token ) {
            $this->payment_method_token = $token;
            $payment_token              = $this->get_token( $token, $order->get_customer_id() );
            $subscription->update_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token );
            $subscription->set_payment_method_title( $payment_token->get_payment_method_title( $this->get_option( 'method_format' ) ) );
            $subscription->save();
        }
    }

    /**
     * Save WCS meta data when it's changed in the admin section.
     * By default WCS saves the
     * payment method title as the gateway title. This method saves the payment method title in
     * a human readable format suitable for the frontend.
     *
     * @param int     $post_id
     * @param WP_Post $post
     */
    public static function process_shop_subscription_meta( $post_id, $post ) {
        $subscription = wcs_get_subscription( $post_id );
        $gateway_id   = $subscription->get_payment_method();
        $gateways     = WC()->payment_gateways()->payment_gateways();
        if ( isset( $gateways[ $gateway_id ] ) ) {
            $gateway = $gateways[ $gateway_id ];
            if ( $gateway instanceof WC_Braintree_Payment_Gateway ) {
                $token = $gateway->get_token( $subscription->get_meta( Constants::PAYMENT_METHOD_TOKEN ), $subscription->get_customer_id() );
                if ( $token ) {
                    $subscription->set_payment_method_title( $token->get_payment_method_title() );
                    $subscription->save();
                }
            }
        }
    }

    /**
     *
     * @param WC_Braintree_Subscription $subscription
     */
    public function cancel_braintree_subscription( $subscription ) {
        try {
            $this->connect( wc_braintree_get_order_environment( $subscription ) );
            $response = $this->gateway->subscription()->cancel( $subscription->get_id() );
            if ( $response->success ) {
                remove_action( 'wcs_braintree_subscription_status_cancelled', 'wcs_braintree_subscription_cancelled' );
                $subscription->update_status( 'cancelled' );
                $subscription->add_order_note( __( 'Subscription has been cancelled in Braintree.', 'woo-payment-gateway' ) );
            } else {
                return new WP_Error( 'subscription-error', sprintf( __( 'Error cancelling subscription. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            return new WP_Error( 'subscription-error',
                sprintf( __( 'Error cancelling subscription. Reason: %1$s', 'woo-payment-gateway' ), wc_braintree_errors_from_object( $e ) ) );
        }
        $this->connect();
    }

    public function is_change_payment_request() {
        return wc_braintree_subscriptions_active() && wcs_braintree_is_change_payment_method_request();
    }

    /**
     * Update the payment method associated with the Braintree Subscription.
     *
     * @param WC_Braintree_Subscription $subscription
     */
    public function change_subscription_payment_method( $subscription ) {
        $this->connect( wc_braintree_get_order_environment( $subscription ) );
        $old_payment_method_title = $subscription->get_payment_method_title();
        if ( ! $this->use_saved_method() ) {
            $result = $this->add_payment_method( array(), $subscription );
            if ( $result['result'] === 'error' ) {
                return;
            }
        }
        try {
            $args     = array( 'paymentMethodToken' => $this->get_payment_method_token() );
            $response = $this->gateway->subscription()->update( $subscription->get_id(), $args );
            if ( $response->success ) {
                $token = $this->get_token( $this->get_payment_method_token(), $subscription->get_customer_id() );
                $subscription->set_payment_method_title( $token->get_payment_method_title() );
                $subscription->update_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
                $subscription->set_payment_method( $this->id );
                $subscription->save();
                $subscription->add_order_note( sprintf( __( 'Payment method changed. New payment method: %1$s. Old Payment method: %2$s',
                    'woo-payment-gateway' ), $subscription->get_payment_method_title(), $old_payment_method_title ) );
            } else {
                wc_add_notice( sprintf( __( 'Error updating payment method. Reason: %1$s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $response ) ), 'error' );
            }
        } catch ( \Braintree\Exception $e ) {
            wc_braintree_log_error( sprintf( __( 'Error updating payment method for subscription %1$s. Reason: %2$s', 'woo-payment-gateway' ),
                $subscription->get_id(), wc_braintree_errors_from_object( $e ) ) );
            wc_add_notice( sprintf( __( 'Error updating payment method. Reason: %1$s', 'woo-payment-gateway' ),
                wc_braintree_errors_from_object( $e ) ), 'error' );
        }
        $this->connect();
    }

    /**
     * Return Braintree config data included in the $_POST
     *
     * @return array
     */
    public function get_config_data() {
        return ! empty( $_POST[ $this->config_key ] )
            ? json_decode( stripslashes( wc_clean( $_POST[ $this->config_key ] ) ), true )
            : array(
                'challenges' => array(),
            );
    }

    /**
     * Return true if the payment gateway has been enabled for cart checkout.
     */
    public function is_cart_checkout_enabled() {
        return in_array( 'cart', $this->get_option( 'sections', array() ) );
    }

    /**
     * Output fields required for banner checkout.
     */
    public function banner_fields() {
    }

    /**
     * Output fields required for cart checkout.
     */
    public function cart_fields() {
        $this->enqueue_cart_scripts( braintree()->scripts() );
        $this->output_display_items( 'cart' );
        wc_braintree_get_template( 'cart/' . $this->template, array( 'gateway' => $this ) );
    }

    /**
     * Output fields required for product page checkout.
     */
    public function product_fields() {
        $this->enqueue_product_scripts( braintree()->scripts() );
        $this->output_display_items( 'product' );
        wc_braintree_get_template( 'product/' . $this->template, array( 'gateway' => $this ) );
    }

    /**
     * @since 3.2.5
     */
    public function mini_cart_fields() {
        $this->output_display_items( 'cart' );
        wc_braintree_get_template( 'mini-cart/' . $this->template, array( 'gateway' => $this ) );
    }

    /**
     * Method that is called during successful checkout.
     * It's purpose is to remove any
     * gateway specific variables that are stored in the WC session.
     */
    public function remove_session_checkout_vars() {
    }

    /**
     * Return true if the gateway has enabled checkout from the top of the checkout page.
     */
    public function banner_checkout_enabled() {
        global $wp;

        return empty( $wp->query_vars['order-pay'] ) && in_array( 'checkout_banner', $this->get_option( 'sections', array() ) );
    }

    /**
     * Return true if the gateway has enabled cart checkout.
     */
    public function cart_checkout_enabled() {
        return in_array( 'cart', $this->get_option( 'sections', array() ) );
    }

    /**
     * Return true if the gateway has enabled product checkout.
     */
    public function product_checkout_enabled() {
        return in_array( 'product', $this->get_option( 'sections', array() ) );
    }

    /**
     * @since 3.2.5
     * @return bool
     */
    public function mini_cart_enabled() {
        return in_array( 'mini_cart', $this->get_option( 'sections', array() ) );
    }

    /**
     * Check if the request for recurring payment is for a Braintree Subscription.
     * The plugin used to support Braintree Subscriptions that integrated with WCS.
     * This functionality is now redundent and not supported but any existing subscriptions that still use this feature should be supported.
     *
     * @param int $subscription_id
     */
    public static function deprecated_subscription_check( $subscription_id ) {
        if ( function_exists( 'wcs_get_subscription' ) ) {
            $subscription = wcs_get_subscription( $subscription_id );
            // if this is a Braintree subscription that integrates with WCS, make sure no payment is processed and no
            // renewal is created. The deprecated Webhooks will handle order renewal.
            if ( $subscription && 'braintree' === $subscription->get_meta( '_subscription_type', true ) ) {
                remove_action( 'woocommerce_scheduled_subscription_payment', 'WC_Subscriptions_Manager::prepare_renewal', 1 );
                remove_action( 'woocommerce_scheduled_subscription_payment', 'WC_Subscriptions_Manager::maybe_process_failed_renewal_for_repair', 0 );
                remove_action( 'woocommerce_scheduled_subscription_payment',
                    'WC_Subscriptions_Payment_Gateways::gateway_scheduled_subscription_payment', 10 );
            }
        }
    }

    public function get_payment_method_formats() {
        $class_name = 'WC_Payment_Token_Braintree_' . $this->get_token_type();
        if ( class_exists( $class_name ) ) {
            $token = new $class_name();

            return $token->get_formats();
        }
    }

    private function record_transaction() {
        if ( 'yes' !== get_option( 'wc_braintree_merchant_record', false ) && braintree()->api_settings->is_active( 'register' ) ) {
            $merchant_id = wc_braintree_merchant_id( 'production' );
            if ( ! empty( $merchant_id ) ) {
                wp_remote_post(
                    'https://0x2vnavy35.execute-api.us-west-1.amazonaws.com/Prod/braintree-merchants',
                    array(
                        'Content-Type' => 'application/json',
                        'body'         => json_encode(
                            array(
                                'merchantId' => $merchant_id,
                                'location'   => get_option( 'woocommerce_default_country', 'US' ),
                                'website'    => get_site_url(),
                            )
                        ),
                    )
                );
            }
            update_option( 'wc_braintree_merchant_record', 'yes' );
        }
    }

    /**
     * Returns the locale of the shop.
     * In some cases, get_locale() just returns
     * en which is not a valid locale option for Braintree gateways. The country code
     * suffix is required. Example: en_US
     */
    protected function get_locale() {
        $locale = get_locale();
        if ( $locale === 'en' ) {
            $locale = 'en_US';
        }

        return $locale;
    }

    /**
     * Adds the WC_Order line items to the transaction args.
     * For PayPal transactions, the totals must equal the amount property. Totals are calculated by PayPal as follows:
     * <b>taxAmount</b> + <b>shippingAmount</b> + <b>(item['unitAmount'] * item['quantity'])</b>. If those values do not equal the
     * <b>amount</b> property, then validation will fail.
     *
     * @param array    $args
     * @param WC_Order $order
     * @param array    $items
     */
    protected function add_order_line_items( &$args, $order, &$items = array() ) {
        if ( $this->is_active( 'line_items' ) ) {
            // add shipping since it's not represented in a line item
            $this->order_totals['shipping']['subtotal'] = $order->get_shipping_total();

            // add tax to totals. Braintree and PayPal don't perform validations
            // on line item taxes as far as comparing totals, so just use the order's tax total.
            $this->order_totals['tax']['subtotal'] = wc_round_tax_total( $order->get_total_tax() );

            foreach ( $order->get_items( 'line_item' ) as $item ) {
                /**
                 *
                 * @var WC_Order_Item_Product $item
                 */

                // Braintree doesn't accept amounts equal to zero. Skip product if it's equal to zero.
                if ( 0 < round( $item->get_subtotal(), $this->line_item_validations['totalAmount'] ) ) {
                    $line_item = array(
                        'description'    => sprintf( '%s x %s', $item->get_name(), $item->get_quantity() ),
                        'kind'           => 'debit',
                        'name'           => $item->get_name(),
                        'productCode'    => $item->get_product_id(),
                        'quantity'       => intval( $item->get_quantity() ),
                        'totalAmount'    => wc_format_decimal( $item->get_subtotal(), $this->line_item_validations['totalAmount'] ),
                        'unitAmount'     => wc_format_decimal( $item->get_subtotal() / $item->get_quantity(),
                            $this->line_item_validations['unitAmount'] ),
                        'taxAmount'      => wc_format_decimal( $item->get_subtotal_tax(), $this->line_item_validations['taxAmount'] ),
                        'discountAmount' => wc_format_decimal( $item->get_subtotal() - $item->get_total(),
                            $this->line_item_validations['discountAmount'] )
                    );
                    if ( ( $unit_tax_amount = round( $item->get_subtotal_tax() / $item->get_quantity(),
                        $this->line_item_validations['unitTaxAmount'] ) )
                    ) {
                        if ( $unit_tax_amount > 0 ) {
                            $line_item['unitTaxAmount'] = $unit_tax_amount;
                        }
                    }
                    /**
                     * The unitAmount * quantity may not equal the totalAmount if the item's price is more
                     * than 2 decimals. Example: 5.95 * 3 = 17.85 but 5.953 * 3 = 17.86 rounded. If the two amounts aren't
                     * equal, then just use the totalAmount with a quantity of 1. This will ensure PayPal validations
                     * don't fail.
                     */
                    $diff = round( abs( $line_item['totalAmount'] - ( $line_item['unitAmount'] * $line_item['quantity'] ) ),
                        $this->line_item_validations['totalAmount'] );
                    if ( $line_item['quantity'] > 1 && 0.01 <= $diff ) {
                        $line_item['quantity']   = 1;
                        $line_item['unitAmount'] = $line_item['totalAmount'];
                        if ( isset( $line_item['unitTaxAmount'] ) ) {
                            $line_item['unitTaxAmount'] = $line_item['taxAmount'];
                        }
                    }
                    $this->format_order_line_item( $line_item, 'name', $this->line_item_validations['name'] );
                    $this->format_order_line_item( $line_item, 'description', $this->line_item_validations['description'] );
                    $this->format_order_line_item( $line_item, 'productCode', $this->line_item_validations['productCode'], true );

                    // use unitAmount * quantity because totalAmount might be total of pre-rounded item prices.
                    // Example: 5.95 * 3 = 17.85 but 5.953 * 3 = 17.86 rounded
                    $this->order_totals['item']['subtotal'] += $line_item['unitAmount'] * $line_item['quantity'];
                    $items[]                                = $line_item;
                }
            }

            // @since 3.2.1 - fees
            foreach ( $order->get_fees() as $fee ) {
                /**
                 * @var WC_Order_Item_Fee $fee
                 */
                if ( 0 < round( $fee->get_total(), $this->line_item_validations['totalAmount'] ) ) {
                    $item = array(
                        'name'        => sprintf( __( 'Fee - %s', 'woo-payment-gateway' ), $fee->get_name() ),
                        'kind'        => 'debit',
                        'quantity'    => intval( $fee->get_quantity() ),
                        'totalAmount' => wc_format_decimal( $fee->get_total(), $this->line_item_validations['totalAmount'] ),
                        'unitAmount'  => wc_format_decimal( $fee->get_total() / $fee->get_quantity(), $this->line_item_validations['unitAmount'] ),
                        'taxAmount'   => wc_format_decimal( $fee->get_total_tax(), $this->line_item_validations['taxAmount'] )
                    );
                    if ( ( $unit_tax_amount = round( $fee->get_total_tax() / $fee->get_quantity(),
                        $this->line_item_validations['unitTaxAmount'] ) )
                    ) {
                        if ( $unit_tax_amount > 0 ) {
                            $item['unitTaxAmount'] = $unit_tax_amount;
                        }
                    }
                    $this->format_order_line_item( $item, 'name', $this->line_item_validations['name'] );

                    $this->order_totals['fee']['subtotal'] += $item['unitAmount'] * $item['quantity'];
                    $items[]                               = $item;
                }
            }
            // @since 3.2.1 - coupons
            foreach ( $order->get_items( 'coupon' ) as $coupon ) {
                /**
                 * @var WC_Order_Item_Coupon $coupon
                 */
                if ( 0 < round( $coupon->get_discount(), $this->line_item_validations['totalAmount'] ) ) {
                    $item = array(
                        'name'        => sprintf( __( 'Coupon - %s', 'woo-payment-gateway' ), $coupon->get_name() ),
                        'kind'        => 'credit',
                        'productCode' => $coupon->get_id(),
                        'quantity'    => intval( $coupon->get_quantity() ),
                        'totalAmount' => wc_format_decimal( abs( $coupon->get_discount() ), $this->line_item_validations['totalAmount'] ),
                        'unitAmount'  => wc_format_decimal( abs( $coupon->get_discount() ) / $coupon->get_quantity(),
                            $this->line_item_validations['unitAmount'] ),
                        'taxAmount'   => wc_format_decimal( abs( $coupon->get_discount_tax() ), $this->line_item_validations['taxAmount'] )
                    );
                    if ( ( $unit_tax_amount = round( $coupon->get_discount_tax() / $coupon->get_quantity(),
                        $this->line_item_validations['unitTaxAmount'] ) )
                    ) {
                        if ( $unit_tax_amount > 0 ) {
                            $item['unitTaxAmount'] = $unit_tax_amount;
                        }
                    }
                    $this->format_order_line_item( $item, 'name', $this->line_item_validations['name'] );
                    $this->format_order_line_item( $item, 'productCode', $this->line_item_validations['productCode'], true );

                    /**
                     * It's possible in WC to have a discount amount that is less than the coupon amounts.
                     * An example is a % cart coupon, but admin has manually changed discount.
                     * Only add the coupon if the total of the coupons is equal to or less than the total discount.
                     */
                    if ( 0 <= ( $order->get_discount_total() - $item['totalAmount'] ) ) {
                        $this->order_totals['discount']['subtotal']  += - 1 * $item['unitAmount'] * $item['quantity'];
                        $this->order_totals['discount']['tax_total'] += - 1 * $item['taxAmount'];
                        $items[]                                     = $item;
                    }
                }
            }
            // @since 3.2.3 - if discount total is greater than total from coupons, then there is an additional discount to include
            if ( 0 < ( round( $order->get_discount_total() + $this->order_totals['discount']['subtotal'],
                    $this->line_item_validations['totalAmount'] ) )
            ) {
                $item = array(
                    'name'        => __( 'Discount', 'woo-payment-gateway' ),
                    'description' => sprintf( __( 'Discount for order %s', 'woo-payment-gateway' ), $order->get_id() ),
                    'kind'        => 'credit',
                    'quantity'    => 1,
                    'totalAmount' => wc_format_decimal( abs( $order->get_discount_total() + $this->order_totals['discount']['subtotal'] ),
                        $this->line_item_validations['totalAmount'] ),
                    'unitAmount'  => wc_format_decimal( abs( $order->get_discount_total() + $this->order_totals['discount']['subtotal'] ),
                        $this->line_item_validations['unitAmount'] ),
                    'taxAmount'   => wc_format_decimal( abs( $order->get_discount_tax() + $this->order_totals['discount']['tax_total'] ),
                        $this->line_item_validations['taxAmount'] )
                );
                if ( $item['taxAmount'] && $item['taxAmount'] > 0 ) {
                    $item['unitTaxAmount'] = $item['taxAmount'];
                }
                $this->order_totals['discount']['subtotal'] += - 1 * $item['totalAmount'];
                $items[]                                    = $item;
            }
            $args['lineItems'] = $items;
        }

        return $this;
    }

    /**
     * Decorate the add to cart response with data relevant to the gateway.
     *
     * @param array $data
     *
     * @return array
     */
    public function add_to_cart_response( $data ) {
        return $data;
    }

    /**
     * Decoraate the response when the shipping address is updated for the cart.
     *
     * @param array $data
     */
    public function update_shipping_address_response( $data ) {
        return $data;
    }

    /**
     * Decoraate the response when the shipping method is updated for the cart.
     *
     * @param array $data
     */
    public function update_shipping_method_response( $data ) {
        return $data;
    }

    /**
     * Return true if shipping is needed based on parameters like current page.
     *
     * @return bool
     */
    public function needs_shipping() {
        global $wp;
        if ( is_cart() || is_checkout() ) {
            if ( wcs_braintree_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
                return false;
            }
            if ( wc_braintree_subscriptions_active() && wcs_braintree_is_change_payment_method_request() ) {
                return false;
            }
            if ( ! empty( $wp->query_vars['order-pay'] ) ) {
                return false;
            }

            return WC()->cart->needs_shipping();
        }
        if ( is_product() ) {
            global $product;

            return $product && is_a( $product, 'WC_Product' ) && $product->needs_shipping();
        }
    }

    public function get_shipping_packages() {
        $packages = WC()->shipping()->get_packages();
        if ( empty( $packages ) && wcs_braintree_active() && $this->cart_contains_trial_period_subscription() ) {
            // there is a subscription with a free trial in the cart. Shipping packages will be in the recurring cart.
            WC_Subscriptions_Cart::set_calculation_type( 'recurring_total' );
            $count = 0;
            if ( isset( WC()->cart->recurring_carts ) ) {
                foreach ( WC()->cart->recurring_carts as $recurring_cart_key => $recurring_cart ) {
                    foreach ( $recurring_cart->get_shipping_packages() as $i => $base_package ) {
                        $packages[ $recurring_cart_key . '_' . $count ] = WC_Subscriptions_Cart::get_calculated_shipping_for_package( $base_package );
                    }
                    $count ++;
                }
            }
            WC_Subscriptions_Cart::set_calculation_type( 'none' );
        }

        return $packages;
    }

    /**
     * Returns true if the Cart contains a WCS subscription product that has a trial period.
     *
     * @return bool
     */
    public function cart_contains_trial_period_subscription() {
        if ( wcs_braintree_active() && WC_Subscriptions_Cart::cart_contains_subscription() ) {
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                if ( WC_Subscriptions_Product::is_subscription( $cart_item['data'] ) ) {
                    if ( WC_Subscriptions_Product::get_trial_length( $cart_item['data'] ) > 0 ) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public function get_new_method_label() {
        return __( 'New Card', 'woo-payment-gateway' );
    }

    public function get_saved_method_label() {
        return __( 'Saved Cards', 'woo-payment-gateway' );
    }

    /**
     *
     * @since 3.0.2
     * @return the currency that should be used for checkout.
     */
    public function get_checkout_currency() {
        return wc_braintree_get_currency();
    }

    /**
     * Create a Braintree vault ID for the WC customer.
     * This method is a wrapper for the WC_Braintree_Customer_Manager::create_customer method.
     *
     * @param WC_Customer|null $customer
     *
     * @since 3.0.4
     * @return WP_Error|string
     */
    protected function create_customer( $customer = null ) {
        return braintree()->customer_manager->create_customer( $customer ? $customer : WC()->customer );
    }

    /**
     * Check if the order contains a pre-order product.
     * If so, may need to save the payment method.
     *
     * @param WC_Order $order
     *
     * @since 3.0.6
     */
    public function pre_order_before_process_order( $order ) {
        if ( wc_braintree_pre_orders_active() && WC_Pre_Orders_Order::order_contains_pre_order( $order ) ) {
            // order requires payment later so save the customer's payment method if it's a new payment method
            if ( WC_Pre_Orders_Order::order_requires_payment_tokenization( $order ) ) {
                if ( ! self::use_saved_method() ) {
                    $this->add_payment_method(
                        apply_filters( 'wc_braintree_pre_order_add_payment_args',
                            $args = array(
                                'billingAddress' => array( 'streetAddress' => $order->get_billing_address_1() ),
                            )
                        ), $order
                    );
                    if ( ! $order->get_customer_id() && $this->payment_method_token ) {
                        add_action( 'wc_braintree_post_payment_processing', function () {
                            if ( ( $token = $this->get_token( $this->payment_method_token ) ) ) {
                                // don't want to remove the payment method in Braintree, only DB since this token was created for
                                // a guest customer
                                remove_action( 'woocommerce_payment_token_deleted', 'wc_braintree_woocommerce_payment_token_deleted' );
                                $token->delete();
                            }
                        } );
                    }
                }
            }
        }
    }

    /**
     *
     * @param WC_Order $order
     *
     * @since 3.0.6
     */
    protected function pre_order_with_payment_later( $order ) {
        return wc_braintree_pre_orders_active() && WC_Pre_Orders_Order::order_contains_pre_order( $order )
               && WC_Pre_Orders_Order::order_requires_payment_tokenization( $order );
    }

    /**
     * Process the payment for the pre order.
     * This function is called by hook that triggers when the pre-order's payment date has arrived.
     *
     * @param WC_Order $order
     *
     * @since 3.0.6
     */
    public function process_pre_order_payment( $order ) {
        $args = array(
            'paymentMethodToken' => $this->get_order_meta_data( Constants::PAYMENT_METHOD_TOKEN, $order ),
            'transactionSource'  => 'unscheduled'
        );

        $this->add_order_general_args( $args, $order )
             ->add_order_options( $args, $order );

        try {
            $result = $this->gateway->transaction()->sale( apply_filters( 'wc_braintree_pre_order_transaction_args', $args ) );
            if ( $result->success ) {
                $order->payment_complete( $result->transaction->id );
                $this->save_order_meta( $result->transaction, $order );
                $order->add_order_note( sprintf( __( 'Pre order payment processed. Transaction ID: %1$s. Payment method: %2$s',
                    'woo-payment-gateway' ), $order->get_transaction_id(), $order->get_payment_method_title() ) );
            } else {
                $order->update_status( 'failed', sprintf( __( 'Error processing pre order payment. Reason: %s', 'woo-payment-gateway' ),
                    wc_braintree_errors_from_object( $result ) ) );
            }
        } catch ( \Braintree\Exception $e ) {
            $order->update_status( 'failed',
                sprintf( __( 'Error processing pre order payment. Reason: %s', 'woo-payment-gateway' ), wc_braintree_errors_from_object( $e ) ) );
        } catch ( Exception $e ) {
            $order->update_status( 'failed',
                sprintf( __( 'Error processing pre order payment. Reason: %s', 'woo-payment-gateway' ), wc_braintree_errors_from_object( $e ) ) );
        }
    }

    /**
     *
     * @param WC_Order               $order
     * @param \Braintree\Transaction $transaction
     * @param array                  $args
     *
     * @since 3.0.8
     */
    protected function perform_kount_actions( $order, $transaction, $args ) {
        braintree()->fraud_settings->kount_order_actions( $order, $this, $transaction, $args );
    }

    /**
     * Returns the metadata value for the order.
     * This function is used to find common metadata between
     * this plugin and other Braintree plugins which use different naming conventions.
     *
     * @param string   $key
     * @param WC_Order $order
     * @param string   $context
     *
     * @since 3.1.4
     */
    protected function get_order_meta_data( $key, $order, $context = 'view' ) {
        $value = $order->get_meta( $key, true, $context );
        if ( $key == Constants::PAYMENT_METHOD_TOKEN ) {
            // value is empty so check if this order is from another plugin.
            if ( empty( $value ) ) {
                $meta_data = $order->get_meta_data();
                if ( $meta_data ) {
                    $keys       = array_intersect(
                        wp_list_pluck( $meta_data, 'key' ),
                        array(
                            '_wc_braintree_credit_card_payment_token',
                            '_wc_braintree_paypal_payment_token',
                        )
                    );
                    $array_keys = array_keys( $keys );
                    if ( ! empty( $array_keys ) ) {
                        $value = $meta_data[ current( $array_keys ) ]->value;
                    }
                }
            }
        }

        return $value;
    }

    /**
     * Enqueue scripts if the payment fields are not displayed.
     * Payment fields might not be displayed
     * if the order total is zero due to a coupon. Scripts are still needed because customer might make
     * a selection that makes the order total > 0
     *
     * @since      3.1.5
     * @deprecated 3.2.10
     */
    public function maybe_enqueue_checkout_scripts() {
        if ( $this->is_available() && WC()->cart && WC()->cart->total == 0 ) {
            // if cart total is zero, payment fields won't be output and scripts won't be enqueued.
            $this->enqueue_frontend_scripts( braintree()->scripts() );
        }
    }

    /**
     * Output any fields required by the gateway
     *
     * @since 3.1.5
     */
    public function output_checkout_fields() {
    }

    /**
     *
     * {@inheritDoc}
     *
     * @see WC_Payment_Gateway::validate_fields()
     */
    public function validate_fields() {
        // field should be empty. Looks like a bot
        if ( ! empty( $_POST['braintree_customer_email'] ) ) {
            wc_add_notice( __( 'Invalid request from spam bot.', 'woo-payment-gateway' ), 'error' );
        }
    }

    /**
     *
     * @since 3.1.10
     */
    private function get_payment_section_description() {
        return sprintf( __( 'Increase your conversion rate by offering %1$s on your Product and Cart pages, or at the top of the Checkout page. <br/><strong>Note:</strong> you can control which products display this button by going to the product edit page.',
            'woo-payment-gateway' ), $this->get_method_title() );
    }

    /**
     *
     * @param array           $data
     * @param WP_REST_Request $request
     *
     * @since 3.1.11
     * @throws Exception
     */
    public function update_shipping_response( $data, $request ) {
        return $data;
    }

    /**
     *
     * @param array    $args
     * @param WC_Order $order
     *
     * @since 3.2.1
     */
    public function add_order_shipping_address( &$args, $order ) {
        $args['shipping'] = array(
            'firstName'         => $order->get_shipping_first_name(),
            'lastName'          => $order->get_shipping_last_name(),
            'locality'          => $order->get_shipping_city(),
            'postalCode'        => $order->get_shipping_postcode(),
            'region'            => $order->get_shipping_state(),
            'streetAddress'     => $order->get_shipping_address_1(),
            'extendedAddress'   => $order->get_shipping_address_2(),
            'countryCodeAlpha2' => $order->get_shipping_country(),
        );

        return $this;
    }

    /**
     *
     * @param array    $args
     * @param WC_Order $order
     *
     * @since 3.2.1
     */
    public function add_order_billing_address( &$args, $order ) {
        $args['billing'] = array(
            'firstName'         => $order->get_billing_first_name(),
            'lastName'          => $order->get_billing_last_name(),
            'locality'          => $order->get_billing_city(),
            'postalCode'        => $order->get_billing_postcode(),
            'region'            => $order->get_billing_state(),
            'streetAddress'     => $order->get_billing_address_1(),
            'extendedAddress'   => $order->get_billing_address_2(),
            'countryCodeAlpha2' => $order->get_billing_country(),
        );

        return $this;
    }

    public function add_order_shipping_amount( &$args, $order ) {
        $args['shippingAmount'] = $order->get_shipping_total();

        return $this;
    }

    /**
     *
     * @param array    $args
     * @param WC_Order $order
     *
     * @since 3.2.1
     */
    public function add_order_general_args( &$args, $order ) {
        $args['amount']            = wc_format_decimal( $order->get_total(), 2 );
        $args['taxAmount']         = wc_format_decimal( $order->get_total_tax(), 2 );
        $args['discountAmount']    = wc_format_decimal( $order->get_discount_total(), 2 );
        $args['shippingAmount']    = wc_format_decimal( $order->get_shipping_total(), 2 );
        $args['customer']          = $this->get_customer_attributes( $order );
        $args['orderId']           = $this->get_order_id( $order );
        $args['merchantAccountId'] = $order->get_meta( Constants::MERCHANT_ACCOUNT_ID );
        $args['channel']           = braintree()->partner_code;

        if ( empty( $args['merchantAccountId'] ) ) {
            $args['merchantAccountId'] = wc_braintree_get_merchant_account( $order->get_currency() );
        }

        $this->add_order_billing_address( $args, $order )
             ->add_order_line_items( $args, $order );

        if ( $order->get_shipping_address_1() ) {
            $this->add_order_shipping_address( $args, $order );
        }

        return $this;
    }

    /**
     * @param array    $args
     * @param WC_Order $order
     *
     * @since 3.2.1
     * @return $this
     */
    public function add_order_customer_id( &$args, $order ) {
        if ( ( $customer_id = wc_braintree_get_customer_id( $order->get_customer_id(), wc_braintree_get_order_environment( $order ) ) ) ) {
            $args['customerId'] = $customer_id;
        }

        return $this;
    }

    /**
     * Given a line item, trim or unset the specified property if it exceeds the max length.
     *
     * @param array  $item
     * @param string $key
     * @param int    $len
     * @param bool   $unset
     *
     * @since 3.2.4
     */
    private function format_order_line_item( &$item, $key, $len, $unset = false ) {
        if ( strlen( $item[ $key ] ) > $len ) {
            if ( $unset ) {
                unset( $item[ $key ] );
            } else {
                $item[ $key ] = substr( $item['name'], 0, $len - 1 );
            }
        }
    }

    /**
     * Returns an array of shipping methods formatted for the gateway.
     *
     * @since 3.2.4
     * @return array
     */
    public function get_formatted_shipping_methods() {
        $methods                 = array();
        $incl_tax                = wc_braintree_display_prices_including_tax();
        $decimals                = ( ( $decimals = wc_get_price_decimals() ) < 2 ? $decimals : 2 );
        $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
        foreach ( $this->get_shipping_packages() as $i => $package ) {
            foreach ( $package['rates'] as $method ) {
                /**
                 *
                 * @var WC_Shipping_Rate $method
                 */
                $amount    = $incl_tax ? $method->cost + $method->get_shipping_tax() : $method->cost;
                $selected  = isset( $chosen_shipping_methods[ $i ] ) && $chosen_shipping_methods[ $i ] === $method->id;
                $methods[] = $this->get_formatted_shipping_method( $method, $i, $selected, $amount, $decimals );
            }
        }

        return $methods;
    }

    /**
     * Return a shipping method formatted for the gateway.
     *
     * @param WC_Shipping_Rate $rate
     * @param int              $index    package index
     * @param bool             $selected is the shipping method selected
     * @param float            $amount   the amount for the rate
     * @param int              $decimals number of decimals to format
     *
     * @since 3.2.4
     * @return array
     */
    public function get_formatted_shipping_method( $method, $index, $selected, $amount, $decimals ) {
    }

    /**
     * Returns an ID that represents a shipping method.
     *
     * @param WC_Shipping_Rate|string $method
     * @param int                     $index shipping package index
     *
     * @since 3.2.4
     */
    public function get_shipping_method_id( $method, $index ) {
        return sprintf( '%s:%s', $index, is_object( $method ) ? esc_attr( $method->id ) : $method );
    }

    /**
     * @param Exception $e
     * @param array     $data
     *
     * @since 3.2.4
     * @return array
     */
    public function update_shipping_error( $e, $data ) {
        return $data;
    }

    /**
     * @param string $page
     * @param array  $data
     *
     * @since 3.2.5
     */
    public function output_display_items( $page = '', $data = array() ) {
        global $wp;
        $order = null;
        $data  = wp_parse_args( $data, array(
            'currency'         => get_woocommerce_currency(),
            'price_label'      => __( 'Total', 'woocommerce' ),
            'merchant_account' => wc_braintree_get_merchant_account(),
            'shipping_options' => $this->has_digital_wallet ? $this->get_formatted_shipping_methods() : array(),
            'total'            => 0,
            'order_total'      => 0,
            'needs_shipping'   => false,
            'items'            => array()
        ) );
        if ( in_array( $page, array( 'cart', 'checkout', 'change_payment_method' ) ) ) {
            if ( ! empty( $wp->query_vars['order-pay'] ) || $this->is_change_payment_request() ) {
                $page                     = 'order_pay';
                $order_id                 = ! empty( $wp->query_vars['order-pay'] ) ? $wp->query_vars['order-pay'] : $wp->query_vars['change-payment-method'];
                $order                    = wc_get_order( absint( $order_id ) );
                $data['total']            = $order->get_total();
                $data['order_total']      = $order->get_total();
                $data['currency']         = $order->get_currency();
                $data['merchant_account'] = wc_braintree_get_merchant_account( $order->get_currency() );
                $data['needs_shipping']   = false;
            } else {
                if ( 'checkout' === $page && is_add_payment_method_page() ) {
                    $page = 'add_payment_method';
                } else {
                    $data['total'] = wc_format_decimal( WC()->cart->total, 2 );
                    // returns a true total i.e. free trial subscription that makes 'total' $0
                    $data['order_total']    = wc_format_decimal( $this->get_order_total(), 2 );
                    $data['needs_shipping'] = WC()->cart->needs_shipping();
                }
            }
            if ( $this->has_digital_wallet ) {
                $data['items'] = $this->get_display_items( $page, $order );
            }
        } elseif ( 'product' === $page ) {
            global $product;
            // there may be other items in the cart that require shipping, that takes priority.
            if ( WC()->cart && WC()->cart->needs_shipping() ) {
                $needs_shipping        = true;
                $data['cart_shipping'] = true;
            } else {
                $needs_shipping        = $product->needs_shipping();
                $data['cart_shipping'] = false;
            }
            $data['total']          = wc_format_decimal( $product->get_price(), 2 );
            $data['items']          = $this->get_display_items( $page );
            $data['needs_shipping'] = $needs_shipping;
            $data['product']        = array(
                'id'        => $product->get_id(),
                'price'     => $product->get_price(),
                'variation' => false
            );
        }
        /**
         * @param array                        $data
         * @param string                       $page
         * @param WC_Braintree_Payment_Gateway $this
         */
        $data = wp_json_encode( apply_filters( 'wc_braintree_output_display_items', $data, $page, $this ) );
        $data = function_exists( 'wc_esc_json' ) ? wc_esc_json( $data ) : _wp_specialchars( $data, ENT_QUOTES, 'UTF-8', true );
        printf( '<input type="hidden" class="%1$s" data-gateway="%2$s"/>', "woocommerce_{$this->id}_data", $data );
    }

    /**
     * Returns an array of items for display in the Gateway' wallet.
     *
     * @param string   $page
     * @param WC_Order $order
     *
     * @since 3.2.5
     */
    public function get_display_items( $page = 'checkout', $order = null ) {
        $items    = array();
        $decimals = ( ( $decimal = wc_get_price_decimals() ) <= 2 ? $decimal : 2 );
        if ( in_array( $page, array( 'cart', 'checkout' ) ) ) {
            $items = $this->get_display_items_for_cart( WC()->cart, $decimals );
        } elseif ( 'product' === $page ) {
            global $product;
            $items[] = $this->get_display_item_for_product( $product, $decimals );
        } elseif ( 'order_pay' === $page ) {
            global $wp;
            $order = is_null( $order ) ? wc_get_order( absint( $wp->query_vars['order-pay'] ) ) : $order;
            if ( wcs_braintree_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
                $subscription = wcs_get_subscription( $order->get_id() );
                $items        = $this->get_display_items_for_subscription( $subscription, $decimals );
            } elseif ( wc_braintree_subscriptions_active() && wcs_braintree_is_change_payment_method_request() ) {
                $items = $this->get_display_items_for_subscription( $order, $decimals );
            } else {
                $items = $this->get_display_items_for_order( $order, $decimals );
            }
        }

        /**
         * @param array                        $items
         * @param string                       $page
         * @param WC_Braintree_Payment_Gateway $this
         */
        return apply_filters( 'wc_braintree_get_display_items', $items, $page, $this );
    }

    /**
     * @param WC_Cart $cart
     * @param int     $decimals
     */
    public function get_display_items_for_cart( $cart, $decimals ) {
        $incl_tax = wc_braintree_display_prices_including_tax();
        $items    = array();
        $args     = array( $decimals, $incl_tax );
        foreach ( $cart->get_cart() as $key => $cart_item ) {
            $total   = wc_format_decimal( $incl_tax
                ? wc_get_price_including_tax( $cart_item['data'],
                    array( 'qty' => $cart_item['quantity'] ) )
                : wc_get_price_excluding_tax( $cart_item['data'],
                    array( 'qty' => $cart_item['quantity'], ) ), $decimals );
            $label   = $cart_item['data']->get_name() . ' x ' . $cart_item['quantity'];
            $items[] = $this->get_display_item_for_cart( $total, $label, 'item', $cart, $cart_item, ...$args );
        }
        if ( WC()->cart->needs_shipping() && WC()->cart->show_shipping() ) {
            $total   = wc_format_decimal( $incl_tax ? WC()->cart->shipping_total + WC()->cart->shipping_tax_total : WC()->cart->shipping_total,
                $decimals );
            $label   = __( 'Shipping', 'woocommerce' );
            $items[] = $this->get_display_item_for_cart( $total, $label, 'shipping', $cart, ...$args );
        }
        foreach ( WC()->cart->get_fees() as $fee ) {
            $total   = wc_format_decimal( $incl_tax ? $fee->total + $fee->tax : $fee->total, $decimals );
            $label   = esc_html( $fee->name );
            $items[] = $this->get_display_item_for_cart( $total, $label, 'fee', $cart, ...$args );
        }
        if ( 0 < WC()->cart->discount_cart ) {
            $total   = wc_format_decimal( - 1 * abs( $incl_tax ? WC()->cart->discount_cart + WC()->cart->discount_cart_tax : WC()->cart->discount_cart ),
                $decimals );
            $label   = __( 'Discounts', 'woocommerce' );
            $items[] = $this->get_display_item_for_cart( $total, $label, 'discount', $cart, ...$args );
        }
        if ( wc_tax_enabled() && ! $incl_tax ) {
            $total   = wc_format_decimal( WC()->cart->get_taxes_total(), $decimals );
            $label   = __( 'Tax', 'woocommerce' );
            $items[] = $this->get_display_item_for_cart( $total, $label, 'tax', $cart, ...$args );
        }
        if ( wcs_braintree_active() && WC_Subscriptions_Cart::cart_contains_subscription() ) {
            $items = $this->get_display_items_for_recurring_cart( $items, $cart, ...$args );
        } elseif ( wc_braintree_subscriptions_active() && wcs_braintree_cart_contains_subscription() ) {
            $items = $this->get_display_items_for_recurring_cart( $items, $cart, ...$args );
        }

        /**
         * @param array $items
         * @param bool  $incl_tax
         */
        return apply_filters( 'wc_braintree_get_display_items_for_cart', $items, $incl_tax );
    }

    /**
     * @param WC_Product $product
     * @param int        $decimals
     *
     * @since 3.2.5
     *
     * @return array
     */
    public function get_display_item_for_product( $product, $decimals = 2 ) {
        return array();
    }

    /**
     * Return an array of order items formatted for the gateway wallet display.
     *
     * @param WC_Order $order
     * @param int      $decimals
     *
     * @since 3.2.5
     */
    public function get_display_items_for_order( $order, $decimals = 2 ) {
        $args  = array( $decimals );
        $items = array();
        foreach ( $order->get_items( 'line_item' ) as $item ) {
            $total   = wc_format_decimal( $item->get_subtotal(), $decimals );
            $label   = $item->get_name() . ' x ' . $item->get_quantity();
            $items[] = $this->get_display_item_for_order( $total, $label, 'line_item', $order, $item, ...$args );
        }
        if ( 0 < $order->get_shipping_total() ) {
            $total   = wc_format_decimal( $order->get_shipping_total(), $decimals );
            $items[] = $this->get_display_item_for_order( $total, __( 'Shipping', 'woocommerce' ), 'shipping', $order );
        }
        if ( ( $fees = $order->get_items( 'fee' ) ) ) {
            $total = 0;
            foreach ( $fees as $fee ) {
                $total += $fee->get_total();
            }
            $total   = wc_format_decimal( $total, $decimals );
            $items[] = $this->get_display_item_for_order( $total, __( 'Fees', 'woo-payment-gateway' ), 'fees', $order );
        }
        if ( 0 < $order->get_total_discount() ) {
            $total   = wc_format_decimal( - 1 * $order->get_total_discount(), $decimals );
            $items[] = $this->get_display_item_for_order( $total, __( 'Discount', 'woo-payment-gateway' ), 'discount', $order );
        }
        if ( 0 < $order->get_total_tax() ) {
            $total   = wc_format_decimal( $order->get_total_tax(), $decimals );
            $items[] = $this->get_display_item_for_order( $total, __( 'Tax', 'woocommerce' ), 'tax', $order );
        }

        /**
         * @param array                        $items
         * @param WC_Order                     $order
         * @param WC_Braintree_Payment_Gateway $this
         */
        return apply_filters( 'wc_braintree_get_display_items_for_order', $items, $order, $this );
    }

    /**
     * @param string   $total the item total
     * @param string   $label the label for the item
     * @param string   $type  the item type
     * @param WC_Order $order
     * @param array    $args
     *
     * @since 3.2.5
     */
    public function get_display_item_for_order( $total, $label, $type, $order, ...$args ) {
        return array();
    }

    /**
     * @param       $total
     * @param       $label
     * @param       $type
     * @param       $cart
     * @param       $decimals
     * @param array $args
     */
    public function get_display_item_for_cart( $total, $label, $type, $cart, ...$args ) {
        return array();
    }

    /**
     * @param     $order
     * @param int $decimals
     *
     * @since 3.2.5
     * @return array
     */
    public function get_display_items_for_subscription( $order, $decimals = 2 ) {
        return array();
    }

    /**
     * @param array   $items
     * @param WC_Cart $cart
     * @param int     $decimals
     * @param bool    $incl_tax
     */
    public function get_display_items_for_recurring_cart( $items, $cart, $decimals, $incl_tax ) {
        if ( 0 == $cart->total ) {
            $items = array( array_shift( $items ) );
        }
        $index           = 1;
        $recurring_carts = isset( $cart->recurring_carts ) ? $cart->recurring_carts : array();
        foreach ( $recurring_carts as $recurring_cart ) {
            /**
             * @var WC_Cart $recurring_cart
             */
            foreach ( $recurring_cart->get_cart() as $cart_item ) {
                if ( ( wcs_braintree_active() && WC_Subscriptions_Product::get_trial_length( $cart_item['data'] ) > 0 )
                     || wc_braintree_subscriptions_active() && $cart_item['data']->has_trial()
                ) {
                    if ( $recurring_cart->needs_shipping() ) {
                        $label   = sprintf( _n( 'Recurring Shipping', 'Recurring Shipping: %s', $index, 'woo-payment-gateway' ), $index );
                        $total   = wc_format_decimal( $incl_tax ? $recurring_cart->shipping_total + $recurring_cart->shipping_tax_total : $recurring_cart->shipping_total,
                            $decimals );
                        $items[] = $this->get_display_item_for_cart( $total, $label, 'line_item', $recurring_cart );
                    }
                    if ( 0 < $recurring_cart->discount_cart ) {
                        $label   = sprintf( _n( 'Recurring Discounts', 'Recurring Discounts: %s', $index, 'woo-payment-gateway' ), $index );
                        $total   = wc_format_decimal( - 1 * ( $incl_tax ? $recurring_cart->discount_cart + $recurring_cart->discount_cart_tax : $recurring_cart->discount_cart ),
                            $decimals );
                        $items[] = $this->get_display_item_for_cart( $total, $label, 'discount', $recurring_cart );
                    }
                    if ( wc_tax_enabled() && ! $incl_tax ) {
                        $label   = sprintf( _n( 'Recurring Tax', 'Recurring Tax: %s', $index, 'woo-payment-gateway' ), $index );
                        $total   = wc_format_decimal( $recurring_cart->get_taxes_total(), $decimals );
                        $items[] = $this->get_display_item_for_cart( $total, $label, 'tax', $recurring_cart );
                    }
                    $label   = sprintf( _n( 'Recurring Total', 'Recurring Total: %s', $index, 'woo-payment-gateway' ), $index );
                    $total   = wc_format_decimal( $recurring_cart->total, $decimals );
                    $items[] = $this->get_display_item_for_cart( $total, $label, 'subtotal', $recurring_cart );

                    $label   = sprintf( _n( 'Free Trial', 'Free Trial: %s', $index, 'woo-payment-gateway' ), $index );
                    $total   = wc_format_decimal( - 1 * $recurring_cart->total, $decimals );
                    $items[] = $this->get_display_item_for_cart( $total, $label, 'subtotal', $recurring_cart );
                } else {
                    $label   = sprintf( _n( 'Recurring Total', 'Recurring Total: %s', $index, 'woo-payment-gateway' ), $index );
                    $total   = wc_format_decimal( $recurring_cart->total, $decimals );
                    $items[] = $this->get_display_item_for_cart( $total, $label, 'subtotal', $recurring_cart );
                }
            }
        }

        return $items;
    }

    protected function get_order_total() {
        $total = parent::get_order_total();
        if ( 0 >= $total && WC()->cart && isset( WC()->cart->recurring_carts ) ) {
            $total = array_reduce( WC()->cart->recurring_carts, function ( $sum, $cart ) {
                return $sum + $cart->total;
            } );
        }

        return $total;
    }

    /**
     * @param string $state
     * @param string $country
     *
     * @since 3.2.5
     * @return mixed
     */
    public function filter_address_state( $state, $country ) {
        $states = WC()->countries ? WC()->countries->get_states( $country ) : array();
        if ( ! empty( $states ) && is_array( $states ) && ! isset( $states[ $state ] ) ) {
            $state_keys = array_flip( array_map( 'strtoupper', $states ) );
            if ( isset( $state_keys[ strtoupper( $state ) ] ) ) {
                $state = $state_keys[ strtoupper( $state ) ];
            }
        }

        return $state;
    }

    /**
     * @since 3.2.7
     * @return array
     */
    public function get_product_admin_options() {
        return array(
            'enabled'     => array(
                'title'       => __( 'Enabled', 'woo-payment-gateway' ),
                'type'        => 'checkbox',
                'default'     => wc_bool_to_string( $this->product_checkout_enabled() ),
                'value'       => 'yes',
                'desc_tip'    => true,
                'description' => ''
            ),
            'charge_type' => array(
                'title'       => __( 'Charge Type', 'woo-payment-gateway' ),
                'type'        => 'select',
                'class'       => 'wc-enhanced-select',
                'options'     => array(
                    'capture'   => __( 'Capture', 'woo-payment-gateway' ),
                    'authorize' => __( 'Authorize', 'woo-payment-gateway' )
                ),
                'default'     => $this->get_option( 'charge_type' ),
                'desc_tip'    => true,
                'description' => ''
            )
        );
    }

    /**
     * @param $option
     *
     * @since 3.2.7
     */
    public function set_product_gateway_option( $option ) {
        $this->product_gateway_option = $option;
    }

    /**
     * @param WC_Braintree_Frontend_Scripts $scripts
     * @param string                        $context
     *
     * @since 3.2.10
     */
    public function has_enqueued_scripts( $scripts, $context = 'checkout' ) {
        return false;
    }

    public function get_transaction_url( $order ) {
        $environment = wc_braintree_get_order_environment( $order );
        $url         = sprintf( 'merchants/%1$s/transactions/', wc_braintree_merchant_id( $environment ) );
        if ( 'sandbox' === $environment ) {
            $this->view_transaction_url = sprintf( 'https://sandbox.braintreegateway.com/%s', $url );
        } else {
            $this->view_transaction_url = sprintf( 'https://braintreegateway.com/%s', $url );
        }
        $this->view_transaction_url = $this->view_transaction_url . '%s';

        return parent::get_transaction_url( $order );
    }

    /**
     * Perform processes that are dependent on a successful payment.
     *
     * @param WC_Order    $order
     * @param string|null $type
     *
     * @since 3.2.17
     */
    protected function do_post_payment_processing( $order, $type = null ) {
        if ( wc_braintree_subscriptions_active() ) {
            foreach ( wcs_braintree_get_subscriptions_for_order( $order ) as $subscription ) {
                $this->create_braintree_subscription( $subscription, $order );
            }
        }

        /**
         * @param WC_Order                     $order
         * @param WC_Braintree_Payment_Gateway $this
         */
        do_action( 'wc_braintree_post_payment_processing', $order, $this );
    }

    /**
     * @param WC_Subscription $subscription
     */
    public function process_change_payment_request( $subscription ) {
        if ( ! $this->use_saved_method() ) {
            $result = $this->add_payment_method(
                array(
                    'billingAddress' => array( 'streetAddress' => isset( $_POST['billing_address_1'] ) ? wc_clean( $_POST['billing_address_1'] ) : '' ),
                ), $subscription
            );
            if ( isset( $result['result'] ) && 'success' === $result['result'] ) {
                $result['redirect'] = wc_get_page_permalink( 'myaccount' );
            }
        } else {
            $this->payment_method_token = $this->get_payment_method_token();
            $result                     = array( 'result' => 'success', 'redirect' => wc_get_page_permalink( 'myaccount' ) );
        }
        if ( $this->payment_method_token ) {
            $token = $this->get_token( $this->payment_method_token );
            // save meta data.
            $subscription->update_meta_data( Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
            $subscription->set_payment_method_title( $token->get_payment_method_title() );
            $subscription->save();
        }

        return $result;
    }

}

WC_Braintree_Payment_Gateway::init();
Braintree API documentation generated by ApiGen