This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I have tried getting a response from my request but it didn't work.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.monnify.com/api/v1/bank-transfer/reserved-accounts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\n \"accountReference\": \"0111443-JP098\",\n \"accountName\": \"Joe Philips\",\n \"currencyCode\": \"NGN\",\n \"contractCode\": \"6146592431\",\n \"customerEmail\": \"jp#tester.com\",\n \"customerName\": \"Joe Philips\",\n \"incomeSplitConfig\": [\n {\n \"subAccountCode\": \"MFY_SUB_275274693326\",\n \"feePercentage\": 10.5,\n \"splitPercentage\": 20,\n \"feeBearer\": true\n }\n ]\n}",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibW9ubmlmeS1wYXltZW50LWVuZ2luZSJdLCJzY29wZSI6WyJwcm9maWxlIl0sImV4cCI6MTU5NzI2MzAyNCwiYXV0aG9yaXRpZXMiOlsiTVBFX01BTkFHRV9MSU1JVF9QUk9GSUxFIiwiTVBFX1VQREFURV9SRVNFUlZFRF9BQ0NPVU5UIiwiTVBFX0lOSVRJQUxJWkVfUEFZTUVOVCIsIk1QRV9SRVNFUlZFX0FDQ09VTlQiLCJNUEVfQ0FOX1JFVFJJRVZFX1RSQU5TQUNUSU9OIiwiTVBFX1JFVFJJRVZFX1JFU0VSVkVEX0FDQ09VTlQiLCJNUEVfREVMRVRFX1JFU0VSVkVEX0FDQ09VTlQiLCJNUEVfUkVUUklFVkVfUkVTRVJWRURfQUNDT1VOVF9UUkFOU0FDVElPTlMiXSwianRpIjoiYTQ5YjIxNDgtNTJkMy00ZGI1LTg2NGYtYzdiM2NjM2M4NzUzIiwiY2xpZW50X2lkIjoiTUtfVEVTVF9DSFZRRlJBN1NHIn0.mqwi5y7wnXpBCk6R9dC3ORhf9pNkwHVOCJr2SHUfk9TFYpVMnGuBUVyxJFOwLHROyKVodquPr1eS2AT1nTUDCrW0YXlX9tX5BPrfckvDoPPza7Klc8uQrw1aVxF6sAK-hFZgC79lKOq9gowOqWP1frbJ5BqozZfYiQ6ZsZcf2LubDOoen_G6_13wGtCM58-9BcY6aMKv--Vxr0AFwSqujBMny1D-x2SgsqT98asoYvtaHGtiC4MbVg-jFwwJuG4BYststO0k1J0YI5frpyLyQfaNEJSR6Y-WJiCqFWIDpHgDFINl65xtMIE_15OV2BKfBsruCo5mkx_rHPH_4_tXWw"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
These is the request code in curl, and below is the response
{
"requestSuccessful": true,
"responseMessage": "success",
"responseCode": "0",
"responseBody": {
"contractCode": "6146592431",
"accountReference": "abc123",
"accountName": "Test Reserved Account",
"currencyCode": "NGN",
"customerEmail": "test#tester.com",
"accountNumber": "3000004533",
"bankName": "Providus Bank",
"bankCode": "101",
"collectionChannel": "RESERVED_ACCOUNT",
"reservationReference": "W3HP7E6VZP78TUKV4U9E",
"reservedAccountType": "GENERAL",
"status": "ACTIVE",
"createdOn": "2020-08-12 18:56:49.0",
"contract": {
"name": "Default Contract",
"code": "6146592431",
"description": null,
"supportsAdvancedSettlementAccountSelection": false,
"sweepToExternalAccount": false
},
"transactionCount": 0,
"restrictPaymentSource": false
}
}
In all of the response body, I need just the following response;
"accountNumber": "3000004533",
"customerEmail": "test#tester.com",
"bankName": "Providus Bank",
Please, how do I get this done.
Parse json string to PHP object or array and then you get it. Get your info to $rp variable
...
$response = curl_exec($curl);
$obj = json_decode($response, true);
$i = 0;
$nw= array_filter($obj['responseBody'], function($v,$k){
return in_array($k, ['accountNumber', 'customerEmail', 'bankName']);
}, ARRAY_FILTER_USE_BOTH);
$i=0;
foreach($nw as $k => $v){
$last = $i !== count($nw)-1 ? ','.PHP_EOL : '';
echo "\"$k\": \"$v\"".$last;
$i++;
}
curl_close($curl);
EDIT: Just show the result in the
Related
I am trying to send a message to Discord Webhook, with Components.
I have tried normal message and embed, and both give me the same result. I get the message, but not the components.
Syntax From here: https://discord.com/developers/docs/interactions/message-components
Here is my code:
<?php
$url = "https://discord.com/api/webhooks/1234567890";
$content = '{
"content": "This is a message with components.",
"components": [
{
"type": 1,
"components": [
{
"type": 2,
"label": "Click me!",
"style": 1,
"custom_id": "click_one"
}
]
}
]
}';
$curl = curl_init();
$headers = array('Content-Type: application/json');
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $content,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => true
));
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
var_dump($response);
Here is the var_dump of the response:
I am trying to loop an array of fixtures using foreach and this works fine. However I want to pick the {fixtuteID} from the fixtures loop and put it in the predictions api endpoint
Api call for fixtures
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/fixtures?date=2xx1-06-10&timezone=XXXXX",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Api call for predictions which requires {fixtuteID} from the above
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/predictions?fixture={fixtuteID}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Below is the loop I would like.
fixture 1 and prediction-fixture 1
fixture 2 and prediction-fixture 2
fixture 3 and prediction-fixture 3
fixture 4 and prediction-fixture 4
end loop
EDIT: my loop
$fixture = curl_exec($curl);
$fs = json_decode($fixture, true);
$fixtures = $fs['response'];
//get error
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
foreach($fixtures as $fx){
//fixture ID {fixtuteID}
echo $fx['fixture']['id'];
//I wand to add the prediction here like this-- echo $pr['prediction']."<br>";
}
}
And that loop gives me
fixture 1
fixture 2
fixture 3
fixture 4
EDIT I want to get the
"predictions->winner->id": 2232,->name": "Sao Jose",->comment": "Win or draw"
},
The json response from the predictions call is as below.
{
"get": "predictions",
"parameters": {
"fixture": "840715"
},
"errors": [
],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [
{
"predictions": {
"winner": {
"id": 2232,
"name": "Sao Jose",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": null,
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Double chance : Sao Jose or draw",
"percent": {
"home": "50%",
"draw": "50%",
"away": "0%"
}
},
"league": {
"id": 75,
"name": "Serie C",
"country": "Brazil",
"logo": "https://media.api-sports.io/football/leagues/75.png",
"flag": "https://media.api-sports.io/flags/br.svg",
"season": 2022
},
where I want to pick predictions -> winner -> id for each fixture in the loop.
It's not entirely clear where you got stuck with this, but it seems like the neatest way would be to put the cURL code in a function and then call the function from the loop. (Of course you could put the cURL code directly in the looop but it would clutter it up a bit.)
foreach($fixtures as $fx)
{
//fixture ID
echo $fx['fixture']['id'];
echo getPrediction($fx["fixture"]["id"])."<br>";
}
function getPrediction($fixtureID)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/predictions?fixture=
$fixtureID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
I want to create envelope using DocuSign API in my web application. When I run it in postman then response showing object move with html content
This is my php code sample
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://account-d.docusign.com/v2.1/accounts/b15b77b0-9345-4780-bfc1-440b37991820/envelopes?change_routing_order=true',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"documents": [
{
"documentBase64": "Base64 code of my pdf file",
"documentId": "5865888",
"fileExtension": "pdf",
"name": "test pdf"
}
],
"emailSubject": "test pdf",
"recipients": {
"signers": [
{
"name": "User full name",
"email": "user#gmail.com",
"recipientId": "8959555"
}
]
},
"status": "send "
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: [{"key":"Authorization","value":"Bearer {{accessToken}}"}]'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
My API response is
Object moved to here.
Please guide me how to solve the issue
Thank You
That base URL is incorrect. Account-d.docusign.com is only for authentication.
Requests should be made to {SERVER}/restapi/v2.1
So for you it would be demo.docusign.net/restapi/v2.1/accounts/{ACCOUNT_ID/envelopes
Here's the dev centre article showing the whole process
How do I pass multidimensional associative array or a json as a payload to cURL request. I have been trying to wrap my head around this for sometime now without any success.
Here is what I have done so far. I make a curl request and pass a json to the CURLOPT_POSTFIELDS fields. This works alright. The problem is I want the code to run for multiple users which are in a json string saved in a variable
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url/tokens',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"customerName": "orland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123456",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The above code works fine.
But the payload for CURLOPT_POSTFIELDS is not fixed.
So this is what I tried doing, I encoded the json string and tried passing it to a for loop. I am sure the approach isn't bad, but I am not getting the syntax quite right. Here is my code.
<?php
$recip = '[{
"customerName": "Sorland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123346",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
},
{
"customerName": "Corland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123678",
"description": "Awaiting",
"reference": "0jsbfbsubfhbj"
},
{
"customerName": "orland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123111",
"description": "Awaiting",
"reference": "1234568djnfjnfjds"
}]';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>
echo ("'{<br>");
foreach($arr[$keys[$i]] as $key => $value) {
echo implode($key . " : " . $value . ",<br>");
}
echo "}',<br>";
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
I want to use a for loop to make multiple curl request with different payloads, and the payloads are coming from the json data above. I converted the json to an array to be able to loop through and converted it back to a json for CURLOPT_POSTFIELDS.
This seems a simpler way to make multiple call to curl and save the responses, hope I got the right end of the stick this time :)
$recip =
'[
{"customerName": "Sorland", "mno": "Network", "amount": "1",
"msisdn": "447911123346","description": "Awaiting","reference": "0fgdufgdfgdfs"
},
{"customerName": "Corland","mno": "MTN","amount": 1,
"msisdn": "447911123678","description": "Awaiting","reference": "0jsbfbsubfhbj"
},
{"customerName": "orland","mno": "MTN","amount": 1,"msisdn": "447911123111",
"description": "Awaiting","reference": "1234568djnfjnfjds"
}
]';
// make a PHP datatype out of the JSON so you can use it
$recipients = json_decode($recip);
$responses = [];
foreach ( $recipients as $r) {
$curl = curl_init();
// convert $r back to json so it can be passed as param
$postfield = json_encode($r);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postfield,
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$response[] = curl_exec($curl);
// if you need to know which customer the response was for
// use this next line instead, for example
//$response[$r->customerName] = curl_exec($curl);
curl_close($curl);
}
// this is now an array of all responses
print_r($responses);
Below is my CURL request. Im trying to pull data from a CRM called pipedrive. The URL is pulling the data correctly but for some reason its not displaying on my website.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.pipedrive.com/v1/persons/find?term=devonvermaak2%40gmail.com&start=0&search_by_email=1&api_token=e7f91c84dad486160a9744f4972d7f742de3d",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-length": "217",
"content-type": "application/json",
"x-ratelimit-limit": "20",
"x-ratelimit-remaining": "19",
"x-ratelimit-reset": "2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//because of true, it's in an array
$response = json_decode($response, true);
echo 'Name: '. $response['data']['name']. '<br />';
echo 'Email: '. $response['data']['email']. '<br />';
echo 'Phone: '. $response['data']['phone'];
Its not showing the data at all. Is there something wrong with my code?
Note: I've edited the api token for security purposes..
since your $response is
{
"success": true,
"data": [
{
"id": 91235,
"name": "Devon Vermaak",
"email": "devonvermaak2#gmail.com",
"phone": "0555877857",
"org_id": null,
"org_name": "",
"visible_to": "3"
}
],
"additional_data": {
"search_method": "search_by_email",
"pagination": {
"start": 0,
"limit": 100,
"more_items_in_collection": false
}
}
}
you can see that the data is an array
hence, you can access the values via its index. Ex
$response['data'][0]['name'] returns Devon Vermaak
echo 'Name: '. $response['data'][0]['name']. '<br />';
echo 'Email: '. $response['data'][0]['email']. '<br />';
echo 'Phone: '. $response['data'][0]['phone'];
Wrong 'CURLOPT_HTTPHEADER' array values.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.pipedrive.com/v1/persons/find?term=devonvermaak2%40gmail.com&start=0&search_by_email=1&api_token=e7f91c84dad486160a9744f4972d7f742de3d",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control"=> "no-cache",
"content-length"=> "217",
"content-type"=> "application/json",
"x-ratelimit-limit"=> "20",
"x-ratelimit-remaining"=> "19",
"x-ratelimit-reset"=> "2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//because of true, it's in an array
$response = json_decode($response, true);
print_r($response);