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)
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?
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I tried to connect Coinmarketcap's API using PHP curl to take out the live bitcoin price out of it as a practice. The point is that the output it gives is way too confusing that I have got no idea about how should I take the "price" out of it. There were some similar questions around but unfortunately, the responses didn't help me. So I was wondering how is it possible to take the price of bitcoin out of the return given by API? It seems like I'm misunderstanding arrays and objects since I'm still a newbie.
This is what "die and dump" returns:
#data: array:1 [▼
"response" => """
{
"status": {
"timestamp": "2019-04-15T14:03:35.573Z",
"error_code": 0,
"error_message": null,
"elapsed": 5,
"credit_count": 1
},
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"circulating_supply": 17646787,
"total_supply": 17646787,
"max_supply": 21000000,
"date_added": "2013-04-28T00:00:00.000Z",
"num_market_pairs": 7253,
"tags": [
"mineable"
],
"platform": null,
"cmc_rank": 1,
"last_updated": "2019-04-15T14:02:29.000Z",
"quote": {
"USD": {
"price": 5166.87433557,
"volume_24h": 11238888046.6075,
"percent_change_1h": 0.0140845,
"percent_change_24h": 1.39641,
"percent_change_7d": -0.981349,
"market_cap": 91178730855.57031,
"last_updated": "2019-04-15T14:02:29.000Z"
}
}
}
]
}
"""
]
Here is the code which requests from API:
function apiGet($url)
{
$parameters = [
'start' => '1',
'limit' => '3',
];
$query = http_build_query($parameters);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30000,
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept-Encoding: deflate, gzip',
'X-CMC_PRO_API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
),
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
return view('price', compact('response'));
}
$parameters = [
'start' => '1',
'limit' => '1',
];
$query = http_build_query($parameters);
$btc = new \App\Http\Controllers\CoinsController();
$result = $btc->apiGet('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'."?".$query);
dd($result);
That's a nested key value array that contains a json string. You can get the price like this:
$price = json_decode($result['response'])->data[0]->quote->USD->price;
Also for your knowledge. You can use the Arr::get() helper provided by Laravel. See docs:
use \Illuminate\Support\Arr;
...
$data = json_decode($result['response'], true);
$price = Arr::get($data, 'data.0.quote.USD.price');
I am using #unificationengine API to send message on facebook.
Details I have given while registering my APP on facebook:
site url : http://localhost:3000
Email adress and other required details
In unificationengine API I have used all the curls mentioned in their documentation step by step as follows:
1. Created user using API key and Secret
2. Added connection
3. test connection
4. Refresh connection
5. Send message
All 4 gave 200 success code but send message gives 403 fobidden error.
The curl I am using for this is as below:
$post_msg = json_encode(
array(
'message' =>
array(
'receivers' =>
array(
array(
'name' => 'Me',
'address' => 'https://graph.facebook.com/v2.5/me/feed',
'Connector' => 'facebook'
),
),
'sender' =>
array('address' => ''),
'subject' => 'Hello',
'parts' =>
array(
array(
'id' => '1',
'contentType' => 'text/plain',
'data' => 'Hi welcome to UE',
'size' => 100,
'type' => 'body',
'sort' => 0
),
),
),
)
);
$ch = curl_init('https://apiv2.unificationengine.com/v2/message/send');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_USERPWD,'3f43c37b-a066-4cc4-a3be-33faf72d6a21:2722fc72d-5d347-4a3a-a82b-0c1ss51aafb4');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_msg);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
return ['label' =>$response];
I am trying to figure this. But no success.
Again I like to mention that I am using this on localhost, could that be the reason for forbidden error? If so then facebook graph api from which we get access token should also give such error.
Earlier I have posted this question, here also I didn't find right solution. I added Curl options that is mentioned in comment of my question there but it didn't changed the things.
Any help would be highly appreciated.
Error Message:
{\"Status\":{\"facebook\":{\"status\":403,\"info\":\"Forbidden:
\"}},\"URIs\":[]}
UPDATE
Below is the json I get when I run me/permissions in facebook graph API explorer:
{
"data": [
{
"permission": "user_birthday",
"status": "granted"
},
{
"permission": "user_about_me",
"status": "granted"
},
{
"permission": "user_status",
"status": "granted"
},
{
"permission": "user_posts",
"status": "granted"
},
{
"permission": "email",
"status": "granted"
},
{
"permission": "manage_pages",
"status": "granted"
},
{
"permission": "publish_actions",
"status": "granted"
},
{
"permission": "public_profile",
"status": "granted"
}
]
}
I have resolved this problem:
public function facebookSharing($access_token) {
$app = new UEApp(env('UNIFICATION_APP_KEY'), env('UNIFICATION_APP_SECRATE'));
$user = new UEUser('unification_userkey', 'unification_usersecret');
$connection = $user->add_connection('FACEBOOK', "facebook", $access_token);
$options = array(
"receivers" => array(
array(
"name"=> "Me"
)
),
"message"=>array(
"subject"=>'testing',
"body"=> 'description',
"image"=> 'use any image url',
"link"=>array(
"uri"=> 'any web site url',
"description"=> "",
"title"=>"Title"
)
)
);
$uris = $connection->send_message($options);
}
Please use your keys like
facebook accesstoken
UNIFICATION_APP_KEY (its your unification keys)
UNIFICATION_APP_SECRATE (its your unification keys)
If this will not work then please let me know.
Can you please confirm if the "Connector" name that you have given is correct?
While I tried your sample code that you provided, I could sent the message to facebook via UE.
Can you please provide the exact error message that is returned while you execute the command?
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}]";
<?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.