How to use curl with the MediaWiki API - php

I want to use mediawiki api to retrieve some informations with a symfony project, i want tu use curl to fo api calls,
I tried with
$ch=curl_init();
$postfield = "action=query&titles=Watch&prop=langlinks&lllimit=20";
$url = "https://en.wikipedia.org/w/api.php"; //url to wiki's api
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
but it does not work, it gives me boolean false as result

Here's a good example of using the PHP API using cURL from WikiMedia itself.
First, logging in:
/**
* Configuration
* -------------------------------------------------
*/
// Start session
session_start();
// Login
$app['username'] = "Example";
$app['password'] = "mypassword";
// Version
$app["version"] = "0.0.1-dev";
// Last modified
date_default_timezone_set("UTC");
$app["lastmod"] = date("Y-m-d H:i", getlastmod()) . " UTC"; // Example: 2010-04-15 18:09 UTC
// User-Agent used for loading external resources
$app["useragent"] = "My First Tool " . $app["version"] . " (LastModified: " . $app["lastmod"] . ") Contact: myfirsttool (at) example (.) com";
// Cookie file for the session
$app["cookiefile"] = tempnam("/tmp", "CURLCOOKIE");
// cURL to avoid repeating ourselfs
$app["curloptions"] =
array(
CURLOPT_COOKIEFILE => $app["cookiefile"],
CURLOPT_COOKIEJAR => $app["cookiefile"],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $app["useragent"],
CURLOPT_POST => true
);
$app["apiURL"] = "http://www.mediawiki.org/w/api.php";
Then to do the login using cookies:
/**
* Login
* -------------------------------------------------
*/
// Info: http://www.mediawiki.org/wiki/API:Login
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 003: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Basic error check + Confirm token
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "NeedToken") {
if (!empty($result["login"]["token"])) {
$_SESSION["logintoken"] = $result["login"]["token"];
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
"lgtoken" => $_SESSION["logintoken"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 004: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
} else {
$other_error = "Error 006: Token error.";
}
}
// Check for all documented errors
// Source: http://www.mediawiki.org/wiki/API:Login#Errors
// Date: 2010-04-17
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "Success") {
$_SESSION["login_result"] = $result["login"]["result"];
$_SESSION["login_lguserid"] = $result["login"]["lguserid"];
$_SESSION["login_lgusername"] = $result["login"]["lgusername"];
} else if ($result["login"]["result"] == "NeedToken") {
$other_error = "Error 005: Token error.";
} else if ($result["login"]["result"] == "NoName") {
$username_error = "The username can not be blank";
} else if ($result["login"]["result"] == "Illegal") {
$username_error = "You provided an illegal username";
} else if ($result["login"]["result"] == "NotExists") {
$username_error = "The username you provided doesn't exist";
} else if ($result["login"]["result"] == "EmptyPass") {
$password_error = "The password can not be blank";
} else if ($result["login"]["result"] == "WrongPass" || $result["login"]["result"] == "WrongPluginPass") {
$password_error = "The password you provided is incorrect";
} else if ($result["login"]["result"] == "CreateBlocked") {
$username_error = "Autocreation was blocked from this IP address";
} else if ($result["login"]["result"] == "Throttled") {
$other_error = "You've logged in too many times in a short time. Try again later.";
} else if ($result["login"]["result"] == "mustbeposted") {
$other_error = "Error 004: Logindata was not send correctly";
} else if ($result["login"]["result"] == "Blocked") {
$username_error = "This account is blocked.";
} else if ($result["login"]["result"]){
$other_error = "Error 001: An unknown event occurred.";
} else {
$other_error = "Error 002: An unknown event occurred.";
}
// The tool you use may log or display the variables:
// $other_error, $username_error and $password_error in the appropiate place
// Such as near a login form, or in a specific debug/logfile
// by default the errors are not outputted
if($_SESSION["login_result"] !== "Success"){
die("Login error. Have you defined app[username] and app[password] ?");
}
Example of building a query:
/**
* Get userinfo
* -------------------------------------------------
*/
$postdata = http_build_query([
"action" => "query",
"format" => "php",
"meta" => "userinfo",
"uiprop" => "rights|hasmsg",
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
Death("Error 003: " . curl_error($ch),"API connection failed.");
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Check for usermessages
if (isset($result['query']['userinfo']['messages'])) {
$api['hasmsg'] = true;
$api['hasmsghtml'] = '<div class="usermessage">You have new messages !</div>';
} else {
// User does not have new messages
}
And finally, how to clean up the session:
// Delete the cookie file
unlink($app["cookiefile"]);
// Destroy the session
session_destroy();
// End this file
die($output);

I tried that, and it works either
public function callWiki($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function getAllCategories()
{
$api = 'https://en.wikipedia.org/w/api.php? action=query&titles=watch&prop=categories&format=json';
//get query result
$api_response = $this->callWiki($api);
$results = json_decode($api_response, true);
}

Related

Error Code 400: Invalid Value - Google Play IAP Verification Failure

I had working code in my server, that verified in-app purchases.
There are already 2 days, that my verification started give me a bad response.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
Nothing changed on my side.
(P.S. I'm able to get an access token via refresh, so, I assume I have no problems with my credentials).
Here is the code, that worked OK before.
$product_sku = $_REQUEST['product_sku'];
$transaction_id = $_REQUEST['transaction_id'];
$transaction_time = $_REQUEST['transaction_time'];
$purchase_data = #$_REQUEST['purchase_data'];
$market = $_REQUEST['market'];
$verified = false;
$test_purchase = false;
if (isset($product_sku) && isset($transaction_id) && isset($transaction_time) && isset($market)) {
// If it's GOOGLE
if ($market == '2') {
// verifies if the IAB is correct
if (isset($purchase_data) && $purchase_data != "") {
// Getting necessary data for verification
$client_id = file_get_contents('google_play_developer_api_client_id');
$client_secret = file_get_contents('google_play_developer_api_client_secret');
$refresh_token = file_get_contents('google_play_developer_api_refresh_token');
$refresh_token_url = 'https://accounts.google.com/o/oauth2/token';
$verification_url = "https://www.googleapis.com/androidpublisher/v3/applications/mypackage/purchases/products/" . $product_sku . "/tokens/" . $purchase_data;
// Preparing for the REFRESH_TOKEN request. This need to be changed after Memcache enabling.
// Will be needed to store the ACCESS_TOKEN in the Memcache for the expiration time and after expiring get new ACCESS_TOKEN with REFRESH_TOKEN
// constructing the necessary data for Google authentication
$data_array = array(
"grant_type" => "refresh_token",
"client_id" => $client_id,
"client_secret" => $client_secret,
"refresh_token" => $refresh_token
);
// replacing '\/' with '/' as after json_encode() the '/' in the array values will be replaced with '\/'
$data_array = str_replace("\/", "/", json_encode($data_array));
// contracting Headers for the REFRESH_TOKEN request
$headers = array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
);
// making REFRESH_TOKEN request and getting the new ACCESS_TOKEN
$make_call = callAPI('POST', $refresh_token_url, $data_array, $headers);
$response = json_decode($make_call, true);
if (array_key_exists("access_token", $response)) {
$accessToken = $response["access_token"];
// preparing for the Verification request
// adding necessary headers
array_push($headers, "Authorization: OAuth " . $accessToken, "Accept: application/json");
// making Verification request and getting the receipt from Google
$make_call = callAPI('GET', $verification_url, false, $headers);
$receipt = json_decode($make_call, true);
if (array_key_exists("purchaseState", $receipt)) {
// checking for the test purchase or for the purchase made using promo code.
// if purchaseType exists in the receipt the it is test purchase or the purchase made using promo code
// purchaseType = 0 -> Test Purchase, purchaseType = 1 -> Purchase made using promo code
if (array_key_exists("purchaseType", $receipt)) {
$purchaseType = $receipt["purchaseType"];
$test_purchase = $purchaseType == 0;
}
// Getting the purchaseState from the receipt.
// purchaseState = 0 -> Successfull purchase, purchaseState = 0 -> Canceled purchase
$purchaseState = $receipt["purchaseState"];
// Getting Order Id from the receipt
$order_id = $receipt["orderId"];
// Getting Purchase Time from the receipt. Time in millis from the Unix Epoch
$purchaseTimeMillis = $receipt["purchaseTimeMillis"];
// Verifying the purchase
// Verification is failed for any of the following reasons
// 1. Test purchase or the purchase made using promo code
// 2. Canceled Purchase
// 3. If the order id from receipt and the transaction id from the mobile app are different
// 4. If the PurchaseTime from the receipt and the Transaction Time from the mobile are different
// If all conditions are true, the purchase is verified.
$verified = ($purchaseState == 0 && $order_id == $transaction_id && $purchaseTimeMillis == $transaction_time);
} elseif(!array_key_exists("error", $receipt)){
// Something went wrong, let's set the verified to true, so we don't know if it is cheating
$verified = true;
}
} else {
// Something went wrong, let's set the verified to true, so we don't know if it is cheat
$verified = true;
}
}
} else {
// Changed this, while adding verification for other platforms
$verified = true;
}
$verified = $verified ? 1 : 0;
$test_purchase = $test_purchase ? 1 : 0;
// Updating verified and test Purchase fields in the payment_transaction table
// The default value is 1, so no need for updating , if the payment is verified
if ($verified == 0 || $test_purchase == 1) {
dbQuery("UPDATE payment_transaction SET verified=$verified, test_purchase=$test_purchase WHERE user_id=$user_id AND txnid='$transaction_id'", $user_id);
}
$output['status'] = 'ok';
$output['verified'] = $verified;
$output['test_purchase'] = $test_purchase;
}
echo json_encode($output);
function callAPI($method, $url, $data = false, $headers = null)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "GET":
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
if ($headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if (! $result) {
die("Connection Failure");
}
curl_close($curl);
return $result;
}
?>
Any Ideas what may be the reason for the bad response?
I have tried to generate a new refresh token, but the result is the same. (
Ok. I found the problem. The PurchaseToken was incorrect in my case.
BTW, the Error Code 400 means that the authentication is ok , but some data is invalid. In my case, it was the PurchaseToken.

GCM Push notification sending taking very long time in PHP

I am using a class to send GCM based Push Notification from PHP. I downloaded this class from https://www.phpclasses.org/package/8987-PHP-Send-push-notifications-to-Android-and-iOS-devices.html
All things are working as expected but as the number of Android users has crossed 3K now sending push notification is taking very long time. It takes around 2 to 2 and a half hours to send Push Notification.
And I cannot refresh the page to even close the browser otherwise the operation gets aborted.
How can I increase the speed of sending Push Notification from my script.
The important part of code that I am using for sending Push Notification is give below:
if (isset($_POST['sendmessage']) && !empty($_POST['sendmessage'])) {
$errorvalid = array();
$success = TRUE;
$requiredFields = array("subject_notify" => "Please Enter Notify Subject.", "subject_main" => "Please Enter Main Subject.", "msg" => "Please Enter Message");
foreach ($requiredFields as $fld => $msg) {
$v = $_POST[$fld];
if (empty($v)) {
$success = false;
$errorvalid[$fld] = $msg;
} else {
$errorvalid[$fld] = '';
$$fld = $v;
}
}
if($success)
{
$get_result = mysql_query("SELECT ps_mobile_id, ps_service_type FROM push_service", $con);
$row_result = mysql_fetch_assoc($get_result);
$totalRows_row_result = mysql_num_rows($get_result);
echo "Total Records: ".$totalRows_row_result;
echo "<br/>";
//Set parameters to hold time out error
set_time_limit(0);
error_reporting(E_ALL);
//ob_implicit_flush(TRUE);
//ob_end_flush();
if($totalRows_row_result > 0) {
$push = new pushmessage();
do {
$MobID = $row_result['ps_mobile_id'];
$MobType = $row_result['ps_service_type'];
echo "Mobile ID: ".$MobID;
echo "<br/>";
if($MobType == 1)
{
//Android
$params = array("pushtype"=>"android", "msg"=>$msg, "registration_id"=>$MobID, "subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
$rtn = $push->sendMessage($params);
//Push the message
$rtn = $push->sendMessage($params);
}
else
{
//iOS
//$params = array("pushtype"=>"android", "msg"=>$msg, "registration_id"=>$MobID, //"subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
//$rtn = $push->sendMessage($params);
//Push the message
//$rtn = $push->sendMessage($params);
}
echo "<br/>";
print_r($rtn);
echo "<br/>";
//ob_flush(); //Push data to Browser
}while ($row_result = mysql_fetch_assoc($get_result));
//header("Location: index.php");
echo "<h2>Completed Sending Pusht Message</h2>";
echo "<br/><br/>";
echo "Rediricting.... Please wait....";
echo "<br/><br/>";
echo '<meta http-equiv="refresh" content="3;url=http://mypresence.in/pushtibooks/pushmsg/" />';
}
else
{
echo "NO Data";
}
}
}
TIA
Yogi Yang
You are sending push notification one by one . That's why it takes too much time. You can send group message using device id. Check this documentation .
Use below code for sending push notification to android. Same way you can do this on iOS also.
//For andriod
$get_result = mysql_query("SELECT ps_mobile_id FROM push_service where ps_service_type = 1", $con);
// $row_result = mysql_fetch_assoc($get_result);
$totalRows_row_result = mysql_num_rows($get_result);
$MobIDs=array();
while($row = mysql_fetch_assoc($get_result)){
$MobIDs[] = $row;
}
$params = array("pushtype"=>"android", "msg"=>$msg, "subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
$rtn = $push->sendMessageAndroid($MobIDs, $params)
and sendMessageAndroid($registration_id, $params)
public $androidAuthKey = "Android Auth Key Here";
public $iosApnsCert = "./certification/xxxxx.pem";
/**
* For Android GCM
* $params["msg"] : Expected Message For GCM
*/
private function sendMessageAndroid($registration_id, $params) {
$this->androidAuthKey = "Android Auth Key Here";//Auth Key Herer
## data is different from what your app is programmed
$data = array(
'registration_ids' => array($registration_id),
'data' => array(
'gcm_msg' => $params["msg"]
)
);
$headers = array(
"Content-Type:application/json",
"Authorization:key=".$this->androidAuthKey
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
//result sample {"multicast_id":6375780939476727795,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1390531659626943%6cd617fcf9fd7ecd"}]}
//http://developer.android.com/google/gcm/http.html // refer error code
curl_close($ch);
$rtn["code"] = "000";//means result OK
$rtn["msg"] = "OK";
$rtn["result"] = $result;
return $rtn;
}
Please note that: Don't send more than 1000 device id per request. If you have more than 1000 users. then slice your MobIDs with a size less than 1000

PHP : server error

I have a PHP code for sending OTP, When i execute it in my local server its works well. But when i run this code after changing it from my local to server by changing host name etc, i am getting 500 internal server error. I don't know where i am going wrong. Any solution will be apreciated. Thank you
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.

Paypal Masspay API Masspay input parse error

I am using Paypal MassPay API in php.
My code was working fine but now I am getting this error.
MassPay failed:
Array ( [TIMESTAMP] => 2014/07/06T17%3a27%3a04Z
[CORRELATIONID] => 5d6bf81231859
[ACK] => Failure
[VERSION] => 51%2e0
[BUILD] => 11753088
[L_ERRORCODE0] => 10314
[L_SHORTMESSAGE0] => Masspay input parse error
[L_LONGMESSAGE0] =>The input to the masspay server is incorrect e Please make sure that you are using a correctly formatted input e
[L_SEVERITYCODE0] => Error
Anyone has idea why I am getting this error now? I can provide code if required.
This is the main class:
Paypal_class.php
<?php
class Paypal {
public function __construct($username, $password, $signature) {
$this->username = urlencode($username);
$this->password = urlencode($password);
$this->signature = urlencode($signature);
$this->version = urlencode("51.0");
$this->api = "https://api-3t.paypal.com/nvp";
//The functions can be modified but need to be urlencoded
$this->type = urlencode("EmailAddress");
$this->currency = urlencode("USD");
$this->subject = urlencode("Instant Paypal Payment");
}
public function pay($email, $amount, $note="Instant Payment") {
$string = "&EMAILSUBJECT=".$this->subject."&RECEIVERTYPE=".$this->type."&CURRENCYCODE=".$this->currency;
$string .= "&L_EMAIL0=".urlencode($email)."&L_Amt0=".urlencode($amount)."&L_NOTE0=".urlencode($note);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$request = "METHOD=MassPay&VERSION=".$this->version."&PWD=".$this->password."&USER=".$this->username."&SIGNATURE=".$this->signature."$string";
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("MassPay failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
$httpResponseArray = explode("&", $httpResponse);
$httpParsedResponse = array();
foreach ($httpResponseArray as $i => $value) {
$tempArray = explode("=", $value);
if(sizeof($tempArray) > 1) {
$httpParsedResponse[$tempArray[0]] = $tempArray[1];
}
}
if((0 == sizeof($httpParsedResponse)) || !array_key_exists('ACK', $httpParsedResponse)) {
exit("Invalid HTTP Response for POST request($request) to ".$this->api);
}
return $httpParsedResponse;
}
}
?>
Calling this class with example.php file:
<?php
require "paypal_class.php";
$paypal = new Paypal("example.com", "xyz, "abc");
$send_payment = $paypal->pay("abc#gmail.com", ".001", "Thanks for an amazing service");
if("SUCCESS" == strtoupper($send_payment["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($send_payment["ACK"])) {
exit('MassPay Completed Successfully: '.print_r($send_payment, true));
} else {
exit('MassPay failed: ' . print_r($send_payment, true));
}
?>
Thanks
I was able to solve my problem. I changed the amount to be sent from "0.001" to "0.01", this code worked.
May be Paypal MassPay API doesn't deal with amount having more than two digits after decimal.

hotmail get contacts with curl using API

function tratar_hotmail(){
$client_id = '0xxxxxxxxxxxxxxxx2';
$client_secret = 'Wyyyyyyyyyyyyyyyyyp';
$redirect_uri = 'http://example.com/';
$auth_code = $_GET["code"];
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://apis.live.net/v5.0/me/contacts?access_token='.$accesstoken.'';
$xmlresponse = curl_file_get_contents($url);
echo $xmlresponse;
$xml = json_decode($xmlresponse, true);
foreach($xml['data'] as $emails)
{
echo $emails['name'];
}
}
which outputs:
{ "error": { "code": "request_token_invalid", "message": "The access token isn't valid." } }
How can I get the request_access_token?
-EDIT-
Forgot the curl function
function curl_file_get_contents($url)
{
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5); //The number of seconds to wait while trying to connect.
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //To stop cURL from verifying the peer's certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
Here's a class I've just thrown together for talking to the API:
<?php
// Note: the test script below assumes this is in a
// file called class.liverestapiconsumer.php
class LiveRESTAPIConsumer {
protected $accessTokenURI = 'https://login.live.com/oauth20_token.srf';
protected $restAPIBaseURI = 'https://apis.live.net/v5.0';
protected $appId;
protected $appSecret;
protected $accessToken;
protected $accessTokenExpires;
public function __construct($appId = NULL, $appSecret = NULL, $accessToken = NULL, $accessTokenExpires = NULL) {
$this->setAppId($appId);
$this->setAppSecret($appSecret);
$this->setAccessToken($accessToken);
$this->setAccessTokenExpires($accessTokenExpires);
}
public function getAppId() {
return $this->appId;
}
public function setAppId($appId) {
$this->appId = $appId;
}
public function getAppSecret() {
return $this->appSecret;
}
public function setAppSecret($appSecret) {
$this->appSecret = $appSecret;
}
public function getAccessToken() {
return $this->accessToken;
}
public function setAccessToken($accessToken) {
$this->accessToken = $accessToken;
}
public function getAccessTokenExpires() {
return $this->accessTokenExpires;
}
public function setAccessTokenExpires($accessTokenExpires) {
$this->accessTokenExpires = $accessTokenExpires;
}
public function accessTokenIsExpired() {
return $this->accessTokenExpires <= time();
}
public function fetchAccessToken($code, $redirectURI) {
if (!isset($code, $redirectURI, $this->appId, $this->appSecret)) {
throw new \Exception('Cannot fetch access token without an authorization code, redirect URI, application id and application secret');
}
$postFields = array(
'client_id' => $this->appId,
'client_secret' => $this->appSecret,
'code' => $code,
'redirect_uri' => $redirectURI,
'grant_type' => 'authorization_code'
);
$bodyData = http_build_query($postFields);
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
$ch = curl_init($this->accessTokenURI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (!$response = curl_exec($ch)) {
throw new \Exception('cURL request failed');
} else if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
throw new \Exception('Live API returned an error response code: '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
} else if (!$responseObj = json_decode($response)) {
throw new \Exception('Cannot decode API response as JSON; data: '.$response);
} else if (!isset($responseObj->access_token)) {
throw new \Exception('Live API did not return an access token; error: '.$responseObj->error_description);
}
$this->setAccessToken($responseObj->access_token);
$this->setAccessTokenExpires(time() + $responseObj->expires_in);
}
protected function normalizeAPIPath($path) {
return $path[0] == '/' ? $path : '/'.$path;
}
public function apiCall($method, $path, array $params = array(), $data = NULL) {
if (!isset($this->accessToken)) {
throw new \Exception('Cannot make API requests without an access token');
} else if ($this->accessTokenIsExpired()) {
throw new \Exception('The currently defined access token has expired');
}
$ch = curl_init();
$url = $this->restAPIBaseURI.$this->normalizeAPIPath($path);
if ($params) {
$url .= '?'.http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $url);
$method = trim(strtoupper($method));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$headers = array();
$headers[] = 'Authorization: Bearer '.$this->accessToken;
if ((array) $data) {
$bodyData = json_encode($data);
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyData);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if (!$response = curl_exec($ch)) {
throw new \Exception('cURL request failed');
} else if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
throw new \Exception('Live API returned an error response code: '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
} else if (!$responseObj = json_decode($response)) {
throw new \Exception('Cannot decode API response as JSON; data: '.$response);
}
return $responseObj;
}
}
...and the test script (yes, I am fully aware that my HTML skills are terrible - I don't write very much of it):
<?php
session_start();
require 'class.liverestapiconsumer.php';
// Your details as assigned by Microsoft
$appId = '<your client id>';
$appSecret = '<your client secret>';
// The public (internet) URL of this script
$localUrl = 'http://example.com/path/to/file.php';
// Work out whether we have a valid access token or not
$haveAccessToken = FALSE;
$accessTokenExpiresIn = 'N/A';
if (isset($_SESSION['accessToken'])) {
$now = time();
$haveAccessToken = $now < $_SESSION['accessTokenExpires'];
$accessTokenExpiresIn = ($_SESSION['accessTokenExpires'] - $now).' seconds';
if (!$haveAccessToken || isset($_GET['destroy'])) {
unset($_SESSION['accessToken'], $_SESSION['accessTokenExpires']);
}
if (isset($_GET['destroy'])) {
header('HTTP/1.1 302 Found');
header('Location: '.$localUrl);
}
}
function parse_body_data($str) {
$result = array();
$items = preg_split('/[\r\n]+/', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach ($items as $item) {
$item = explode(':', $item, 2);
if (count($item) !== 2) {
return FALSE;
}
$result[trim($item[0])] = trim($item[1]);
}
return $result;
}
?>
<html>
<head>
<title>Live API Test</title>
<style>
div.label {
margin-top: 10px;
}
</style>
</head>
<body>
<div>Do we have an access token? <b><?php echo $haveAccessToken ? 'Yes <sup>(destroy)</sup>' : 'No'; ?></b> (Expires: <?php echo $accessTokenExpiresIn; ?>)</div>
<?php
if (isset($_POST['path'])) { // get something from the API
do { // do-while so we can easily break out of it on error
$client = new LiveRESTAPIConsumer($appId, $appSecret, $_SESSION['accessToken'], $_SESSION['accessTokenExpires']);
$path = $_POST['path'];
$method = $_POST['method'];
$paramStr = trim($_POST['params']);
$params = array();
if (!empty($paramStr)) {
parse_str($paramStr, $params);
}
if (($body = parse_body_data($_POST['body'])) === FALSE) {
echo "<div>Error: Body data invalid</div>";
break;
}
try {
$result = $client->apiCall($method, $path, $params, $body);
// The class returns the response data decoded to an object, so json_encode() it again for display
echo '
Result:
<pre>'.json_encode($result, JSON_PRETTY_PRINT).'</pre>
';
} catch (\Exception $e) {
echo "<div>Exception: ".$e->getMessage()."</div>";
break;
}
} while(FALSE);
echo '<div>Back</div>';
} else if (isset($_GET['code'])) { // handle redirect from live API
try {
$client = new LiveRESTAPIConsumer($appId, $appSecret);
$client->fetchAccessToken($_GET['code'], $localUrl);
$_SESSION['accessToken'] = $client->getAccessToken();
$_SESSION['accessTokenExpires'] = $client->getAccessTokenExpires();
echo '
<div>Successfully retrieved access token: '.$_SESSION['accessToken'].'</div>
<div>Go to form</div>
';
} catch (\Exception $e) {
echo '
<div>Exception: '.$e->getMessage().'</div>
<div>Back</div>
';
}
} else if ($haveAccessToken) { // Output form
echo '
<form action="'.$localUrl.'" method="post">
<div>
<div class="label">API Path</div>
<div><input name="path" type="text"></div>
</div>
<div>
<div class="label">Parameters (query string)</div>
<div><input name="params" type="text"></div>
</div>
<div>
<div class="label">Method</div>
<div>
<select name="method">
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="MOVE">MOVE</option>
<option value="COPY">COPY</option>
</select>
</div>
</div>
<div>
<div class="label">Body Data (key: value, newline separated)</div>
<div><textarea name="body" rows="10" cols="40"></textarea></div>
</div>
<input type="submit" value="Send Request">
</form>
API Reference
';
} else { // Don't have access token yet
$opts = array(
'client_id' => $appId,
'scope' => 'wl.basic',
'response_type' => 'code',
'redirect_uri' => $localUrl
);
echo '<div>Get access token</div>';
}
?>
</body>
</html>
All the parts that I think need explanation are commented. If you have any questions let me know.
Note that I haven't extensively tested the class, and it may be lacking when it comes to the more advanced API functionality. Seems to work fairly well for simple contact manipulation though.
In addition to the answer of DaveRandom and the comment of saveATcode: You should submit the redirect url given in $localUrl as a valid redirect url at account live application. They must be exactly the same or else you will get the 'The provided value for the input parameter 'redirect_uri' is not valid....' message. I just mentioned it because mine had a typo and i experienced the same error.

Categories