title: Refund using PHP PayPal REST API?
body: <p>I am working on a PHP application that integrates into PayPal's REST API. I have the transactions processing correctly and saving the transaction ID into a MySQL database. I am now trying to refund the sale but cannot get it to cease giving a "Incoming JSON request does not map to API request" error. Does anyone have any advice on how to get this working?</p>
  
  <p>I left some of my attempts in the code with comments about their result. I'm feeling a bit lost in the direction to get this working. Any help will be appreciated.</p>
  
  <p>I've been following the documentation located here:
  <a href="https://developer.paypal.com/docs/integration/direct/payments/refund-payment/" rel="nofollow noreferrer">https://developer.paypal.com/docs/integration/direct/payments/refund-payment/</a></p>
  
  <p>I may be struggling adapting that request to PHP.</p>
  
  <p>I found this bit of code:
  <a href="https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/payments/RefundCapture.php" rel="nofollow noreferrer">https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/payments/RefundCapture.php</a></p>
  
  <p>But it is 'requiring' a tree of files that seem a bit excessive for a simple refund request. </p>
  
  <pre><code>&lt;?php
  
  require_once(dirname(__FILE__) . '/paypalSDK/autoload.php'); // require paypal files
  require_once(dirname(__FILE__) . '/paypalSDK/paypal/rest-api-sdk-php/sample/common.php'); // require paypal files
  // call required stuff
  use PayPal\Api\Address;
  use PayPal\Api\Amount;
  use PayPal\Api\Details;
  use PayPal\Api\ExecutePayment;
  use PayPal\Api\FundingInstrument;
  use PayPal\Api\Item;
  use PayPal\Api\ItemList;
  use PayPal\Api\Payer;
  use PayPal\Api\Payment;
  use PayPal\Api\PaymentCard;
  use PayPal\Api\PaymentExecution;
  use PayPal\Api\Transaction;
  use PayPal\Api\Capture;
  use PayPal\Api\Refund;
  use PayPal\Api\RefundRequest;
  use PayPal\Api\Sale;
  
  $orderID = $_GET['order_id']; // order ID we wish to refund
  // pull the details from the database so we have the transaction refund ID
  $refQ = mysql_query("SELECT * FROM orders WHERE orders_ID = $orderID", $db);
  $refC = mysql_num_rows($refQ);
  if(!empty($refC)){
  
      $refR = mysql_fetch_assoc($refQ);
      $refNumber = $refR['orders_transaction_ref']; // paypal transaction ID
      $FinalTotal = $refR['orders_order_total']; // order total
      // paypal credentials
      $apiContext = new \PayPal\Rest\ApiContext(
          new \PayPal\Auth\OAuthTokenCredential(
              'abc',    
              'xyz'  
          )
      );
      $apiContext-&gt;setConfig(array('mode' =&gt; 'live',)); // live use, not sandbox
  
      //$amount = new Amount();  // commenting these out seemingly has no effect
      //$amount-&gt;setCurrency("USD")  // commenting these out seemingly has no effect
      //    -&gt;setTotal($FinalTotal);  // commenting these out seemingly has no effect
  
      $refund = new Refund(); // if I comment these 2 lines out, I get "refund cannot be null"
      $refund-&gt;setAmount($FinalTotal); // if I comment these 2 lines out, I get "refund cannot be null"
  
      $sale = new Capture(); // if I comment these 2 lines out, I get "Call to a member function refund() on a non-object"
      $sale-&gt;setId($refNumber); // if I comment these 2 lines out, I get "Call to a member function refund() on a non-object"
  
      $refundRequest = new RefundRequest(); // commenting these out seemingly has no effect
      $refundRequest-&gt;setAmount($FinalTotal); // commenting these out seemingly has no effect
  
      //$captureRefund = $sale-&gt;refundCapturedPayment($refundRequest, $apiContext); // failure, error 400
  
      try {
          $sale-&gt;refund($refund, $apiContext);
          //$sale-&gt;refundCapturedPayment($refund, $apiContext); // failure, error 400
      } catch (Exception $ex) {
          echo '&lt;pre style="font-size:16px;"&gt;';
              var_dump($ex);
          echo '&lt;/pre&gt;';
          exit();
          die;
      }
  }
  </code></pre>
  
  <p><strong>Update 3/8/2017 @ 12:23pm</strong></p>
  
  <p>I have seemingly made 'some' progress, though I use the term loosely. The state is returning as 'completed' but the refund is not actually happening. It also isn't returning the parent payment ID like the samples demonstrate. Any ideas on this? I'm still trying to get this to work.</p>
  
  <p>This is the result I am presently getting from PayPal:</p>
  
  <pre><code>object(PayPal\Api\Refund)#3 (1) {
    ["_propMap":"PayPal\Common\PayPalModel":private]=&gt;
    array(5) {
      ["id"]=&gt;
      string(17) "123456789123456789"
      ["create_time"]=&gt;
      string(20) "2017-03-06T20:56:32Z"
      ["state"]=&gt;
      string(9) "completed"
      ["amount"]=&gt;
      object(PayPal\Api\Amount)#9 (1) {
        ["_propMap":"PayPal\Common\PayPalModel":private]=&gt;
        array(3) {
          ["total"]=&gt;
          string(4) "0.02"
          ["currency"]=&gt;
          string(3) "USD"
          ["details"]=&gt;
          object(PayPal\Api\Details)#13 (1) {
            ["_propMap":"PayPal\Common\PayPalModel":private]=&gt;
            array(1) {
              ["subtotal"]=&gt;
              string(4) "0.02"
            }
          }
        }
      }
      ["links"]=&gt;
      array(1) {
        [0]=&gt;
        object(PayPal\Api\Links)#17 (1) {
          ["_propMap":"PayPal\Common\PayPalModel":private]=&gt;
          array(3) {
            ["href"]=&gt;
            string(59) "https://api.paypal.com/v1/payments/refund/123456789123456789"
            ["rel"]=&gt;
            string(4) "self"
            ["method"]=&gt;
            string(3) "GET"
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>Below is the code presently returning the response above...</p>
  
  <pre><code>require_once(dirname(__FILE__) . '/paypalSDK/autoload.php'); // require paypal files
  require_once(dirname(__FILE__) . '/paypalSDK/paypal/rest-api-sdk-php/sample/bootstrap.php'); // require paypal files
  require_once(dirname(__FILE__) . '/paypalSDK/paypal/rest-api-sdk-php/sample/common.php'); // require paypal files
  // call required stuff
  use PayPal\Api\Address;
  use PayPal\Api\Amount;
  use PayPal\Api\Details;
  use PayPal\Api\ExecutePayment;
  use PayPal\Api\FundingInstrument;
  use PayPal\Api\Item;
  use PayPal\Api\ItemList;
  use PayPal\Api\Payer;
  use PayPal\Api\Payment;
  use PayPal\Api\PaymentCard;
  use PayPal\Api\PaymentExecution;
  use PayPal\Api\Transaction;
  use PayPal\Api\Capture;
  use PayPal\Api\Refund;
  use PayPal\Api\RefundRequest;
  use PayPal\Api\Sale;
  
  $orderID = $_GET['order_id']; // internal order ID we wish to refund
  
  // pull the details from database so we have the PayPal transction ID
  $refQ = mysql_query("SELECT * FROM orders WHERE orders_ID = $orderID", $db);
  $refC = mysql_num_rows($refQ);
  if(!empty($refC)){
  
      $refR = mysql_fetch_assoc($refQ);
      $refNumber = $refR['orders_transaction_ref']; // PayPal transaction ID 
  
      // attempted 'PAY-' ID, results in "Requested resource ID was not found."
      // $refNumber = $refR['orders_payment_ref']; // ex. PAY-123456789012345678901234 
  
      $FinalTotal = $refR['orders_order_total']; // order total
  
      // paypal credentials
      $apiContext = new \PayPal\Rest\ApiContext(
          new \PayPal\Auth\OAuthTokenCredential(
              'abc',    
              'xyz'  
          )
      );
      $apiContext-&gt;setConfig(array('mode' =&gt; 'live',)); // live use, not sandbox
  
      //$amount = new Amount();  // commenting these out seemingly has no effect
      //$amount-&gt;setCurrency("USD")  // commenting these out seemingly has no effect
      //    -&gt;setTotal($FinalTotal);  // commenting these out seemingly has no effect
  
      /*
      // attempted code 
      // ### Refund object
      $refund = new Refund();
      //$refund = new RefundRequest();
      $refund-&gt;setAmount($FinalTotal);
      */
  
      $refund = new Refund();
      $refund-&gt;setId($refNumber);
      $refund-&gt;setSaleId($refNumber);
      $refund-&gt;setAmount($FinalTotal);
      $refund-&gt;setReason("Testing refund code");
      //$refund-&gt;get($refNumber, $apiContext);
  
      // Attempted code, didn't work
      // https://stackoverflow.com/questions/18927591/paypal-api-how-to-get-sale-id-and-refund-payment-made-via-paypal
      // Fatal error: Uncaught exception 'InvalidArgumentException' with message 'paymentId cannot be null' in /home/cartridgeworkspl/public_html/cfx_controllers/paypalSDK/paypal/rest-api-sdk-php/lib/PayPal/Validation/ArgumentValidator.php:25 Stack trace: #0 
      // $payments = Payment::get($refNumber, $apiContext);
      // $payments-&gt;getTransactions();
      // $obj = $payments-&gt;toJSON();//I wanted to look into the object
      // $paypal_obj = json_decode($obj);//I wanted to look into the object
      // $transaction_id = $paypal_obj-&gt;transactions[0]-&gt;related_resources[0]-&gt;sale-&gt;id;
      // $this-&gt;refund($transaction_id);//Call your custom refund method
  
      try {
          //var_dump($refund);
          $refundResponse = Refund::get($refNumber, $apiContext);
          echo '&lt;pre&gt;';
              var_dump($refundResponse);
          echo '&lt;/pre&gt;';
          echo $refundResponse-&gt;getState();
          echo $refundResponse-&gt;getReasonCode();
      } catch (Exception $ex) {
          // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
          ResultPrinter::printError("Get Payment", "Payment", null, null, $ex);
          exit(1);
      }
  
  }
  </code></pre>
  
  <p>Any help would be supremely appreciated.</p>