function closePendingInvoice($invoiceObj) { $invoiceId = $invoiceObj->id; $subscriptionId = $invoiceObj->subscriptionId; $startDate = $invoiceObj->startDate; $endDate = $invoiceObj->endDate; $chargeInCents = MeterBilling::getUsageCharge($startDate, $endDate, $subscriptionId); $addChargeParam = array("amount" => $chargeInCents, "description" => "monthly usage"); /* * Calling ChargeBee Add Charge Invoice API and add Charge to invoice * based on the usage made by customer. */ ChargeBee_Invoice::addCharge($invoiceId, $addChargeParam); $addonQuantity = MeterBilling::getQuantityUsed($startDate, $endDate, $subscriptionId); $addAddonCharge = array("addonId" => "wallpapers", "addonQuantity" => $addonQuantity); /* * Calling the ChargeBee Add Addon Charge Invoice API and add the no of * addons used by customers to the invoice. */ ChargeBee_Invoice::addAddonCharge($invoiceId, $addAddonCharge); /* * Closing the invoice and Collecting the payment(if auto collection is on) * by calling the ChargeBee Collect Invoice API. */ ChargeBee_Invoice::collect($invoiceId); }
return; } $content = file_get_contents('php://input'); /* * Assigning the recieved content to ChargeBee Event object. */ $event = ChargeBee_Event::deserialize($content); /* * Checking the event type as Invoice Created to add Charge for Meter Billing. */ $eventType = $event->eventType; if ($eventType == "invoice_created") { $invoiceId = $event->content()->invoice()->id; $invoiceObj = ChargeBee_Invoice::retrieve($invoiceId)->invoice(); if ($invoiceObj->status == "pending") { $meterBilling = new MeterBilling(); $meterBilling->closePendingInvoice($invoiceObj); echo "Invoice has been closed successfully"; } else { echo "Invoice is not in pending state"; } } } /* Check if the request is from chargebee. * You can secure the webhook either using * - Basic Authentication * - Or check for specific value in a parameter. * For demo purpose we are using the second option though * basic auth is strongly preferred. Also store the key * securely in the server rather than hard coding in code. */