I am having trouble getting any data out of a mashape API, I have made the UNIREST POST but I am unable to echo the data back to myself, this is what the call should return;
{
"result": {
"name": "The Elder Scrolls V: Skyrim",
"score": "92",
"rlsdate": "2011-11-11",
"genre": "Role-Playing",
"rating": "M",
"platform": "PlayStation 3",
"publisher": "Bethesda Softworks",
"developer": "Bethesda Game Studios",
"url": "http://www.metacritic.com/game/playstation-3/the-elder-scrolls-v-skyrim"
}
}
And my code...
require_once 'MYDIR/mashape/unirest-php/lib/Unirest.php';
$response = Unirest::post(
"https://byroredux-metacritic.p.mashape.com/find/game",
array(
"X-Mashape-Authorization" => "MY API AUTH CODE"
),
array(
"title" => "The Elder Scrolls V: Skyrim",
"platform" => undefined
)
);
echo "$response->body->name";
?>
Can anyone suggest how I can get it to echo the "name".
Any help would be appreciated :)
It appears the way you are trying to display the body is preventing you from seeing an error in the response telling you that the property platform is required to be a number.
Try using json_encode($response->body) instead to see the full response:
<?php
require_once 'lib/Unirest.php';
$response = Unirest::post(
"https://byroredux-metacritic.p.mashape.com/find/game",
array(
"X-Mashape-Authorization" => "-- your authorization key goes here --"
),
array(
"title" => "The Elder Scrolls V: Skyrim",
"platform" => 1 # try placing undefined here.
)
);
echo json_encode($response->body);
?>
Once you've gotten the response you can then use $response->body->result->name:
$result = $response->body->result;
echo "{$result->name} has a score of [{$result->score}]";
Related
I am using the MPESA-Express also called the STK push api V1 to receive payments from my clients.
To get the customer paying, I am looking for the PhoneNumber value in the results body of the response if the payment is successful. This way I can associate a payment with a customer.
However now that we'll be having data minimisation on the MPesa api, the PhoneNumber will not be displayed fully, and I am facing a challenge of how to associate a payment transaction with a client. I have tried setting the AcccountReference in the request as shown below, but I can't get this AccountReference back in the response results body. I was thinking of setting a unique AcccountReference for each customer.
The data I am sending to the endpoint https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
$postData = json_encode([
"BusinessShortCode" => Yii::$app->params['businessShortCode'],
"Password" => $this->createMpesaRequestsPassword($timestamp),
"Timestamp" => $timestamp,
"TransactionType" => $transactionType,
"Amount" => $amount,
"PartyA" => $phoneNumber,
"PartyB" => Yii::$app->params['businessShortCode'],
"PhoneNumber" => $phoneNumber,
"CallBackURL" => $callBackUrl,
"AccountReference" => $phoneNumber,
"TransactionDesc" => $transactionDesc
]);
On my callback url I get this response:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "9183-42212949-1",
"CheckoutRequestID": "ws_CO_23072022133552132714385056",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{
"Name": "Amount",
"Value": 1
},
{
"Name": "MpesaReceiptNumber",
"Value": "QGN2XSH6MQ"
},
{
"Name": "Balance"
},
{
"Name": "TransactionDate",
"Value": 20220723133617
},
{
"Name": "PhoneNumber",
"Value": 254711111111
}
]
}
}
}
}
How do know which transaction belongs to which user?
I am trying to set up wav -> mp3 conversion through AWS, I've followed documentation closely but I can't find anything about the problem I am facing so hoping someone can help here. Here is my code to start a conversion on AWS:
$job_settings = '{
"TimecodeConfig": {
"Source": "ZEROBASED"
},
"OutputGroups": [
{
"Name": "File Group",
"Outputs": [
{
"ContainerSettings": {
"Container": "RAW"
},
"AudioDescriptions": [
{
"AudioTypeControl": "FOLLOW_INPUT",
"AudioSourceName": "Audio Selector 1",
"CodecSettings": {
"Codec": "MP3",
"Mp3Settings": {
"Bitrate": 192000,
"Channels": 2,
"RateControlMode": "CBR",
"SampleRate": 48000
}
},
"LanguageCodeControl": "FOLLOW_INPUT"
}
]
}
],
"OutputGroupSettings": {
"Type": "FILE_GROUP_SETTINGS",
"FileGroupSettings": {
"Destination": "{DESTINATION}"
}
}
}
],
"AdAvailOffset": 0,
"Inputs": [
{
"AudioSelectors": {
"Audio Selector 1": {
"Tracks": [
1
],
"Offset": 0,
"DefaultSelection": "DEFAULT",
"SelectorType": "TRACK",
"ProgramSelection": 1
}
},
"FilterEnable": "AUTO",
"PsiControl": "USE_PSI",
"FilterStrength": 0,
"DeblockFilter": "DISABLED",
"DenoiseFilter": "DISABLED",
"InputScanType": "AUTO",
"TimecodeSource": "ZEROBASED",
"FileInput": "{INPUT}"
}
]
}';
//Job starts here
$job_settings = json_decode($job_settings, true);
$convert_client = new MediaConvertClient(array(
'version' => '2017-08-29',
'region' => $this->login_details->region,
'credentials' => $this->credentials
));
try {
$res = $convert_client->describeEndpoints([]);
} catch(AwsException $e) {
//echo $e->getMessage();
return null;
}
//print_r($res);
$single_endpoint = $res['Endpoints'][0]['Url'];
$convert_client = new MediaConvertClient(array(
'version' => '2017-08-29',
'region' => $this->login_details->region,
'credentials' => $this->credentials,
'endpoint' => $single_endpoint
));
$res = $client->createJob(array(
"Role" => "arn:aws:iam::{$this->login_details->account_number}:role/MediaConvert_Default_Role",
"Settings" => $job_settings,
"Queue" => "arn:aws:mediaconvert:{$this->login_details->region}:{$this->login_details->account_number}:queues/Default"
));
I grabbed the JSON by creating a conversion job on AWS Console and copying the JSON of the job, the destination and input tags are replaced in the json before decoding to assoc array however I am getting an error of the following:
Error executing "CreateJob" on "aws_url"; AWS HTTP error: Client error: POST aws_url resulted in a 400 Bad Request response: { "errorType": "BadRequestException", "httpStatus" : 400, "requestId" : "-----------", (truncated...) BadRequestException (client): /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings: Should match exactly one schema defined in "oneOf" | /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings: Should have at least 2 properties | /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings/codec: Should be equal to one of the allowed values in ["PASSTHROUGH","OPUS","VORBIS"]
This is using aws-3.93.3 PHP SDK. Any idea why this happens? Of course the job runs perfectly fine if ran through console.
Actually I just found what I suspected was the case; this version of the library does not yet support MP3 ingestion as outlined here:
https://github.com/aws/aws-sdk-php/blob/master/CHANGELOG.md
Updating to the newest version solved this issue.
I'm trying to create a card with my webhook service. my website is in php but I don't know how to respond to api.ai in a way to display my result in card format on client's phone. I ask my question with more detail in here.
Considering, you know receiving and checking action from Api.ai request in php
For responding with the card, you can use this:
$request== file_get_contents("php://input");
$messages=[];
// Building Card
array_push($messages, array(
"type"=> "basic_card",
"platform"=> "google",
"title"=> "Card title",
"subtitle"=> "card subtitle",
"image"=>[
"url"=>'http://image-url',
"accessibility_text"=>'image-alt'
],
"formattedText"=> 'Text for card',
"buttons"=> [
[
"title"=> "Button title",
"openUrlAction"=> [
"url"=> "http://url redirect for button"
]
]
]
)
);
// Adding simple response (mandatory)
array_push($messages, array(
"type"=> "simple_response",
"platform"=> "google",
"textToSpeech"=> "Here is speech and additional msg for card"
)
);
$response=array(
"source" => $request["result"]["source"],
"speech" => "Speech for response",
"messages" => $messages,
"contextOut" => array()
);
json_encode($response);
Make sure you don't push more than one card and have 'simple response' with it.
Im creating a simple web application in php that consume the adaptivePayments/Pay Api of paypal, I made some test using POSTMAN and everything works fine, I make the initial request and I get my payKey, also with this payKey I can check the status of the transaction using the /AdaptivePayments/PaymentDetails Api, the problem is when I try to make the request via php code:
$endpoint = 'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay';
$payload['actionType'] = "PAY";
$payload['clientDetails']['applicationId'] = "APP-80W284485P519543T";
$payload['clientDetails']['ipAddress'] = "xxx.xxx.xxx.xxx";
$payload['currencyCode'] = "USD";
$payload['feesPayer'] = "EACHRECEIVER";
$payload['memo'] = "Transaction";
$payload['receiverList']['receiver'] = $receivers;
$payload['requestEnvelope']['errorLanguage'] = "en_US";
$payload['returnUrl'] = "URL";
$payload['cancelUrl'] = "URL";
$json = json_encode($payload);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-SECURITY-USERID: ACCOUNT',
'X-PAYPAL-SECURITY-PASSWORD: PASSWORD',
'X-PAYPAL-SECURITY-SIGNATURE: SIGNATURE',
'X-PAYPAL-REQUEST-DATA-FORMAT: JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT: JSON',
'X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T',
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
));
$result = curl_exec($ch);
$receivers is a PHP array that contain information about emails and payment amounts, something like this:
Array
(
[0] => Array
(
[amount] => 19.8
[email] => client2-ubs#gmail.com
[primary] =>
)
[1] => Array
(
[amount] => 20.7
[email] => client1-ubs#gmail.com
[primary] =>
)
[2] => Array
(
[amount] => 45
[email] => store-ubs#gmail.com
[primary] => 1
)
)
I dont get any error, I even get the payKey which I use to create the html button so the user can pay for his goods, the problem is when I check the payment status /AdaptivePayments/PaymentDetails, Im getting:
{
"responseEnvelope": {
"timestamp": "2015-08-06T23:59:23.075-07:00",
"ack": "Success",
"correlationId": "bab22ca0bd887",
"build": "17603431"
},
"cancelUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"currencyCode": "USD",
"paymentInfoList": null,
"returnUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"status": "CREATED",
"payKey": "AP-8ML17897XK803351A",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"sender": {
"useCredentials": "false"
}
}
for some strange reason paymentInfoList is null, so the user see an error (transaction error) at the moment of click the paypal button.
As I said before, If i made the transaction using POSTMAN and then check the status I get a correct response:
{
"responseEnvelope": {
"timestamp": "2015-08-07T00:14:08.510-07:00",
"ack": "Success",
"correlationId": "b9049ba0d4cf1",
"build": "17603431"
},
"cancelUrl": "URL",
"currencyCode": "USD",
"memo": "Bank of souls payment",
"paymentInfoList": {
"paymentInfo": [
{
"receiver": {
"amount": "123.30",
"email": "client2-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "SLKM4ZQ5FMSHG"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "510.30",
"email": "client1-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "8PUDR7LSRS4MJ"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "704.00",
"email": "store-ubs#gmail.com",
"primary": "true",
"paymentType": "SERVICE",
"accountId": "E29BAQX7C7P3N"
},
"pendingRefund": "false"
}
]
},
"returnUrl": "URL",
"status": "CREATED",
"payKey": "AP-9MU4806743660523S",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"reverseAllParallelPaymentsOnError": "false",
"sender": {
"useCredentials": "false"
}
}
(paymentInfoList actually contains a json object with the goods, but this is doing the request manually using POSTMAN)
Could this be a PHP issue? some ideas to debug the curl connection will help me a lot.
PD: I have been debuging this the whole day, I even print_r the $json variable (i get the json format) and copy / paste directly in postman and its works, but for some reason the same request using curl is not sending the $receivers information.
Solved, I was making the requests (create the order and the request order information) using two different api credentials, also, it seems that paypal hide the order goods when receiving api credentials different than the originals, however still showing the state of the order (CREATE, COMPLETED, etc)
<?php
$appId = 'XXXXX';
$pageId = 'XXXXX';
$secret = 'XXXXX';
$token = 'XXXXX';
$data = array(
'access_token' => $token,
'description' => 'test_description',
'link' => 'http://www.google.co.uk',
'message' => 'test_message',
'name' => 'test_name'
);
try
{
require_once 'facebook/facebook.php';
$sdk = new Facebook(
array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
)
);
$post = $sdk->api('/'.$pageId.'/feed', 'POST', $data);
print_r($post);
}
catch (FacebookApiException $e)
{
echo $e;
}
?>
Using the code above I am trying to post a link to Google on my page wall. When I run the code, I get an ID response which is what I would expect. However nothing shows up on the page, despite having a valid ID.
If I remove the "link" and try again, I get another ID and the post is visible on my page.
Am I doing something wrong?
Why should the "link" value cause an ID to be returned but no post to be displayed?
This is what Facebook sees (queried via the Graph API explorer):
{
"id": "484729401573953",
"created_time": "2013-01-08T12:03:27+0000",
"caption": "www.readesresidential.com",
"description": "test_description",
"from": {
"name": "David Reade",
"id": "100003544363105"
},
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"link": "http://www.readesresidential.com/brookside-crescent-northop-hall-ch7-6hw-ps03009/",
"message": "test_message",
"name": "test_name",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQC7MpbP6aNe2CVP&w=90&h=90&url=http%3A%2F%2Fwww.readesresidential.com%2Fframework%2Fstatic-487d%2F2%2Fimg%2Fv3%2Ffacebook.png",
"privacy": {
"description": "Friends",
"value": "ALL_FRIENDS",
"allow": "",
"deny": "",
"networks": "",
"friends": ""
}
}
I can see it says "ALL_FRIENDS" - could this be what's causing the post to not be displayed? You can't be friends with a page can you?
I have now modified the "data" variable to the following:
$data = array(
'access_token' => $token,
'description' => 'test_description',
'link' => 'http://www.readesresidential.com/go/ps02618',
'message' => 'test_message',
'name' => 'test_name',
'privacy' => array(
'value' => 'EVERYONE'
)
);
The response from the Graph API explorer is:
{
"id": "454654274601000",
"created_time": "2013-01-08T12:14:52+0000",
"caption": "www.readesresidential.com",
"description": "test_description",
"from": {
"name": "David Reade",
"id": "100003544363105"
},
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"link": "http://www.readesresidential.com/church-street-tarvin-ch3-8eb-ps02618/",
"message": "test_message",
"name": "test_name",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQC7MpbP6aNe2CVP&w=90&h=90&url=http%3A%2F%2Fwww.readesresidential.com%2Fframework%2Fstatic-487d%2F2%2Fimg%2Fv3%2Ffacebook.png",
"privacy": {
"description": "Public",
"value": "EVERYONE",
"allow": "",
"deny": "",
"networks": "",
"friends": ""
}
}
Even though the post is now "public" and I have used a completely new URL, it's still not showing.
Could this be a Facebook bug?
Why should the "link" value cause an ID to be returned but no post to be displayed?
This usually happens if the same link is posted again by the same user (with only a certain amount of time between those two posts).
After some fiddling with the code, I found out how to fix this. Turns out the access token I was using was incorrect, even though the debugger tool said it was valid and had the appropriate permissions.
I had to query the Graph API, in particular the /me/accounts bit using the access token which returned the page info but and a completely different access token. This access token in question has no expiration time (I thought this feature was no more??) and after inserting it into my code, the posts now display properly for all users.
None of these steps were in the Facebook documentation anywhere, and if they are then they're extremely hard to find.