MediaWiki fundraising/REL1_35
BraintreeAdapter Class Reference
Inheritance diagram for BraintreeAdapter:
Collaboration diagram for BraintreeAdapter:

Public Member Functions

 doPayment ()
 Attempt the default transaction for the current DonationData.
 
 getClientToken ()
 
 getCommunicationType ()
 Data format for outgoing requests to the processor.
 
 getPaymentMethodsSupportingRecurringConversion ()
 Should return an array of payment methods that support setting up a recurring donation after a one-time donation via this gateway.
 
- Public Member Functions inherited from GatewayAdapter
 __construct ( $options=[])
 Constructor.
 
 addRequestData ( $dataArray)
 A helper function to let us stash extra data after the form has been submitted.
 
 addResponseData ( $dataArray)
 Add data from the processor to staged_data and run any unstaging functions.
 
 addStandardMessageFields ( $transaction)
 For making freeform queue messages.
 
 buildOrderIDSources ()
 buildOrderIDSources: Uses the 'alt_locations' array in the order id metadata, to build an array of all possible candidates for order_id.
 
 buildRequestParams ()
 Build the parameters sent with the next request.
 
 calculateKeyMashScore ( $stringToCheck)
 
 cancel ()
 Cancel payment based on adapter and set status to cancelled.
 
 checkTokens ()
 Checks the edit tokens in the user's session against the one gathered from populated form data.
 
 createDonorReturnParams ()
 Takes normalized data and creates adapter specific params for processDonorReturn.
 
 defineDataTransformers ()
 Sets up the $data_transformers array.
 
 definePaymentMethods ()
 Sets up the $payment_methods array.
 
 do_transaction ( $transaction)
 Performs a transaction through the gateway.
 
 finalizeInternalStatus ( $status)
 Sets the final payment status.
 
 findCodeAction ( $transaction, $key, $code)
 findCodeAction
 
 formatStagedData ()
 Format staged data.
 
 generateOrderID ( $dataObj=null)
 Default orderID generation This used to be done in DonationData, but gateways should control the format here.
 
 getAccountConfig ( $key)
 Get globals-based configuration setting.
 
 getAvailableSubmethods ()
 Get metadata for all available submethods, given current method / country TODO: A PaymentMethod should be able to list its child options.
 
 getClientSideValidationRules ()
 Returns an array of rules used to validate data before submission.
 
 getConfig ( $key=null)
 Get settings loaded from adapter's config directory.
 
 getCoreDataTransformers ()
 
 getCurrencies ( $options=[])
 
 getCurrentTransaction ()
 Gets the currently set transaction name.
 
 getData_Unstaged_Escaped ( $val='')
 This is the ONLY getData type function anything should be using outside the adapter.
 
 getDataConstraints ( $field)
 Get any known constraints on the field's value.
 
 getDataSources ()
 
 getDataTransformers ()
 FIXME: Not convinced we need this.
 
 getDonationRules ()
 Add donation rules for the users country & currency combo.
 
 getErrorMap ( $code, $options=[])
 getErrorMap
 
 getErrorMapByCodeAndTranslate ( $code)
 getErrorMapByCodeAndTranslate
 
 getErrorState ()
 Return any errors that prevent this transaction from continuing.
 
 getFinalStatus ()
 If it has been set: returns the final payment status in the $final_status member variable.This is the one we care about for switching on overall behavior. Otherwise, returns false.

Returns
mixed Final Transaction results status, or false if not set. Should be one of the constants defined in
See also
FinalStatus

 
 getFormFields ( $knownData=null)
 Build list of form fields TODO: Determine if this ever needs to be overridden per gateway, or if all the per-country / per-gateway cases can be expressed declaratively in payment method / submethod metadata.
 
 getGatewayAdapterClass ()
 
 getLogDebugJSON ()
 Returns some useful debugging JSON we can append to loglines for increased debugging happiness.
 
 getLogMessagePrefix ()
 Get the log message prefix: $contribution_tracking_id .
 
 getMerchantID ()
 For places that might need the merchant ID outside of the adapter.
 
 getMonthlyConvertAmounts ()
 Add the suggested monthly donation amounts for each donation level according to the currency saved in session for this donation attempt.
 
 getOrderIDMeta ( $key=false)
 Returns information about how to manage the Order ID, either a specific value or the whole associative array.
 
 getPaymentMethod ()
 Get the payment method.
 
 getPaymentMethodMeta ( $payment_method=null)
 Get metadata for the specified payment method as set in.
 
 getPaymentMethods ()
 Define payment methods.
 
 getPaymentSubmethod ()
 Get the name of the currently selected payment submethod.
 
 getPaymentSubmethodMeta ( $payment_submethod=null)
 Get metadata for the specified payment submethod.
 
 getPaymentSubmethods ()
 Get the entire list of payment submethod definitions.
 
 getRequestProcessId ( $requestValues)
 Gateways which return true from isReturnProcessingRequired must override this with logic to get an ID from the request which will identify repeated attempts to process the same payment.
 
 getRequiredFields ( $knownData=null)
 
 getResponseType ()
 Default response type to be the same as communication type.
 
 getScoreCountryMap ()
 This custom filter function checks the global variable:
 
 getScoreEmailDomainMap ()
 This custom filter function checks the global variable:
 
 getScoreName ()
 This custom filter function checks the global variable: wgDonationInterfaceNameFilterRules Each entry in that array has keys KeyMapA, KeyMapB: define keyboard zones GibberishWeight: threshold fraction of name letters in a single zone Score: added to the total fraud score when this threshold is exceeded.
 
 getScoreUtmCampaignMap ()
 This custom filter function checks the global variable:
 
 getScoreUtmMediumMap ()
 This custom filter function checks the global variable:
 
 getScoreUtmSourceMap ()
 This custom filter function checks the global variable:
 
 getTransactionData ()
 Returns the FORMATTED data harvested from the reply, or false if it is not set.
 
 getTransactionMessage ()
 
 getTransactionResponse ()
 Returns the response object with the details of the latest transaction, or null if the adapter has not yet performed one.
 
 getTransactionSpecificValue ( $gateway_field_name)
 This function is used exclusively by the two functions that build requests to be sent directly to external payment gateway servers.
 
 getTransactionStatus ()
 Returns the transaction communication status, or false if not set present.
 
 getValidationAction ()
 Returns the current validation action.
 
 isBatchProcessor ()
 Lets the outside world (particularly filters that accumulate points scores) know if we are a batch processor.
 
 isReturnProcessingRequired ()
 Whether donation processing depends on additional processing on-wiki at the donor's return from a payment processor.
 
 loadConfig ( $variant=null)
 
 localizeGlobal ( $varname)
 Gets a global variable according to.
 
 logFinalStatus ( $status)
 Easily-child-overridable log component of setting the final transaction status, which will only ever be set at the very end of a transaction workflow.
 
 logPending ()
 Dump info about a transaction in logs and pending queues before sending the donor off to complete it.
 
 normalizeOrderID ( $override=null, $dataObj=null)
 This function is meant to be run by the DonationData class, both before and after any communication has been done that might retrieve an order ID.
 
 processDonorReturn ( $requestValues)
 Default implementation sets status to complete.
 
 rectifyOrphan ()
 Looks at message to see if it should be rectified Allows exit if the adapter should not rectify the orphan Then tries to see if the orphan can be matched.
 
 regenerateOrderID ()
 
 runAntifraudFilters ()
 Runs all the fraud filters that have been enabled and configured in donationdata.php and/or LocalSettings.php This function is most likely to be called through executeFunctionIfExists, early on in do_transaction.
 
 sendFinalStatusMessage ( $status)
 Build and send a message to the payments-init queue, once the initial workflow is complete.
 
 session_addDonorData ()
 Removes any old donor data from the session, and adds the current set.
 
 session_ensure ()
 session_ensure Ensure that we have a session set for the current user.
 
 session_getData ( $key, $subkey=null)
 Retrieve data from the session if it's set, and null if it's not.
 
 session_hasDonorData ()
 Checks to see if we have donor data in our session.
 
 session_killAllEverything ()
 This should kill the session as hard as possible.
 
 session_resetForNewAttempt ( $force=false)
 For those times you want to have the user functionally start over without, you know, cutting your entire head off like you do with session_unsetAllData().
 
 session_setDonorBackupData (array $donorData)
 Saves a backup of the Donor Data in session.
 
 session_unsetAllData ()
 Destroys the session completely.
 
 session_unsetDonorData ()
 Unsets the session data, in the case that we've saved it for gateways like GlobalCollect that require it to persist over here through their iframe experience.
 
 setCurrentTransaction ( $transaction_name)
 Sets the transaction you are about to send to the payment gateway.
 
 setHash ( $hashval)
 Set a value used to determine whether data has changed.
 
 setOrderIDMeta ( $key, $value)
 sets more orderID Meta, so we can remember things about what we chose to go with in later logic.
 
 setRiskScore ( $score)
 Set the adapter's fraud score.
 
 setValidationAction ( $action, $reset=false)
 Sets the current validation action.
 
 shouldRectifyOrphan ()
 Allows adapters to specify logic as to whether an orphan can be rectified.
 
 showMonthlyConvert ()
 
 token_getSaltedSessionToken ()
 Establish an 'edit' token to help prevent CSRF, etc.
 
 unsetHash ()
 Clear the data hash value.
 
 unstageKeys ( $processor_data, $key_map=null)
 Change the keys on this data from processor API names to normalized names.
 
 validate ()
 Check donation data for validity and set errors.
 
 validatedOK ()
 
- Public Member Functions inherited from RecurringConversion
 doRecurringConversion ()
 If we have just made a one-time donation that is possible to convert to recurring, do the conversion.
 

Public Attributes

const GATEWAY_NAME = 'Braintree'
 
const GLOBAL_PREFIX = 'wgBraintreeGateway'
 
const IDENTIFIER = 'braintree'
 
- Public Attributes inherited from GatewayAdapter
string[] $debugarray
 
bool $log_outbound = false
 This should be set to true for gateways that don't return the request in the response.
 
bool $posted = false
 A boolean that will tell us if we've posted to ourselves.
 
const COMPLETED_PREFACE = 'Completed donation: '
 
const DONOR = 'Donor'
 
const DONOR_BKUP = 'Donor_BKUP'
 
const GATEWAY_NAME = 'Donation Gateway'
 
const GLOBAL_PREFIX = 'wgDonationGateway'
 
const IDENTIFIER = 'donation'
 
const REDIRECT_PREFACE = 'Redirecting for transaction: '
 Don't change these strings without fixing cross-repo usages.
 

Protected Member Functions

 defineAccountInfo ()
 defineAccountInfo needs to set up the $accountInfo array.
 
 defineOrderIDMeta ()
 Sets up the $order_id_meta array.
 
 defineReturnValueMap ()
 defineReturnValueMap sets up the $return_value_map array.
 
 defineTransactions ()
 defineTransactions will define the $transactions array.
 
 getLocalizedValidationErrorResult (array $validationErrors)
 
 handleCreatedPayment (CreatePaymentResponse $createPaymentResult, PaypalPaymentProvider $provider)
 
- Protected Member Functions inherited from GatewayAdapter
 addCodeRange ( $transaction, $key, $action, $lower, $upper=null)
 addCodeRange is used to define ranges of response codes for major gateway transactions, that let us know what status bucket to sort them into.
 
 addContactMessageFields ( $message)
 IMPORTANT: only add the contact_id to a message if the contact_hash is preset.
 
 appendNodeIfValue ( $value, &$node)
 appendNodeIfValue is a helper function for buildTransactionNodes, which is used by buildRequestXML to construct an XML transaction.
 
 buildRequestArray ()
 
 buildRequestNameValueString ()
 Builds a set of transaction data in name/value format *)The current transaction must be set before you call this function.
 
 buildRequestXML ( $rootElement='XML', $encoding='UTF-8')
 Builds a set of transaction data in XML format *)The current transaction must be set before you call this function.
 
 buildTransactionNodes ( $structure, &$node)
 buildRequestXML helper function.
 
 cleanTransactionStructureForLogs ( $structure, $never_log)
 Recursively sink through a transaction structure array to remove all nodes that we can't have showing up in the server logs.
 
 curl_errno ( $ch)
 Wrapper for the real curl_errno so we can override with magic for unit tests.
 
 curl_exec ( $ch)
 Wrapper for the real curl_exec so we can override with magic for unit tests.
 
 curl_getinfo ( $ch)
 Wrapper for the real curl_getinfo so we can override with magic for unit tests.
 
 curl_transaction ( $data)
 Sends a curl request to the gateway server, and gets a response.
 
 curlResponseIsValidFormat ( $curl_response)
 Allows adapters to specify curl response format requirements (e.g.
 
 defineDataConstraints ()
 TODO: see comment on definePaymentMethods.
 
 defineErrorMap ()
 Define the message keys used to display errors to the user.
 
 defineVarMap ()
 defineVarMap needs to set up the $var_map array.
 
 doQueueTransaction ()
 Sends a queue message to the configured server and queue, based on the outcome of our current transaction.
 
 ensureUniqueOrderID ()
 
 executeIfFunctionExists ( $function_name, $parameter=null)
 Executes the specified function in $this, if one exists.
 
 fallbackToDefaultCurrency ()
 Called when a currency code error exists.
 
 findAccount ()
 Determine which account to use for this session.
 
 formatXmlString ( $xml)
 To avoid reinventing the wheel: taken from http://recursive-design.com/blog/2007/04/05/format-xml-with-php/.
 
 getCurlBaseHeaders ()
 
 getCurlBaseOpts ()
 
 getData_Staged ( $val='')
 Returns staged data from the adapter object, or null if a key was specified and no value exists.
 
 getFailedValidationResponse ()
 
 getFormattedResponse ( $rawResponse)
 Take the entire response string, and strip everything we don't care about.
 
 getProcessorUrl ()
 Return the base URL to use for the current transaction.
 
 getQueueContactMessage ()
 
 getQueueDonationMessage ()
 Collect donation details and normalize keys for pending or donations queue.
 
 getTransactionRequestStructure ()
 Returns the current transaction request structure if it exists, otherwise returns false.
 
 incrementNumAttempt ()
 Adds one to the 'numAttempt' field we use to keep track of how many times a donor has attempted a payment, in a session.
 
 incrementSequenceNumber ()
 Some payment gateways require a distinct identifier for each API call or for each new payment attempt, even if retrying an attempt that failed validation.
 
 isMonthlyConvertCountry ()
 Check if currency is in the list for $wgDonationInterfaceMonthlyConvertCountries.
 
 logCompletedPayment ()
 
 logPaymentDetails ( $preface=self::REDIRECT_PREFACE)
 
 parseResponseCommunicationStatus ( $response)
 Check the response for general sanity - e.g.
 
 parseResponseData ( $response)
 Harvest the data we need back from the gateway.
 
 parseResponseErrors ( $response)
 Parse the response to get the errors in a format we can log and otherwise deal with.
 
 postProcessDonation ()
 Runs all the post-process logic that has been enabled and configured in donationdata.php and/or LocalSettings.php, including the queue message.
 
 processResponse ( $response)
 Process the API response obtained from the payment processor and set properties of transaction_response.
 
 pushMessage ( $queue, $contactOnly=false)
 NOTE: Adyen Checkout has it's own pushMessage that does not push recurring iDEALs to the donations queue.
 
 refreshGatewayValueFromSource ( $val)
 Instead of pulling all the DonationData back through to update one local value, use this.
 
 runSessionVelocityFilter ()
 
 sendPendingMessage ()
 
 session_resetOnSwitch ()
 Check to see if donor is making a repeated attempt that is incompatible with the previous attempt, such as a gateway changes.
 
 setGatewayDefaults ( $options=[])
 Called in the constructor, this function should be used to define pieces of default data particular to the gateway.
 
 stageData ()
 Run any staging DataTransformers configured for the adapter.
 
 stripXMLResponseHeaders ( $rawResponse)
 
 token_checkTokens ()
 token_checkTokens The main function to check the salted and MD5'd token we should have saved and gathered from the request, against the clear-text token we should have saved to the user's session.
 
 token_matchEditToken ( $val)
 token_matchEditToken Determine the validity of a token by checking it against the salted version of the clear-text token we have already stored in the session.
 
 token_refreshAllTokenEverything ()
 token_refreshAllTokenEverything In the case where we have an expired session (token mismatch), we go ahead and fix it for 'em for their next post.
 
 transaction_option ( $option_value)
 If there are things about a transaction that we need to stash in the transaction's definition (defined in a local defineTransactions() ), we can recall them here.
 
 trimFieldToConstraints ( $value, $field)
 Trims a single field according to length constraints in data_constraints.yaml.
 
 unstageData ()
 Run any unstaging functions to decode processor responses.
 
 validateDataConstraintsMet ( $field, $value)
 Validates that the gateway-specific data constraints for this field have been met.
 
 xmlChildrenToArray ( $xml, $nodename)
 

Additional Inherited Members

- Static Public Member Functions inherited from GatewayAdapter
static getEnabledGateways (Config $mwConfig)
 Return an array of all the currently enabled gateways.
 
static getGatewayName ()
 Gets the name of the payment processor, e.g.
 
static getGlobal ( $varname)
 This function is important.
 
static getGlobalPrefix ()
 
static getIdentifier ()
 Get a general purpose identifier for this processor, e.g.
 
static getLogIdentifier ()
 Get a tag to use to identify this adapter in logs, e.g.
 
static token_generateToken ( $padding='')
 token_generateToken Generate a random string to be used as an edit token.
 
- Static Protected Member Functions inherited from GatewayAdapter
static token_applyMD5AndSalt ( $clear_token)
 token_applyMD5AndSalt Takes a clear-text token, and returns the MD5'd result of the token plus the configured gateway salt.
 
- Protected Attributes inherited from GatewayAdapter
 $account_config
 
 $account_name
 
 $accountInfo
 
string $action
 
 $batch = false
 
array $config = []
 config tree
 
string $current_transaction
 Name of the current transaction.
 
StagingHelper ValidationHelper[] $data_transformers = []
 Data transformation helpers.
 
array $dataConstraints = []
 $dataConstraints provides information on how to handle variables.
 
DonationData $dataObj
 
array $error_map = []
 $error_map Reference map from gateway error to client error.
 
ErrorState $errorState
 List of errors preventing this transaction from continuing.
 
string $final_status
 When the smoke clears, this should be set to one of the constants defined in.
 
Psr Log LoggerInterface $logger
 Standard logger, logs to {type}_gateway.
 
 $order_id_candidates
 
 $order_id_meta
 
Psr Log LoggerInterface $payment_init_logger
 Logs to {type}_gateway_payment_init.
 
array $payment_methods = []
 $payment_methods will be defined by the adapter.
 
array $payment_submethods = []
 $payment_submethods will be defined by the adapter (or will default to an empty array if none are defined).
 
DonationProfiler $profiler
 Times and logs various operations.
 
 $return_value_map
 
int $risk_score = 0
 
 $staged_data
 
PaymentTransactionResponse $transaction_response
 $transaction_response is the member var that keeps track of the results of the latest discrete transaction with the gateway.
 
 $transactions
 
 $unstaged_data
 
array $var_map = []
 $var_map maps gateway variables to client variables
 
DomDocument $xmlDoc
 For gateways that speak XML, we use this variable to hold the document while we build the outgoing request.
 

Detailed Description

Definition at line 14 of file braintree.adapter.php.

Member Function Documentation

◆ defineAccountInfo()

BraintreeAdapter::defineAccountInfo ( )
protected

defineAccountInfo needs to set up the $accountInfo array.

Keys = the name (or node name) value in the gateway transaction Values = The actual values for those keys. Probably have to access a global or two. (use getGlobal()!)

Reimplemented from GatewayAdapter.

Definition at line 163 of file braintree.adapter.php.

◆ defineOrderIDMeta()

BraintreeAdapter::defineOrderIDMeta ( )
protected

Sets up the $order_id_meta array.

Todo
Data Item Class. There should be a class that keeps track of the metadata for every field we use (everything that currently comes back from DonationData), that can be overridden per gateway. Revisit this in a more universal way when that time comes.

In general, $order_id_meta contains default data about how we handle/create/gather order_id, which needs to be defined on a per-gateway basis. Once $order_id_meta has been used to decide the order_id for the current request, it will also be used to keep information about the origin and state of the order_id data.

Should contain the following keys/values: 'alt_locations' => [ $dataset_name, $dataset_key ] ** alt_locations is intended to contain a list of arrays that are always available (or should be), from which we can pull the order_id. ** Examples of valid things to throw in $dataset_name are 'request' and 'session' ** $dataset_key : The key in the associated dataset that is expected to contain the order_id. Probably going to be order_id if we are generating the dataset internally. Probably something else if a gateway is posting or getting back to us in a resultswitcher situation. ** These should be expressed in $order_id_meta in order of preference / authority. 'generate' => boolean value. True if we will be generating our own order IDs, false if we are deferring order_id generation to the gateway. 'ct_id' => boolean value. If True, when generating order ID use the contribution tracking ID with the sequence number appended

Will eventually contain the following keys/values: 'final'=> The value that we have chosen as the valid order ID for this request. 'final_source' => Where we ultimately decided to grab the value we chose to stuff in 'final'.

Reimplemented from GatewayAdapter.

Definition at line 21 of file braintree.adapter.php.

◆ defineReturnValueMap()

BraintreeAdapter::defineReturnValueMap ( )
protected

defineReturnValueMap sets up the $return_value_map array.

Keys = The different constants that may be contained as values in the gateway's response. Values = what that string constant means to mediawiki.

Reimplemented from GatewayAdapter.

Definition at line 30 of file braintree.adapter.php.

◆ defineTransactions()

BraintreeAdapter::defineTransactions ( )
protected

defineTransactions will define the $transactions array.

The array will contain everything we need to know about the request structure for all the transactions we care about, for the current gateway. First array key: Some way for us to id the transaction. Doesn't actually have to be the gateway's name for it, but I'm going with that until I have a reason not to. Second array key: 'request' contains the structure of that request. Leaves in the array tree will eventually be mapped to actual values of ours, according to the precedence established in the getTransactionSpecificValue function. 'values' contains default values for the transaction. Things that are typically not overridden should go here. 'check_required' should be set to true for transactions that require donor information, like initial payment setup. TODO: different required fields per transaction

Reimplemented from GatewayAdapter.

Definition at line 131 of file braintree.adapter.php.

◆ doPayment()

BraintreeAdapter::doPayment ( )

Attempt the default transaction for the current DonationData.

Returns
PaymentResult hints for the next donor interaction

Implements GatewayType.

Definition at line 95 of file braintree.adapter.php.

References PaymentResult\newFailure(), and Gateway_Extras_CustomFilters\onGatewayReady().

◆ getClientToken()

BraintreeAdapter::getClientToken ( )

Definition at line 167 of file braintree.adapter.php.

◆ getCommunicationType()

BraintreeAdapter::getCommunicationType ( )

Data format for outgoing requests to the processor.

Must be one of 'xml', 'namevalue' (for POST), or 'redirect'. May depend on current transaction.

Returns
string

Implements GatewayType.

Definition at line 127 of file braintree.adapter.php.

◆ getLocalizedValidationErrorResult()

BraintreeAdapter::getLocalizedValidationErrorResult ( array $validationErrors)
protected
Parameters
ValidationError[]$validationErrors
Returns
PaymentResult

Definition at line 179 of file braintree.adapter.php.

◆ getPaymentMethodsSupportingRecurringConversion()

BraintreeAdapter::getPaymentMethodsSupportingRecurringConversion ( )

Should return an array of payment methods that support setting up a recurring donation after a one-time donation via this gateway.

Returns
array

Implements RecurringConversion.

Definition at line 226 of file braintree.adapter.php.

◆ handleCreatedPayment()

BraintreeAdapter::handleCreatedPayment ( CreatePaymentResponse $createPaymentResult,
PaypalPaymentProvider $provider )
protected
Parameters
CreatePaymentResponse$createPaymentResult
PaypalPaymentProvider$provider
Returns
PaymentResult

Definition at line 40 of file braintree.adapter.php.

Member Data Documentation

◆ GATEWAY_NAME

const BraintreeAdapter::GATEWAY_NAME = 'Braintree'

Definition at line 17 of file braintree.adapter.php.

◆ GLOBAL_PREFIX

const BraintreeAdapter::GLOBAL_PREFIX = 'wgBraintreeGateway'

Definition at line 19 of file braintree.adapter.php.

◆ IDENTIFIER

const BraintreeAdapter::IDENTIFIER = 'braintree'

Definition at line 18 of file braintree.adapter.php.


The documentation for this class was generated from the following file: