class ExtStripeSubscriptionsWebhooksController extends Controller
{
/**
* @var PaymentGatewayStripeSubscriptionsExt
*/
public $extension;
/**
* Default action.
*/
public function actionIndex()
{
$rawBody = Yii::app()->request->getRawBody();
$data = !empty($rawBody) ? @json_decode($rawBody, true) : null;
if (empty($data) || empty($data['data']) ||
empty($data['data']['object']['customer']) ||
empty($data['data']['object']['subscription']) ||
empty($data['data']['object']['paid']) ||
empty($data['type']) || $data['type'] != 'invoice.payment_succeeded') {
return;
}
\Stripe\Stripe::setApiKey($this->extension->getExtModel()->getSecretKey());
try {
$stripeCustomer = \Stripe\Customer::retrieve($data['data']['object']['customer']);
$subscription = $stripeCustomer->subscriptions->retrieve($data['data']['object']['subscription']);
} catch (Exception $e) {
Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
return;
}
$order = PricePlanOrder::model()->findByAttributes(array(
'customer_id' => $subscription->metadata->customer_id,
'order_id' => $subscription->metadata->order_id,
'status' => PricePlanOrder::STATUS_INCOMPLETE,
));
if (!empty($order)) {
$order->status = PricePlanOrder::STATUS_COMPLETE;
$order->save(false);
return;
}
$order = new PricePlanOrder();
foreach ($subscription->metadata as $key => $value) {
if ($order->hasAttribute($key)) {
$order->setAttribute($key, $value);
}
}
$order->order_id = $order->date_added = $order->last_updated = null;
$order->status = PricePlanOrder::STATUS_COMPLETE;
$order->save(false);
$transaction = new PricePlanOrderTransaction();
$transaction->order_id = $order->order_id;
$transaction->payment_gateway_name = 'Stripe Subscriptions - www.stripe.com';
$transaction->payment_gateway_transaction_id = $subscription->id;
$transaction->payment_gateway_response = print_r((array)$subscription, true);
$transaction->status = PricePlanOrderTransaction::STATUS_SUCCESS;
$transaction->save(false);
Yii::app()->end();
}
}