Extracting the Payment ID

Hi Team,
I am trying to extract the payment ID from the $response variable from the php connect example. It returns private objects/arrays. I can’t find any documentation that details how to extract the information. I am not that experienced with coding, so my knowledge is limited.

Example:
var_dump($response); returns this:

object(Square\Http\ApiResponse)#26 (8) {
  ["request":"Square\Http\ApiResponse":private]=>
  object(Square\Http\HttpRequest)#15 (4) {
    ["httpMethod":"Square\Http\HttpRequest":private]=>
    string(4) "Post"
    ["headers":"Square\Http\HttpRequest":private]=>
    array(5) {
      ["user-agent"]=>
      string(29) "Square-PHP-SDK/6.1.0.20200722"
      ["Accept"]=>
      string(16) "application/json"
      ["content-type"]=>
      string(16) "application/json"
      ["Square-Version"]=>
      string(10) "2020-07-22"
      ["Authorization"]=>
      string(71) "Bearer EAAAEKqGJAcxq33I1vRGDoSdHuOjM1e0mD_yuMQwFpHnyPpuH-vqy3FCQSojC6Cv"
    }
    ["queryUrl":"Square\Http\HttpRequest":private]=>
    string(47) "https://connect.squareupsandbox.com/v2/payments"
    ["parameters":"Square\Http\HttpRequest":private]=>
    NULL
  }
  ["statusCode":"Square\Http\ApiResponse":private]=>
  int(200)
  ["reasonPhrase":"Square\Http\ApiResponse":private]=>
  NULL
  ["headers":"Square\Http\ApiResponse":private]=>
  array(13) {
    [0]=>
    string(15) "HTTP/1.1 200 OK"
    ["Date"]=>
    string(29) "Sun, 30 Aug 2020 19:36:47 GMT"
    ["Frame-Options"]=>
    string(4) "DENY"
    ["X-Frame-Options"]=>
    string(4) "DENY"
    ["X-Content-Type-Options"]=>
    string(7) "nosniff"
    ["X-Xss-Protection"]=>
    string(13) "1; mode=block"
    ["Content-Type"]=>
    string(16) "application/json"
    ["Square-Version"]=>
    string(10) "2020-07-22"
    ["Squareup--Connect--V2--Common--Versionmetadata-Bin"]=>
    string(16) "CgoyMDIwLTA3LTIy"
    ["Vary"]=>
    string(27) "Accept-Encoding, User-Agent"
    ["Content-Encoding"]=>
    string(4) "gzip"
    ["Content-Length"]=>
    string(3) "568"
    ["Strict-Transport-Security"]=>
    string(45) "max-age=631152000; includeSubDomains; preload"
  }
  ["result":"Square\Http\ApiResponse":private]=>
  object(Square\Models\CreatePaymentResponse)#28 (2) {
    ["errors":"Square\Models\CreatePaymentResponse":private]=>
    NULL
    ["payment":"Square\Models\CreatePaymentResponse":private]=>
    object(Square\Models\Payment)#30 (28) {
      ["id":"Square\Models\Payment":private]=>
      string(29) "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"
      ["createdAt":"Square\Models\Payment":private]=>
      string(24) "2020-08-30T19:36:47.584Z"
      ["updatedAt":"Square\Models\Payment":private]=>
      string(24) "2020-08-30T19:36:47.771Z"
      ["amountMoney":"Square\Models\Payment":private]=>
      object(Square\Models\Money)#29 (2) {
        ["amount":"Square\Models\Money":private]=>
        int(100)
        ["currency":"Square\Models\Money":private]=>
        string(3) "USD"
      }
      ["tipMoney":"Square\Models\Payment":private]=>
      NULL
      ["totalMoney":"Square\Models\Payment":private]=>
      object(Square\Models\Money)#114 (2) {
        ["amount":"Square\Models\Money":private]=>
        int(100)
        ["currency":"Square\Models\Money":private]=>
        string(3) "USD"
      }
      ["appFeeMoney":"Square\Models\Payment":private]=>
      NULL
      ["processingFee":"Square\Models\Payment":private]=>
      NULL
      ["refundedMoney":"Square\Models\Payment":private]=>
      NULL
      ["status":"Square\Models\Payment":private]=>
      string(9) "COMPLETED"
      ["delayDuration":"Square\Models\Payment":private]=>
      string(6) "PT168H"
      ["delayAction":"Square\Models\Payment":private]=>
      string(6) "CANCEL"
      ["delayedUntil":"Square\Models\Payment":private]=>
      string(24) "2020-09-06T19:36:47.584Z"
      ["sourceType":"Square\Models\Payment":private]=>
      string(4) "CARD"
      ["cardDetails":"Square\Models\Payment":private]=>
      object(Square\Models\CardPaymentDetails)#92 (15) {
        ["status":"Square\Models\CardPaymentDetails":private]=>
        string(8) "CAPTURED"
        ["card":"Square\Models\CardPaymentDetails":private]=>
        object(Square\Models\Card)#37 (11) {
          ["id":"Square\Models\Card":private]=>
          NULL
          ["cardBrand":"Square\Models\Card":private]=>
          string(4) "VISA"
          ["last4":"Square\Models\Card":private]=>
          string(4) "1111"
          ["expMonth":"Square\Models\Card":private]=>
          int(12)
          ["expYear":"Square\Models\Card":private]=>
          int(2021)
          ["cardholderName":"Square\Models\Card":private]=>
          NULL
          ["billingAddress":"Square\Models\Card":private]=>
          NULL
          ["fingerprint":"Square\Models\Card":private]=>
          string(71) "sq-1-hkTPgBOAraVIsVGaBBcvVA8l9BNMGNv2Vz2BGjYytjR1YCLqMLS8S2MKrea0ZsrIdw"
          ["cardType":"Square\Models\Card":private]=>
          string(6) "CREDIT"
          ["prepaidType":"Square\Models\Card":private]=>
          NULL
          ["bin":"Square\Models\Card":private]=>
          string(6) "411111"
        }
        ["entryMethod":"Square\Models\CardPaymentDetails":private]=>
        string(5) "KEYED"
        ["cvvStatus":"Square\Models\CardPaymentDetails":private]=>
        string(12) "CVV_ACCEPTED"
        ["avsStatus":"Square\Models\CardPaymentDetails":private]=>
        string(12) "AVS_ACCEPTED"
        ["authResultCode":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationIdentifier":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationName":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationCryptogram":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["verificationMethod":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["verificationResults":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["statementDescription":"Square\Models\CardPaymentDetails":private]=>
        string(24) "SQ *DEFAULT TEST ACCOUNT"
        ["deviceDetails":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["refundRequiresCardPresence":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["errors":"Square\Models\CardPaymentDetails":private]=>
        NULL
      }
      ["locationId":"Square\Models\Payment":private]=>
      string(13) "LH0MT7DEW5C1P"
      ["orderId":"Square\Models\Payment":private]=>
      string(27) "bJshmQ0AozoB1zVEH4iif0XpuaB"
      ["referenceId":"Square\Models\Payment":private]=>
      NULL
      ["customerId":"Square\Models\Payment":private]=>
      NULL
      ["employeeId":"Square\Models\Payment":private]=>
      NULL
      ["refundIds":"Square\Models\Payment":private]=>
      NULL
      ["buyerEmailAddress":"Square\Models\Payment":private]=>
      NULL
      ["billingAddress":"Square\Models\Payment":private]=>
      NULL
      ["shippingAddress":"Square\Models\Payment":private]=>
      NULL
      ["note":"Square\Models\Payment":private]=>
      NULL
      ["statementDescriptionIdentifier":"Square\Models\Payment":private]=>
      NULL
      ["receiptNumber":"Square\Models\Payment":private]=>
      string(4) "7PVO"
      ["receiptUrl":"Square\Models\Payment":private]=>
      string(73) "https://squareupsandbox.com/receipt/preview/7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"
    }
  }
  ["body":"Square\Http\ApiResponse":private]=>
  string(944) "{"payment": {"id": "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY","created_at": "2020-08-30T19:36:47.584Z","updated_at": "2020-08-30T19:36:47.771Z","amount_money": {"amount": 100,"currency": "USD"},"status": "COMPLETED","delay_duration": "PT168H","source_type": "CARD","card_details": {"status": "CAPTURED","card": {"card_brand": "VISA","last_4": "1111","exp_month": 12,"exp_year": 2021,"fingerprint": "sq-1-hkTPgBOAraVIsVGaBBcvVA8l9BNMGNv2Vz2BGjYytjR1YCLqMLS8S2MKrea0ZsrIdw","card_type": "CREDIT","bin": "411111"},"entry_method": "KEYED","cvv_status": "CVV_ACCEPTED","avs_status": "AVS_ACCEPTED","statement_description": "SQ *DEFAULT TEST ACCOUNT"},"location_id": "LH0MT7DEW5C1P","order_id": "bJshmQ0AozoB1zVEH4iif0XpuaB","total_money": {"amount": 100,"currency": "USD"},"receipt_number": "7PVO","receipt_url": "https://squareupsandbox.com/receipt/preview/7PVOoMjV8mUoSaGWKrX1F8VDyHDZY","delay_action": "CANCEL","delayed_until": "2020-09-06T19:36:47.584Z"}}
"
  ["errors":"Square\Http\ApiResponse":private]=>
  array(0) {
  }
  ["cursor":"Square\Http\ApiResponse":private]=>
  NULL
}

All I want to pull is the payment id string here:

  object(Square\Models\CreatePaymentResponse)#28 (2) {
    ["errors":"Square\Models\CreatePaymentResponse":private]=>
    NULL
    ["payment":"Square\Models\CreatePaymentResponse":private]=>
    object(Square\Models\Payment)#30 (28) {
      ["id":"Square\Models\Payment":private]=>
      string(29) "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"

For reference, here is the php code:

// Initialize the Square client.
$client = new Square\SquareClient([
  'accessToken' => $access_token,
  'environment' => getenv('ENVIRONMENT')
]);

$payments_api = $client->getPaymentsApi();

$create_payment_request = new CreatePaymentRequest($nonce, uniqid(), $money);

// The SDK throws an exception if a Connect endpoint responds with anything besides
// a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
  $response = $payments_api->createPayment($create_payment_request);
  // If there was an error with the request we will
  // print them to the browser screen here
  if ($response->isError()) {
    echo 'Api response has Errors';
    $errors = $response->getErrors();
    echo '<ul>';
    foreach ($errors as $error) {
        echo '<li>❌ ' . $error->getDetail() . '</li>';
    }
    echo '</ul>';
    exit();
  }
  echo '<pre>';
  var_dump($response);
  echo '</pre>';
}
1 Like

I believe you should be able to use getters for the private variables. For instance, if you’re trying to get the id, you can do $response->getId(). Let me know if that doesn’t work of course!

Thanks for info. PHP was throwing undefined method errors with that getter, but I was able to use getBody() Which pulls the json array & gives me the payment id string. Now I just have to decode it & extract it. Thanks for your help in pointing me in the right direction!

1 Like

No worries! It’s actually probably $response->getPayment()->getId() if you want to use the SDK class, but whatever works best for you :slight_smile:.

1 Like

No worries! This is the full set that worked for me:

  $resp_arr = $response->getBody();
  $resp_dec = json_decode($resp_arr, true);
  $transid = $resp_dec["payment"]["id"];
2 Likes

Thank you ZetaRevan for this info!
Was looking for this! Not sure why this obviously important info is not found in their docs.
Maybe I just missed it.

1 Like

it took me for a while to get the payment id. here is the properway for payment id:

$payment_id = $response->getResult()->getPayment()->getId();

Reference Id:

$oRefId = $response->getResult()->getPayment()->getReferenceId();

Here is the full code:

try {
// Every payment you process with the SDK must have a unique idempotency key.
// If you’re unsure whether a particular payment succeeded, you can reattempt
// it with the same idempotency key without worrying about double charging
// the buyer.
$create_payment_request = new CreatePaymentRequest($token, $order_uid, $money);
$create_payment_request->setReferenceId($order_referenceId);
$response = $payments_api->createPayment($create_payment_request);

if ($response->isSuccess()) {

 $payment_id = $response->getResult()->getPayment()->getId();
 $oRefId = $response->getResult()->getPayment()->getReferenceId();

echo json_encode($response->getResult());

} else {
echo json_encode(array(‘errors’ => $response->getErrors()));
}
} catch (ApiException $e) {
echo json_encode(array(‘errors’ => $e));
}