Json response from stripe to variables in php - php

I have a code in php that listen to stripe which sends to the my server a json format information. I would like to retrieve the email from the json and assign it to a variable $email. I don't understand what is wrong with my php code.
PHP code:
<?php
include "connect.php";
echo "Works";
require_once('stripe_final/init.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("this is hidden key");
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
// to verify this is a real event, we re-retrieve the event from Stripe
// $event = Stripe_Event::retrieve($event_id);
// successful payment
if($event->type == 'charge.succeeded') {
// send a payment receipt email here
// retrieve the payer's information
$email = $event_json->name;
$sql = "INSERT INTO stripe (email) VALUES ('$email')";
if (mysqli_query($db, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($db);
}
mysqli_close($db);
}
} catch (Exception $e) {
}
}
http_response_code(200); // PHP 5.4 or greater
?>
Json code:
{
"id": "evt_7nxAKynL74HXUu",
"object": "event",
"api_version": "2012-11-07",
"created": 1454008591,
"data": {
"object": {
"id": "ch_7nxA7QWn3069zJ",
"object": "charge",
"amount": 15000,
"amount_refunded": 0,
"application_fee": null,
"balance_transaction": "txn_7nxAqCOclHRnAv",
"captured": true,
"card": {
"id": "card_7nxAJFJ52PhS8G",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": "cus_7nxAxI4lGICtyv",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 11,
"exp_year": 2022,
"fingerprint": "lEO6YJCu2ASyQbvB",
"funding": "credit",
"last4": "4242",
"metadata": {},
"name": "futjakot#gmail.com",
"tokenization_method": null,
"type": "Visa"
},
"created": 1454008591,
"currency": "gbp",
"customer": "cus_7nxAxI4lGICtyv",
"description": null,
"destination": null,
"dispute": null,
"failure_code": null,
"failure_message": null,
"fraud_details": {},
"invoice": null,
"livemode": false,
"metadata": {},
"order": null,
"paid": true,
"receipt_email": "futjakot#gmail.com",
"receipt_number": null,
"refunded": false,
"refunds": [],
"shipping": null,
"source": {
"id": "card_7nxAJFJ52PhS8G",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": "cus_7nxAxI4lGICtyv",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 11,
"exp_year": 2022,
"fingerprint": "lEO6YJCu2ASyQbvB",
"funding": "credit",
"last4": "4242",
"metadata": {},
"name": "futjakot#gmail.com",
"tokenization_method": null,
"type": "Visa"
},
"statement_descriptor": null,
"status": "paid",
"statement_description": null,
"fee": 455,
"fee_details": [
{
"amount": 455,
"amount_refunded": 0,
"application": null,
"currency": "gbp",
"description": "Stripe processing fees",
"type": "stripe_fee"
}
]
}
},
"livemode": false,
"pending_webhooks": 1,
"request": "req_7nxAFmUej9UkFy",
"type": "charge.succeeded"
}

Actually, you have 3 emails in that JSON.
$event_json = json_decode($input);
$email1 = $event_json->data->object->card->name;
$email2 = $event_json->data->object->receipt_email;
$email3 = $event_json->data->object->source->name;
You could have figured it out by yourself by doing a series of var_dump statements on $event_json.

As you see name is in object card of object named object in object named data so the retrieval of e-mail should be:
$email = $event_json->data->object->card->name;

Related

How to echo raw data if it has same name string with others

I have this POST Response from my online shop but the Raw Data has 2 TOKEN string i just want to echo the TOKEN form payment_method what will be PHP code for my problem?
And also in case i want to print the "message" from "transaction" what will be the code though? i already tried to search through internet but its hard for me to figure it out
here is the raw data
{
"transaction": {
"token": "TWN0rD9euove3BEUNRs0PPv2s9w", // this it the token that i dont want to echo
"created_at": "2019-07-05T09:34:21Z",
"updated_at": "2019-07-05T09:34:22Z",
"succeeded": true,
"transaction_type": "AddPaymentMethod",
"retained": false,
"state": "succeeded",
"message_key": "messages.transaction_succeeded",
"message": "Succeeded!",
"payment_method": {
"token": "BXtwsBABZ2z15DkyN5dbTWrwakV", //This is the token that i need to echo
"created_at": "2019-07-05T09:34:21Z",
"updated_at": "2019-07-05T09:34:22Z",
"email": "testemail#gmail.com",
"data": null,
"storage_state": "cached",
"test": false,
"metadata": null,
"callback_url": null,
"last_four_digits": "4242",
"first_six_digits": "424242",
"card_type": "visa",
"first_name": "First",
"last_name": "Last",
"month": 6,
"year": 2022,
"address1": null,
"address2": null,
"city": null,
"state": null,
"zip": "1000",
"country": null,
"phone_number": null,
"company": null,
"full_name": "Test Test",
"eligible_for_card_updater": true,
"shipping_address1": null,
"shipping_address2": null,
"shipping_city": null,
"shipping_state": null,
"shipping_zip": null,
"shipping_country": null,
"shipping_phone_number": null,
"payment_method_type": "credit_card",
"errors": [],
"fingerprint": "eeebce09a3bf9fba352df975a5c999998",
"verification_value": "XXX",
"number": "XXXX-XXXX-XXXX-4242"
}
} }
You can use json_decode with true as second parameter to convert it into array,
echo 'token: '.$arr['transaction']['payment_method']['token']."\n";
echo 'message: '.$arr['transaction']['message'];
Demo.
Output:
token: BXtwsBABZ2z15DkyN5dbTWrwakV
message: Succeeded!

in php ! how to extract a variable value of a response (json) and echo it

i get a response of my code . that response has a variable value which is before a constant string and after another constant string . i want get this variable and echo it .
example : i have this json:
{ "id": "tok_1Cs0osBsNOaFjmrSIBFEAkPd", "object": "token", "client":
{ "id": "card_1Cs0osBsNOaFjmrSl9fAs5hT", "object": "name", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": "74455", "address_zip_check": "unchecked", "country": "RU", "metadata": {}, "name": "2022 Nemelek\r\n", "tokenization_method": null }, "client_ip": "41.199.157.183", "created": 1532578278, "livemode": true, "type": "Uid", "used": false }
i wanna extract tok_1Cs0osBsNOaFjmrSIBFEAkPd which is after { "id": " and before ", "object":
btw : this value is variable but what is before and first word after it are constants
how can i code it in php
Use json_decode():
$str = '{ "id": "tok_1Cs0osBsNOaFjmrSIBFEAkPd", "object": "token", "client": { "id": "card_1Cs0osBsNOaFjmrSl9fAs5hT", "object": "name", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": "74455", "address_zip_check": "unchecked", "country": "RU", "metadata": {}, "name": "2022 Nemelek\r\n", "tokenization_method": null }, "client_ip": "41.199.157.183", "created": 1532578278, "livemode": true, "type": "Uid", "used": false }';
$v = json_decode($str);
//tok_1Cs0osBsNOaFjmrSIBFEAkPd
echo $v->id;

Searching Stripe's JSON response value with PHP

I know this question has been done several times, but after a few tests I really cant figure ho to do this.
I'm implementing SEPA payments with Stripe. I've managed to POST all the infos to Stripe, but having a hard time getting a value within the JSON response.
here it is and what I need is the "mandate_url" value toward the end:
{
"id": "XXXXXXXXXXX",
"object": "customer",
"account_balance": 0,
"created": XXXXXXXXXXX,
"currency": null,
"default_source": "XXXXXXXXXXX",
"delinquent": false,
"description": null,
"discount": null,
"email": null,
"livemode": true,
"metadata": {},
"shipping": null,
"sources": {
"object": "list",
"data": [
{
"id": "XXXXXXXXXXX",
"object": "source",
"amount": null,
"client_secret": "XXXXXXXXXXX",
"created": XXXXXXXXXXX,
"currency": "eur",
"customer": "XXXXXXXXXXX",
"flow": "none",
"livemode": true,
"metadata": {},
"owner": {
"address": {
"city": "XXXXXXXXXXX",
"country": "XXXXXXXXXXX",
"line1": null,
"line2": null,
"postal_code": "00000",
"state": null
},
"email": null,
"name": "John Doe",
"phone": null,
"verified_address": null,
"verified_email": null,
"verified_name": null,
"verified_phone": null
},
"status": "chargeable",
"type": "sepa_debit",
"usage": "reusable",
"sepa_debit": {
"bank_code": "XXXXXXXXXXX",
"branch_code": "XXXXXXXXXXX",
"country": "XXXXXXXXXXX",
"fingerprint": "XXXXXXXXXXX",
"last4": "XXXXXXXXXXX",
"mandate_reference": "XXXXXXXXXXX",
"mandate_url": "https://hooks.stripe.com/adapter/sepa_debit/file/random_keys"
}
}
],
"has_more": false,
"total_count": 1,
"url": "XXXXXXXXXXX"
},
"subscriptions": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "XXXXXXXXXXX"
}
}
isn't there any way to get it without creating an enormous foreach?
thanks :)
first off you're json was invalid as you had several instances of "created": XXXXXXXXXXX, so below is corrected json and example of using json_decode
<?php
$json = '{
"id": "XXXXXXXXXXX",
"object": "customer",
"account_balance": 0,
"created": "XXXXXXXXXXX",
"currency": null,
"default_source": "XXXXXXXXXXX",
"delinquent": false,
"description": null,
"discount": null,
"email": null,
"livemode": true,
"metadata": {},
"shipping": null,
"sources": {
"object": "list",
"data": [{
"id": "XXXXXXXXXXX",
"object": "source",
"amount": null,
"client_secret": "XXXXXXXXXXX",
"created": "XXXXXXXXXXX",
"currency": "eur",
"customer": "XXXXXXXXXXX",
"flow": "none",
"livemode": true,
"metadata": {},
"owner": {
"address": {
"city": "XXXXXXXXXXX",
"country": "XXXXXXXXXXX",
"line1": null,
"line2": null,
"postal_code": "00000",
"state": null
},
"email": null,
"name": "John Doe",
"phone": null,
"verified_address": null,
"verified_email": null,
"verified_name": null,
"verified_phone": null
},
"status": "chargeable",
"type": "sepa_debit",
"usage": "reusable",
"sepa_debit": {
"bank_code": "XXXXXXXXXXX",
"branch_code": "XXXXXXXXXXX",
"country": "XXXXXXXXXXX",
"fingerprint": "XXXXXXXXXXX",
"last4": "XXXXXXXXXXX",
"mandate_reference": "XXXXXXXXXXX",
"mandate_url": "https://hooks.stripe.com/adapter/sepa_debit/file/random_keys"
}
}],
"has_more": false,
"total_count": 1,
"url": "XXXXXXXXXXX"
},
"subscriptions": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "XXXXXXXXXXX"
}
}';
$data = json_decode($json);
$mandate_url = $data->sources->data[0]->sepa_debit->mandate_url);
echo $mandate_url;
?>
Alternatively you could get the json into an associative array and use the following syntax
$data = json_decode($json, true);
$mandate_url = $data['sources']['data'][0]['sepa_debit']['mandate_url'];
echo $mandate_url;

PHP - Access JSON Array

I am trying to access a value in my JSON Array. This is my PHP code to get the JSON content:
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event = \Stripe\Event::retrieve($event_id);
This is the output:
Stripe\Event JSON: {
"id": "evt_6WV8LzHBPwRYW4",
"created": 1435683755,
"livemode": false,
"type": "charge.succeeded",
"data": {
"object": {
"id": "ch_6WV8a3Sdj3ihE2",
"object": "charge",
"created": 1435683755,
"livemode": false,
"paid": true,
"status": "succeeded",
"amount": 5000,
"currency": "usd",
"refunded": false,
"source": {
"id": "card_6WV8kV4c36X1Gl",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 2,
"exp_year": 2022,
"fingerprint": "QXn7Az3ZTTaLBbhx",
"country": "US",
"name": "oliverbusk#hotmail.com",
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": null,
"address_country": null,
"cvc_check": "pass",
"address_line1_check": null,
"address_zip_check": null,
"tokenization_method": null,
"dynamic_last4": null,
"metadata": [],
"customer": "cus_6WV87uyazq5L64"
},
"captured": true,
"balance_transaction": "txn_6WV8Bz6aZSB3tb",
"failure_message": null,
"failure_code": null,
"amount_refunded": 0,
"customer": "cus_6WV87uyazq5L64",
"invoice": null,
"description": null,
"dispute": null,
"metadata": {
"product": "deposit"
},
"statement_descriptor": null,
"fraud_details": [],
"receipt_email": null,
"receipt_number": null,
"shipping": null,
"destination": null,
"application_fee": null,
"refunds": {
"object": "list",
"total_count": 0,
"has_more": false,
"url": "\/v1\/charges\/ch_6WV8a3Sdj3ihE2\/refunds",
"data": []
}
}
},
"object": "event",
"pending_webhooks": 1,
"request": "iar_6WV8y99x1gReuF",
"api_version": "2015-06-15"
}
To be specific, I wish to access the data->metadata->product value - which in this example is "deposit"
This is how I am trying to access it:
$event->data->metadata->product;
Although that returns blank.
What am I doing wrong?
There is an object property under data. Do a print_r() on $event to see the structure.
Use: $event->data->object->metadata->product
You can see in the print_r():
stdClass Object
(
[id] => evt_6WV8LzHBPwRYW4
.....
[data] => stdClass Object
(
[object] => stdClass Object
(
.....
[metadata] => stdClass Object
(
[product] => deposit
)

Trying to parse JSON using PHP

This is my json response but when I am trying to decode the Json string I got the NULL error. When i fix the same json output in online decode it works properly. What is the problem here? I can't fix the error.
{
"amount": 474,
"created": 1414385307,
"currency": "usd",
"id": "-snip-",
"livemode": false,
"paid": true,
"refunded": false,
"disputed": null,
"captured": true,
"description": null,
"statement_description": null,
"failure_message": null,
"failure_code": null,
"amount_refunded": 0,
"customer": "-snip-",
"invoice": null,
"refunds": {
"data": [],
"total_count": 0,
"has_more": false,
"url": "/v1/charges/-snip-/refunds",
"count": null
},
"card": {
"exp_month": 11,
"exp_year": 2025,
"last4": "-snip-",
"country": "US",
"type": null,
"name": null,
"id": "-snip-",
"customer": "-snip-",
"recipient": null,
"address_line1": null,
"address_line2": null,
"address_zip": null,
"address_city": null,
"address_state": null,
"address_country": null,
"address_zip_check": null,
"address_line1_check": null,
"cvc_check": null,
"fingerprint": "-snip-",
"brand": "Visa",
"funding": "credit"
},
"dispute": null,
"balance_transaction": "-snip-",
"metadata": {}
}
PHP code:
$curl = curl_init($service_url);
$curl_post_data = array(
'customerId' => 'Cus_id',
'amount' => 474
);
$data = json_encode($curl_post_data);
$headers = array('Content-type: application/json');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$json=str_replace("JSON: ","","$curl_response");
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Pass that entire string to json_decode() and it will work.
Try this one
$str = '{ "amount": 474, "created": 1414385307, "currency": "usd", "id": "-snip-", "livemode": false, "paid": true, "refunded": false, "disputed": null, "captured": true, "description": null, "statement_description": null, "failure_message": null, "failure_code": null, "amount_refunded": 0, "customer": "-snip-", "invoice": null, "refunds": { "data": [], "total_count": 0, "has_more": false, "url": "/v1/charges/-snip-/refunds", "count": null }, "card": { "exp_month": 11, "exp_year": 2025, "last4": "-snip-", "country": "US", "type": null, "name": null, "id": "-snip-", "customer": "-snip-", "recipient": null, "address_line1": null, "address_line2": null, "address_zip": null, "address_city": null, "address_state": null, "address_country": null, "address_zip_check": null, "address_line1_check": null, "cvc_check": null, "fingerprint": "-snip-", "brand": "Visa", "funding": "credit" }, "dispute": null, "balance_transaction": "-snip-", "metadata": {} }';
$data = json_decode($str);
print_r($data);

Categories