jenkins-bot has submitted this change and it was merged.

Change subject: Associate refunds with parent transactions
......................................................................


Associate refunds with parent transactions

Warning: relies on a couple of undocumented assumptions, though
an Amazon representative endorsed the strategy via email.
* Order reference ID is alwyas the first 19 characters of related
  refund, authorization, or capture IDs
* When an authorization and capture are generated simultaneously
  by setting capture_now = true on the auth call, their IDs will
  be identical except for the 21st character, which is an A for
  the authorization and a C for the capture

Determines order reference ID, retrieves details including a list
of authorizations.  Go through list of authorizations till we find
a successful one, then replaces 'A' with 'C' to return the capture
ID (which we use for gateway_txn_id).

Used in both IPN listener and audit parser.

Bug: T111425
Change-Id: Ia83acf1253baf36aaedd7e98f229c0359a99290d
---
A PaymentProviders/Amazon/Actions/AssociateRefundParent.php
M PaymentProviders/Amazon/AmazonApi.php
M PaymentProviders/Amazon/Audit/AuditParser.php
A 
PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Closed.json
A 
PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Declined.json
A PaymentProviders/Amazon/Tests/Data/responses/getOrderReferenceDetails.json
A PaymentProviders/Amazon/Tests/config_test.php
A PaymentProviders/Amazon/Tests/phpunit/ApiTest.php
M config_defaults.php
9 files changed, 243 insertions(+), 3 deletions(-)

Approvals:
  Awight: Looks good to me, approved
  jenkins-bot: Verified



diff --git a/PaymentProviders/Amazon/Actions/AssociateRefundParent.php 
b/PaymentProviders/Amazon/Actions/AssociateRefundParent.php
new file mode 100644
index 0000000..0d8beb3
--- /dev/null
+++ b/PaymentProviders/Amazon/Actions/AssociateRefundParent.php
@@ -0,0 +1,29 @@
+<?php namespace SmashPig\PaymentProviders\Amazon\Actions;
+
+use SmashPig\Core\Actions\IListenerMessageAction;
+use SmashPig\Core\SmashPigException;
+use SmashPig\Core\Logging\Logger;
+use SmashPig\PaymentProviders\Amazon\AmazonApi;
+
+/**
+ * Associate refunds with their parent contribution
+ */
+class AssociateRefundParent implements IListenerMessageAction {
+       const MESSAGE_CLASS = 
'SmashPig\PaymentProviders\Amazon\ExpatriatedMessages\RefundCompleted';
+
+       public function execute( ListenerMessage $msg ) {
+               // Bail out if not a refund
+               if ( get_class( $msg ) !== self::MESSAGE_CLASS ) {
+                       return true;
+               }
+               $refundId = $msg->gateway_txn_id;
+               try {
+                       $parentId = AmazonApi::findRefundParentId( $refundId );
+                       $msg['gateway_parent_id'] = $parentId;
+                       return true;
+               } catch( SmashPigException $ex ) {
+                       Logger::error( $ex->getMessage() );
+                       return false;
+               }
+       }
+}
diff --git a/PaymentProviders/Amazon/AmazonApi.php 
b/PaymentProviders/Amazon/AmazonApi.php
index a416c31..cffecb3 100644
--- a/PaymentProviders/Amazon/AmazonApi.php
+++ b/PaymentProviders/Amazon/AmazonApi.php
@@ -1,6 +1,7 @@
 <?php namespace SmashPig\PaymentProviders\Amazon;
 
 use SmashPig\Core\Context;
+use SmashPig\Core\SmashPigException;
 
 /**
  * Utility functions for the PayWithAmazon SDK
@@ -12,4 +13,57 @@
                $klass = $config->val( 'ipn-handler-class' );
                return new $klass( $headers, $body );
        }
+
+       public static function findRefundParentId( $refundId ) {
+               $config = Context::get()->getConfiguration();
+               $client = $config->obj( 'payments-client', true );
+
+               // The order reference ID is the first 19 characters of the 
refund ID
+               $orderReferenceId = substr( $refundId, 0, 19 );
+
+               $getDetailsResult = $client->getOrderReferenceDetails( array(
+                       'amazon_order_reference_id' => $orderReferenceId,
+               ) )->toArray();
+               if ( !empty( $getDetailsResult['Error'] ) ) {
+                       throw new SmashPigException( 
$getDetailsResult['Error']['Message'] );
+               }
+
+               // The order reference details should contain an IdList with 
all of the
+               // authorizations that have been made against the order 
reference.  We
+               // should only ever have one authorization per order reference.
+               $details = 
$getDetailsResult['GetOrderReferenceDetailsResult']['OrderReferenceDetails'];
+               if ( !isset( $details['IdList'] ) || !isset( 
$details['IdList']['member'] ) ) {
+                       throw new SmashPigException(
+                               "No authorizations found for order reference 
$orderReferenceId!"
+                       );
+               }
+               if ( is_array( $details['IdList']['member'] ) ) {
+                       $authorizationIds = $details['IdList']['member'];
+               } else {
+                       $authorizationIds = array( $details['IdList']['member'] 
);
+               }
+               // Check the status of each authorization against the order 
reference
+               foreach ( $authorizationIds as $id ) {
+                       $authResult = $client->getAuthorizationDetails( array(
+                               'amazon_authorization_id' => $id,
+                       ) )->toArray();
+                       if ( !empty( $authResult['Error'] ) ) {
+                               throw new SmashPigException( 
$authResult['Error']['Message'] );
+                       }
+                       $details = 
$authResult['GetAuthorizationDetailsResult']['AuthorizationDetails'];
+                       $state = $details['AuthorizationStatus']['State'];
+                       // Once we successfully capture payment against an 
authorization, it
+                       // transitions to the 'Closed' state. Failed attempts 
are 'Declined'
+                       if ( $state === 'Closed' ) {
+                               // And guess what?  The authorization ID is 
exactly the same as the
+                               // capture ID (which we store as the gateway 
txn id), with one letter
+                               // changed.
+                               $captureId = substr( $id, 0, 20 ) . 'C' . 
substr( $id, 21 );
+                               return $captureId;
+                       }
+               }
+               throw new SmashPigException(
+                       "No successful authorizations found for order reference 
$orderReferenceId!"
+               );
+       }
 }
diff --git a/PaymentProviders/Amazon/Audit/AuditParser.php 
b/PaymentProviders/Amazon/Audit/AuditParser.php
index 2ed93f7..188dc3b 100644
--- a/PaymentProviders/Amazon/Audit/AuditParser.php
+++ b/PaymentProviders/Amazon/Audit/AuditParser.php
@@ -3,6 +3,7 @@
 use SmashPig\Core\DataFiles\DataFileException;
 use SmashPig\Core\DataFiles\HeadedCsvReader;
 use SmashPig\Core\UtcDate;
+use SmashPig\PaymentProviders\Amazon\AmazonApi;
 
 /**
  * Parses settlement reports from Amazon MWS
@@ -70,9 +71,8 @@
        }
 
        protected function parseRefund( HeadedCsvReader $csv, array &$msg, 
$type ) {
-               // We need to set this when refunding.  TODO: figure out 
chargebacks!
-               $msg['gateway_parent_id'] = $csv->currentCol( 
'SellerReferenceId' );
-               $msg['gateway_refund_id'] = 'RFD ' . $csv->currentCol( 
'AmazonTransactionId' );
+               $msg['gateway_refund_id'] = $csv->currentCol( 
'AmazonTransactionId' );
+               $msg['gateway_parent_id'] = AmazonApi::findRefundParentId( 
$msg['gateway_refund_id'] );
                $msg['gross_currency'] = $csv->currentCol( 'CurrencyCode' );
                $msg['type'] = strtolower( $type );
        }
diff --git 
a/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Closed.json
 
b/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Closed.json
new file mode 100644
index 0000000..22f6b42
--- /dev/null
+++ 
b/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Closed.json
@@ -0,0 +1,37 @@
+{
+    "GetAuthorizationDetailsResult": {
+        "AuthorizationDetails": {
+            "AuthorizationAmount": {
+                "CurrencyCode": "USD",
+                "Amount": "10.00"
+            },
+            "CapturedAmount": {
+                "CurrencyCode": "USD",
+                "Amount": "10.00"
+            },
+            "SoftDescriptor": "AMZ*Wikimedia Founda",
+            "ExpirationTimestamp": "2015-10-28T17:49:04.234Z",
+            "IdList": {
+                "member": "P01-0133129-0199515-C019658"
+            },
+            "AuthorizationStatus": {
+                "LastUpdateTimestamp": "2015-09-28T17:49:06.200Z",
+                "ReasonCode": "MaxCapturesProcessed",
+                "State": "Closed"
+            },
+            "AuthorizationFee": {
+                "CurrencyCode": "USD",
+                "Amount": "0.00"
+            },
+            "CaptureNow": "true",
+            "SellerAuthorizationNote": [],
+            "CreationTimestamp": "2015-09-28T17:49:04.234Z",
+            "AmazonAuthorizationId": "P01-0133129-0199515-A019658",
+            "AuthorizationReferenceId": "76543855-1"
+        }
+    },
+    "ResponseMetadata": {
+        "RequestId": "f39d77bf-c1be-4c1f-b47a-6b79f77fe4aa"
+    },
+    "ResponseStatus": "200"
+}
\ No newline at end of file
diff --git 
a/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Declined.json
 
b/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Declined.json
new file mode 100644
index 0000000..5fb19f9
--- /dev/null
+++ 
b/PaymentProviders/Amazon/Tests/Data/responses/getAuthorizationDetails_Declined.json
@@ -0,0 +1,34 @@
+{
+    "GetAuthorizationDetailsResult": {
+        "AuthorizationDetails": {
+            "AuthorizationAmount": {
+                "CurrencyCode": "USD",
+                "Amount": "10.00"
+            },
+            "CapturedAmount": {
+                "CurrencyCode": "USD",
+                "Amount": "0"
+            },
+            "SoftDescriptor": "AMZ*Wikimedia Founda",
+            "ExpirationTimestamp": "2015-10-28T17:48:32.431Z",
+            "AuthorizationStatus": {
+                "LastUpdateTimestamp": "2015-09-28T17:48:33.720Z",
+                "State": "Declined",
+                "ReasonCode": "InvalidPaymentMethod"
+            },
+            "AuthorizationFee": {
+                "CurrencyCode": "USD",
+                "Amount": "0.00"
+            },
+            "CaptureNow": "true",
+            "CreationTimestamp": "2015-09-29T17:48:32.431Z",
+            "SellerAuthorizationNote": [],
+            "AmazonAuthorizationId": "P01-0133129-0199515-A068790",
+            "AuthorizationReferenceId": "76543855-0"
+        }
+    },
+    "ResponseMetadata": {
+        "RequestId": "d178a69b-5e5b-45ab-8e38-913986d405ad"
+    },
+    "ResponseStatus": "200"
+}
\ No newline at end of file
diff --git 
a/PaymentProviders/Amazon/Tests/Data/responses/getOrderReferenceDetails.json 
b/PaymentProviders/Amazon/Tests/Data/responses/getOrderReferenceDetails.json
new file mode 100644
index 0000000..04c8f42
--- /dev/null
+++ b/PaymentProviders/Amazon/Tests/Data/responses/getOrderReferenceDetails.json
@@ -0,0 +1,35 @@
+{
+    "GetOrderReferenceDetailsResult": {
+        "OrderReferenceDetails": {
+            "OrderReferenceStatus": {
+                "LastUpdateTimestamp": "2015-09-28T17:49:08.123Z",
+                "ReasonCode": "SellerClosed",
+                "State": "Closed"
+            },
+            "ExpirationTimestamp": "2016-03-27T17:48:23.249Z",
+            "IdList": {
+                "member": [
+                    "P01-0133129-0199515-A068790",
+                    "P01-0133129-0199515-A019658"
+                ]
+            },
+            "SellerOrderAttributes": [],
+            "OrderTotal": {
+                "CurrencyCode": "USD",
+                "Amount": "10.00"
+            },
+            "Buyer": {
+                "Name": "Testy Test",
+                "Email": "[email protected]"
+            },
+            "ReleaseEnvironment": "Sandbox",
+            "SellerNote": "Donation to the Wikimedia Foundation",
+            "AmazonOrderReferenceId": "P01-0133129-0199515",
+            "CreationTimestamp": "2015-09-28T17:48:23.123Z"
+        }
+    },
+    "ResponseMetadata": {
+        "RequestId": "896332ae-e316-4eb6-865e-79278e1aa214"
+    },
+    "ResponseStatus": "200"
+}
\ No newline at end of file
diff --git a/PaymentProviders/Amazon/Tests/config_test.php 
b/PaymentProviders/Amazon/Tests/config_test.php
new file mode 100644
index 0000000..f5253fe
--- /dev/null
+++ b/PaymentProviders/Amazon/Tests/config_test.php
@@ -0,0 +1,18 @@
+<?php
+
+$config = array(
+       'amazon' => array(
+               'payments-client' => array(
+                       'class' => 'PayWithAmazon\Mocks\MockPaymentsClient',
+                       'inst-args' => array( array(
+                               'response-directory' => __DIR__ . 
'/Data/responses',
+                       ) ),
+               ),
+               'reports-client' => array(
+                       'class' => 'PayWithAmazon\Mocks\MockReportsClient',
+                       'inst-args' => array( array(
+                               'response-directory' => __DIR__ . 
'/Data/responses',
+                       ) ),
+               ),
+       )
+);
diff --git a/PaymentProviders/Amazon/Tests/phpunit/ApiTest.php 
b/PaymentProviders/Amazon/Tests/phpunit/ApiTest.php
new file mode 100644
index 0000000..948f08d
--- /dev/null
+++ b/PaymentProviders/Amazon/Tests/phpunit/ApiTest.php
@@ -0,0 +1,32 @@
+<?php
+
+use SmashPig\Core\Configuration;
+use SmashPig\Core\Context;
+use SmashPig\PaymentProviders\Amazon\AmazonApi;
+
+class ApiTest extends BaseSmashPigUnitTestCase {
+
+       protected $mockClient;
+
+       public function setUp() {
+               parent::setUp();
+               $config = new Configuration(
+                       __DIR__ . '/../../../../config_defaults.php',
+                       __DIR__ . '/../config_test.php',
+                       'amazon',
+                       true
+               );
+               Context::init( $config );
+               $this->mockClient = Context::get()->getConfiguration()->obj( 
'payments-client', true );
+               $this->mockClient->calls = array();
+               $this->mockClient->returns = array();
+               $this->mockClient->exceptions = array();
+       }
+
+       public function testFindParent() {
+               $this->mockClient->returns['getAuthorizationDetails'][] = 
'Declined';
+               $this->mockClient->returns['getAuthorizationDetails'][] = 
'Closed';
+               $parentId = AmazonApi::findRefundParentId( 
'P01-0133129-0199515-R019658' );
+               $this->assertEquals( 'P01-0133129-0199515-C019658', $parentId, 
'Did not get the right refund parent ID' );
+       }
+}
diff --git a/config_defaults.php b/config_defaults.php
index 9499348..cfcb737 100644
--- a/config_defaults.php
+++ b/config_defaults.php
@@ -119,6 +119,7 @@
                'actions' => array(
                        
'SmashPig\PaymentProviders\Amazon\Actions\IncomingMessage',
                        
'SmashPig\PaymentProviders\Amazon\Actions\CloseOrderReference',
+                       
'SmashPig\PaymentProviders\Amazon\Actions\AssociateRefundParent',
                ),
 
                'endpoints' => array(

-- 
To view, visit https://gerrit.wikimedia.org/r/244000
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: Ia83acf1253baf36aaedd7e98f229c0359a99290d
Gerrit-PatchSet: 7
Gerrit-Project: wikimedia/fundraising/SmashPig
Gerrit-Branch: master
Gerrit-Owner: Ejegg <[email protected]>
Gerrit-Reviewer: Awight <[email protected]>
Gerrit-Reviewer: Ejegg <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to