Newer
Older
$contributionRecur = $this->getRecurFromSubscriptionID($subscriptionID);
if (empty($contributionRecur)) {
// Subscription was not found in CiviCRM
$result = [];
\CRM_Mjwshared_Hook::webhookEventNotMatched('stripe', $this, 'subscription_not_found', $result);
if (empty($result['contributionRecur'])) {
$return->message = $this->formatResultMessage(__FUNCTION__, E::ts('No contributionRecur record found in CiviCRM. Ignored'));
$return->ok = TRUE;
return $return;
}
$contributionRecur = $result['contributionRecur'];
}
if (!isset($stripeData->previous_attributes)) {
// Nothing changed?!
$return->message = $this->formatResultMessage(__FUNCTION__, E::ts('No changes. Ignored'));
$return->ok = TRUE;
return $return;
}
// First work out what changed. This is held in "previous_attributes" on webhook data
$previousAttributes = $stripeData->previous_attributes;
// Simple check that we actually have some items data
// Otherwise it could just be a metadata change which we are not interested in.
$amountHasChanged = FALSE;
if (!empty($previousAttributes->items->data)) {
$amountHasChanged = TRUE;
}
if ($amountHasChanged) {
$subscriptionItems = $stripeData->object->items->data;
$calculatedItems = $this->api->calculateItemsForSubscription($subscriptionID, $subscriptionItems);
}
// $calculatedItems now contains array of new prices by key [currency]_[frequency_unit]_[frequency_interval]
// Eg. $calculatedItems[usd_month_1] = [
// 'currency' => 'usd',
// 'amount' => '2000', (amount is in pence)
// ];
// Now check if recurring contribution matches frequency
$contributionRecurKey = mb_strtolower($contributionRecur['currency']) . "_{$contributionRecur['frequency_unit']}_{$contributionRecur['frequency_interval']}";
if (isset($calculatedItems[$contributionRecurKey])) {
$calculatedItem = $calculatedItems[$contributionRecurKey];
$templateContribution = \CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecur['id']);
if (!Money::of($calculatedItem['amount'], mb_strtoupper($calculatedItem['currency']))
->isAmountAndCurrencyEqualTo(Money::of($templateContribution['total_amount'], $templateContribution['currency']))) {
// Create a new template contribution to update the amount

mattwire
committed
ContributionRecur::updateAmountOnRecurMJW(FALSE)
->addWhere('id', '=', $contributionRecur['id'])
->addValue('amount', $calculatedItem['amount'])
->execute();
$return->message = $this->formatResultMessage(__FUNCTION__, 'recur: ' . $contributionRecur['id'] . '; new amount: ' . $calculatedItem['amount'] . ' currency: ' . $calculatedItem['currency']);
}
else {
$return->message = $this->formatResultMessage(__FUNCTION__, 'recur already updated: ' . $contributionRecur['id'] . '; amount: ' . $calculatedItem['amount'] . ' currency: ' . $calculatedItem['currency']);
}
$return->ok = TRUE;
return $return;
}