Search code examples
phppaypalsdkinvoice

PayPal PHP SDK - cancel invoice function does nothing


I am using the PayPal SDK for PHP, I am trying to cancel an invoice, the result returned is "true", there isn't exception returned, but the invoice is not canceled. Please could you tell me if there is an error in my code?

$Invoice = new Invoice();

try {
    $invoice = $Invoice->get($id_invoice, $apiContext);
    $notify = new CancelNotification();
    $notify->setSubject("Past due")
           ->setNote("Canceling invoice")
           ->setSendToMerchant(true)
           ->setSendToPayer(true);
    $result = $Invoice->cancel($notify, $apiContext);

} catch (Exception $ex) {
    $result = self::getException($ex);
}

return $result;

Solution

  • First get an invoice object like this:

    $invoice = Invoice::get($invoiceId, $apiContext);
    

    Then, you could do the following to cancel it.

    // ### Cancel Notification Object
    // This would send a notification to both merchant as well
    // the payer about the cancellation. The information of
    // merchant and payer is retrieved from the invoice details
    $notify = new CancelNotification();
    $notify
        ->setSubject("Past due")
        ->setNote("Canceling invoice")
        ->setSendToMerchant(true)
        ->setSendToPayer(true);
    // ### Cancel Invoice
    // Cancel invoice object by calling the
    // static `cancel` method
    // on the Invoice class by passing a valid
    // notification object
    // (See bootstrap.php for more on `ApiContext`)
    $cancelStatus = $invoice->cancel($notify, $apiContext);
    

    Also, to test the code, you could always run the samples, and test it out yourself, by just clicking a button.

    I ran the sample to cancel an invoice, and then use the similar information provided back on get response of invoice:

    "metadata": {
        "created_date": "2015-02-04 13:12:33 PST",
        "first_sent_date": "2015-02-04 13:12:34 PST",
        "last_sent_date": "2015-02-04 13:12:34 PST",
        "payer_view_url": "https://www.sandbox.paypal.com/cgi_bin/webscr?cmd=_pay-inv&viewtype=altview&id=INV2-6S46-MLLN-3FEA-VLZE"
    }
    

    enter image description here

    Opening the URL showed me that the invoice was cancelled as shown below:

    enter image description here