Ejemplo n.º 1
0
 /**
  * Construct Amazon_FPS_Model_PayResponse from XML string
  * 
  * @param string $xml XML string to construct from
  * @return Amazon_FPS_Model_PayResponse 
  */
 public static function fromXML($xml)
 {
     $dom = new DOMDocument();
     $dom->loadXML($xml);
     $xpath = new DOMXPath($dom);
     $xpath->registerNamespace('a', 'http://fps.amazonaws.com/doc/2010-08-28/');
     $response = $xpath->query('//a:PayResponse');
     if ($response->length == 1) {
         return new Amazon_FPS_Model_PayResponse($response->item(0));
     } else {
         $messageCenter = new Adrlist_MessageCenter();
         $messageCenter->newMessage(1, 1, 'Problem with Amazon Payments transaction', 'We were unable to get a proper response from the payment processor.  No payments or charges have been made. Please return to <a href="' . LINKMYACCOUNT . '">your account</a> and try again.<br><br>If the problem persists please <a href="' . LINKSUPPORT . '">contact support</a>', 'Unable to construct Amazon_FPS_Model_PayResponse from provided XML. Make sure that PayResponse is a root element. On line ' . __LINE__ . '. Debug follows:<br>' . $debug->output());
         //throw new Exception ("Unable to construct Amazon_FPS_Model_PayResponse from provided XML. Make sure that PayResponse is a root element");
     }
 }
<?php

$fileInfo = array('title' => 'Amazon IPN Listener', 'fileName' => 'myAccount/amazonIPNListenerMethods.php');
$debug->newFile($fileInfo['fileName']);
/*
This file listens for IPN responses from Amazon Payments. It stores all responses in the database. Responses can be for pay requests, cancellations, changes, etc.
*/
try {
    $messageCenter = new Adrlist_MessageCenter();
    $debug->printArray($_REQUEST, '$_REQUEST');
    //Verify the response came from Amazon.
    $utils = new Amazon_IpnReturnUrlValidation_SignatureUtilsForOutbound();
    $validate = $utils->validateRequest($_POST, AUTOLINK . $_SERVER['PHP_SELF'], "POST");
    $myFile = __DIR__ . '/../CustomLogs/amazonIPNListener' . __LINE__ . '.txt';
    $fh = fopen($myFile, 'w');
    fwrite($fh, '$_POST values: ' . $debug->printArrayOutput($_POST));
    /*
    As this script is ran upon receipt of an IPN response, it will not produce results visible to the end user. We must therefore deliver messages to the end user via the message center.	
    */
    if ($validate !== true) {
        $debug->printArray($validate, '$validate');
        $messageCenter->newMessage(1, 1, 'Problem with Amazon Payments transaction', '', "Could not validate the signature of the IPN response. It could be that it was not from Amazon, although it's more likely a problem with the ipn parameters used to validate. Also, verify that the logic used for this if statement matches the expected response from the {$validate} object." . ' On line ' . __LINE__ . '<br>' . $debug->output());
    } elseif (empty($_REQUEST['operation'])) {
        $messageCenter->newMessage(1, 1, 'Problem with Amazon Payments transaction', '', '$_REQUEST[\'operation\'] is empty. We must have an operation returned from Amazon before we can perform an action. On line ' . __LINE__ . '<br>' . $debug->output());
    } else {
        //The possible operation values for IPN are:
        $operations = array('PAY' => "All pay transactions.", 'REFUND' => "All refund transactions.", 'SETTLE' => "All settle transactions.", 'SETTLE' => "All reserve transactions.", 'MULTI_SETTLE' => "All multi-settle transactions.", 'REAUTH' => "All transactions that required reauthorization.", 'DEPOSIT_FUNDS' => "All fund deposit transactions.", 'WITHDRAW_FUNDS' => "All fund withdrawal transactions.", 'CANCEL_TRANSACTION' => "All non-user cancelled transactions.", 'CANCEL' => "All non-user cancelled transactions.");
        //While there are two status codes returned for a pay response, statusCode and transactionStatus, only transaction Status is returned for all IPN transactions. Therefore we will use it for verification of a successful transaction. The possible transaction status values are:
        $transactionStatusArray = array('CANCELLED' => array('userMessage' => "The transaction has been cancelled. If this result is unexpected, please try again.", 'adminMessage' => "The transaction was canceled."), 'FAILURE' => array('userMessage' => "The transaction failed. Please try again. If it continues to fail you should try a different payment method or account.", 'adminMessage' => "The transaction failed. The API operation failed and Amazon FPS did not receive or record a transaction. You can retry the transaction only if a retriable error has been returned."), 'PENDING' => array('userMessage' => "Your payment is currently pending. Please wait while the payment finishes processing. This should only take a few seconds.", 'adminMessage' => "The transaction is pending."), 'RESERVED' => array('userMessage' => "A reserve has been made on your payment method.", 'adminMessage' => "The reserve request on the transaction succeeded. Amazon FPS reserves the purchase price against the sender's payment instrument."), 'SUCCESS' => array('userMessage' => "", 'adminMessage' => "The transaction succeeded. You can fulfill the order for the customer."));
        if ($_REQUEST['operation'] == 'PAY') {
            if (empty($_REQUEST['callerReference'])) {
function parseReturnUrl()
{
    /*
    The user has authorized recurring payments at Amazon. Parse the url returned from Amazon CBUI. This will validate that the return Url came from Amazon. There are several checks performed here:
    1. The return url must have a query string with the following parameters:
    	tokenID
    	signatureMethod
    	status
    	signatureVersion
    	signature
    	certificateUrl
    	expiry
    	callerReference
    2. The signature of the returnUrl must be verified.
    3. The callerReference is a foreign key in the database. If it doesn't match existing records, this function will fail.
    We will check the tokenId and callerReference fields against the database to see if an entry with matching values already exists.
    Be aware that if this function is called via AJAX the query string will have to be passed via javascript.
    
    After validating the return url we make a pay request.
    */
    global $debug, $message, $success, $Dbc, $returnThis;
    try {
        $messageCenter = new Adrlist_MessageCenter();
        $success = MODE == 'parseReturnUrl' ? true : $success;
        //We set success to true here because a failure below will change it to false.
        $errorMessage = 'We were unable to get a proper response from the payment processor.  No payments or charges have been made. Please return to <a href="' . LINKMYACCOUNT . '">My Account</a> and try again.<br>
<br>
If the problem persists please <a href="' . LINKSUPPORT . '">contact support</a>.';
        if (empty($_POST['returnUrl'])) {
            throw new Adrlist_CustomException($errorMessage, '$_POST[\'returnUrl\'] is empty.');
        } else {
            $goodStatusCodes = array('SA' => 'Success status for the ABT payment method.', 'SB' => 'Success status for the ACH (bank account) payment method.', 'SC' => 'Success status for the credit card payment method.');
            $badStatusCodes = array('SE' => 'System error.', 'A' => 'Buyer abandoned the pipeline.', 'CE' => 'Specifies a caller exception.', 'PE' => 'Payment Method Mismatch Error: Specifies that the buyer does not have payment method that you have requested.', 'NP' => 'There are four cases where the NP status is returned:
1. The payment instruction installation was not allowed on the sender\'s account, because the sender\'s email account is not verified
2. The sender and the recipient are the same
3. The recipient account is a personal account, and therefore cannot
accept credit card payments
4. A user error occurred because the pipeline was cancelled and then
restarted', 'NM' => 'You are not registered as a third-party caller to make this transaction. Contact Amazon Payments for more information.');
            $urlParts = parse_url($_POST['returnUrl']);
            $debug->printArray($urlParts, '$urlParts');
            parse_str($urlParts['query'], $queryArray);
            //Convert the url parameters into an associative array.
            $debug->printArray($queryArray, '$queryArray');
            if (empty($queryArray['callerReference'])) {
                throw new Adrlist_CustomException($errorMessage, '$queryArray[\'callerReference\'] is empty.');
            }
            $utils = new Amazon_IpnReturnUrlValidation_SignatureUtilsForOutbound();
            $validate = $utils->validateRequest($queryArray, AUTOLINK . $_SERVER['PHP_SELF'], "GET");
            if ($validate !== true) {
                //Verify the signature of the payment processor.
                throw new Adrlist_CustomException($errorMessage, 'Could not validate the signature of the payment processor for the return url. This is probably due to an error with the url parameters.');
            } elseif (empty($urlParts['query'])) {
                //We must have a query from the url.
                throw new Adrlist_CustomException($errorMessage, 'There was no query string returned from the payment processor.');
            } elseif (empty($queryArray['callerReference']) || !preg_match("/^\\d+\$/", $queryArray['callerReference'])) {
                //Check the query for callerReference. Check callerReference against a regular expression.
                throw new Adrlist_CustomException($errorMessage, 'There was a problem with $queryArray[\'callerReference\']: ' . $queryArray['callerReference']);
            } elseif (!array_key_exists($queryArray['status'], $goodStatusCodes)) {
                throw new Adrlist_CustomException($errorMessage, 'No good status codes were returned. ' . $queryArray['status'] . ': ' . $badStatusCodes[$queryArray['status']]);
            } else {
                //Get the billingOfferId.
                $billingOfferStmt = $Dbc->prepare("SELECT\n\tbillingOfferId AS 'billingOfferId'\nFROM\n\tuserBillingActions\nWHERE\n\tuserBillingActions.userBillingActionId = ?");
                $billingOfferStmt->execute(array($queryArray['callerReference']));
                $billingOfferRow = $billingOfferStmt->fetch(PDO::FETCH_ASSOC);
                if (empty($billingOfferRow)) {
                    throw new Adrlist_CustomException($errorMessage, 'No billingOfferId was returned. $queryArray[\'status\']: ' . $queryArray['status']);
                }
                //Add a billing action. The recurring payment authorization was successful.
                $userBillingActionId = Adrlist_Billing::addBillingAction($_SESSION['userId'], $billingOfferRow['billingOfferId'], 2, 1, __FILE__ . ' ' . __LINE__);
                //See if the request has already been inserted.
                $responseCheckStmt = $Dbc->prepare("SELECT\n\tamazonCBUIResponseId AS 'amazonCBUIResponseId'\nFROM\n\tamazonCBUIResponses\nWHERE\n\tcallerReference = ? AND\n\ttokenId = ?");
                $responseCheckStmt->execute(array($queryArray['callerReference'], $queryArray['tokenID']));
                $responseRow = $responseCheckStmt->fetch(PDO::FETCH_ASSOC);
                if (empty($responseRow)) {
                    //There is no matching response, so insert the new response to the database.
                    //Convert expiry to Mysql date (YYYY-MM-DD) format. Both the original format and the converted format will be stored in the database.
                    $expiryParts = explode('/', $queryArray['expiry']);
                    if (preg_match('/\\d{2}/', $expiryParts[0]) && preg_match('/\\d{4}/', $expiryParts[1])) {
                        $expiryDatetime = $expiryParts[1] . '-' . $expiryParts[0] . '-01';
                    } else {
                        $expiryDatetime = '0000-00-00';
                    }
                    $amazonCBUIResponseStmt = "INSERT INTO\n\tamazonCBUIResponses\nSET\n\tuserBillingActionId = ?,\n\tcallerReference = ?,\n\tcertificateUrl = ?,\n\taDatetime = ?,\n\texpiry = ?,\n\texpiryDate = ?,\n\tfullUrl = ?,\n\tsignature = ?,\n\tsignatureMethod = ?,\n\tsignatureVersion = ?,\n\taStatus = ?,\n\ttokenId = ?";
                    $amazonCBUIResponseParams = array($userBillingActionId, $queryArray['callerReference'], $queryArray['certificateUrl'], DATETIME, $queryArray['expiry'], $expiryDatetime, $_SERVER['REQUEST_URI'], $queryArray['signature'], $queryArray['signatureMethod'], $queryArray['signatureVersion'], $queryArray['status'], $queryArray['tokenID']);
                    $debug->add('$amazonCBUIResponseStmt: ' . $amazonCBUIResponseStmt);
                    $debug->printArray($amazonCBUIResponseParams, '$amazonCBUIResponseParams');
                    $amazonCBUIResponseStmt = $Dbc->prepare($amazonCBUIResponseStmt);
                    $amazonCBUIResponseStmt->execute($amazonCBUIResponseParams);
                }
                //Make a payment request.
                if (Adrlist_Billing::amazonPayRequest($queryArray['callerReference']) !== true) {
                    $success = false;
                    throw new Adrlist_CustomException('', 'Adrlist_Billing::amazonPayRequest returned false.');
                }
                $returnThis['successUrl'] = LINKMYACCOUNT;
            }
        }
    } catch (Adrlist_CustomException $e) {
        $success = false;
        $debug->add('<pre>' . $e . '</pre>');
        error(__LINE__, ' ', '');
        $messageCenter->newMessage(1, 1, 'Problem with Amazon Payments transaction', '', $debug->output());
    } catch (PDOException $e) {
        $success = false;
        $debug->add('<pre>' . $e . '</pre>');
        error(__LINE__, '', '');
        $messageCenter->newMessage(1, 1, 'Problem with Amazon Payments transaction', '', $debug->output());
    }
    if (MODE == 'parseReturnUrl') {
        $debug->add('$success: ' . $success);
        returnData();
    }
}
Ejemplo n.º 4
0
function supportSend()
{
    //Disabled the recaptcha 2014-03-09.
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        $emailValidate = emailValidate($_POST['supportEmail']);
        if (empty($_POST['supportName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'supportName\'] is empty.');
        } elseif ($emailValidate === false) {
            throw new Adrlist_CustomException('', '$_POST[\'supportEmail\'] is not valid.');
        } elseif (empty($_POST['supportMessage'])) {
            throw new Adrlist_CustomException('', '$_POST[\'supportMessage\'] is empty.');
        }
        /*elseif(empty($_POST['recaptcha_challenge_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_challenge_field\'] is empty.');
        		}elseif(empty($_POST['recaptcha_response_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_response_field\'] is empty.');
        		}
        		$resp = recaptcha_check_answer(RECAPTCHAPRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
        		if($resp->is_valid || LOCAL){
        			$debug->add('The recaptcha response is valid.');*/
        //See if the user has an account.
        $accountCheckStmt = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tprimaryEmail = ? OR\n\tsecondaryEmail = ?");
        $accountCheckStmt->execute(array($_POST['supportEmail'], $_POST['supportEmail']));
        if ($row = $accountCheckStmt->fetch(PDO::FETCH_ASSOC)) {
            //Add the question to the user's support section.
            $newMessage = new Adrlist_MessageCenter();
            $message .= 'Thank you for contacting us!<br>
<br>
Your message has been received. A response will be sent to the message center.';
            $newMessage->newMessage($row['userId'], 1, 'A message sent from the contact page', $_POST['supportMessage']);
        } else {
            //Send the message.
            $subject = $_POST['supportName'] . ' sent a message to support at ' . THENAMEOFTHESITE . '.';
            $bodyText = 'From: ' . $_POST['supportName'] . ' (' . $_POST['supportEmail'] . ')
Sent on: ' . Adrlist_Time::utcToLocal(false, false)->format('F d, Y H:i:s') . '.';
            $bodyHtml = 'From: ' . $_POST['supportName'] . ' (' . $_POST['supportEmail'] . ')<br>
Sent on: ' . Adrlist_Time::utcToLocal(false, false)->format('F d, Y H:i:s') . '<br>
Mesage:<br>
' . nl2br($_POST['supportMessage']);
            //$fromAddress,$toAddress,$subject,$bodyHtml,$bodyText,$senderAddress = NULL,$returnAddress = NULL
            if (email($_POST['supportEmail'], EMAILSUPPORT, $subject, $bodyHtml, $bodyText, $_POST['supportEmail'])) {
                $message .= 'Thank you for contacting us! We will get back to you as soon as we can.';
                $success = true;
                $debug->add('used the function email(' . $_POST['supportEmail'] . ',' . EMAILSUPPORT . ',$subject,$bodyHtml,$bodyText,' . EMAILSUPPORT);
                $debug->add('$subject:' . $subject . '<br>
$bodyHtml:' . $bodyHtml . '<br>
$bodyText:' . $bodyText);
            } else {
                throw new Adrlist_CustomException('', 'There was a problem trying to send an email.');
            }
        }
        /*}else{
        			//Set the error code so that we can display it.
        			$message .= 'The reCAPTCHA wasn\'t entered correctly. Please enter the new reCAPTCHA.';
        			$debug->add('reCAPTCHA said: ' . $resp->error);
        		}*/
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'supportSend') {
        returnData();
    }
}