From b6390142194dbd5b27243b75cfd3e12acba3b085 Mon Sep 17 00:00:00 2001
From: Aidan Saunders <aidan.saunders@squiffle.uk>
Date: Wed, 13 Jul 2022 15:01:21 +0100
Subject: [PATCH] Add a post merge hook to update the metadata at Stripe.

---
 CRM/Stripe/Customer.php                  | 22 ++++++++++++++++++++++
 stripe.php                               | 14 ++++++++++++++
 xml/schema/CRM/Stripe/StripeCustomer.xml |  4 ++--
 3 files changed, 38 insertions(+), 2 deletions(-)

diff --git a/CRM/Stripe/Customer.php b/CRM/Stripe/Customer.php
index 7336af2b..c66f703d 100644
--- a/CRM/Stripe/Customer.php
+++ b/CRM/Stripe/Customer.php
@@ -263,4 +263,26 @@ class CRM_Stripe_Customer {
     CRM_Core_DAO::executeQuery($sql, $queryParams);
   }
 
+  /**
+   * Update the metadata at Stripe for a given contactid
+   *
+   * @param int $contactId
+   * @return void
+   */
+  public static function updateMetadataForContact(int $contactId): void {
+    $customers = \Civi\Api4\StripeCustomer::get()
+      ->addWhere('contact_id', '=', $contactId)
+      ->execute();
+
+    // Could be multiple customer_id's and/or stripe processors
+    foreach ($customers as $customer) {
+      $stripe = new CRM_Core_Payment_Stripe(null, $customer['processor_id']);
+      CRM_Stripe_Customer::updateMetadata(
+        ['contact_id' => $contactId, 'processor_id' => $customer['processor_id']],
+        $stripe,
+        $customer['id']
+      );
+    }
+  }
+
 }
diff --git a/stripe.php b/stripe.php
index 2c5ecda0..107ab67f 100644
--- a/stripe.php
+++ b/stripe.php
@@ -255,3 +255,17 @@ function stripe_civicrm_permission(&$permissions) {
     $permissions['allow stripe moto payments'] = E::ts('CiviCRM Stripe: Process MOTO transactions');
   }
 }
+
+/*
+ * Implements hook_civicrm_post().
+ */
+function stripe_civicrm_post($op, $objectName, $objectId, &$objectRef) {
+  try {
+    if ($objectName == 'Contact' && $op == 'merge') {
+      CRM_Stripe_Customer::updateMetadataForContact($objectId);
+    }
+  }
+  catch (Exception $e) {
+    \Civi::log(E::SHORT_NAME)->error('Stripe Contact Merge failed: ' . $e->getMessage());
+  }
+}
diff --git a/xml/schema/CRM/Stripe/StripeCustomer.xml b/xml/schema/CRM/Stripe/StripeCustomer.xml
index d47501fc..fea5b21e 100644
--- a/xml/schema/CRM/Stripe/StripeCustomer.xml
+++ b/xml/schema/CRM/Stripe/StripeCustomer.xml
@@ -12,7 +12,7 @@
     <title>Stripe Customer ID</title>
     <type>varchar</type>
     <length>255</length>
-    <comment>The Stripe Customer ID</comment>
+    <comment>Stripe Customer ID</comment>
   </field>
   <index>
     <name>id</name>
@@ -36,7 +36,7 @@
     <name>processor_id</name>
     <title>Payment Processor ID</title>
     <type>int unsigned</type>
-    <comment>Foreign key to civicrm_payment_processor.id</comment>
+    <comment>ID from civicrm_payment_processor</comment>
     <pseudoconstant>
       <table>civicrm_payment_processor</table>
       <keyColumn>id</keyColumn>
-- 
GitLab