I am trying to purge a file through the MaxCDN API but it's not working. Here's the code I'm using. The print_r doesn't return any result.
function purge() {
date_default_timezone_set('America/Los_Angeles');
$date = date('c');
$apiid = 'myapiid';
$apikey = 'myapi';
$auth_key = hash('sha256', $date.':'.$apikey.':purge');
$url = 'http://softsailor.alexdumitru.netdna-cdn.com/wp-content/themes/ss3/includes/sprite.jpg';
if (!class_exists('IXR_Client')) {
require_once (ABSPATH . WPINC . '/class-IXR.php');
}
$client = new IXR_Client('api.netdna.com','/xmlrpc/cache',80);
$client->timeout = 30;
$client->query('cache.purge', $apiid, $auth_string, $date, $url);
print_r($client->getResponse());
}
I turned debug on and I'm getting the following error
Something went wrong - -32300 : transport error - HTTP status code was not 200
Hey Alex. I work at MaxCDN and here is a code example that I took from our Wiki:
<?php
date_default_timezone_set('America/Los_Angeles');
include("lib/xmlrpc.inc");
$cur = date('c');
$apiKey = 'api-key';
$apiUserId = 'api-user-id';
$namespace = 'cache';
$method = 'purge';
$authString = hash('sha256', $cur . ':' . $apiKey . ':' . $method);
// this is the url to purge
$url= 'http://static.jdorfman.netdna-cdn.com/static/images/frugal-it-logo.png';
$f=new xmlrpcmsg("$namespace.$method", array(php_xmlrpc_encode($apiUserId),
php_xmlrpc_encode($authString), php_xmlrpc_encode($cur),
php_xmlrpc_encode($url)));
$c=new xmlrpc_client("/xmlrpc/cache", "api.netdna.com", 80,'http11');
$r=&$c->send($f);
print_r($r);
?>
If you have any other questions or concerns feel free to get in contact with me: jdorfman at maxcdn dot com
jdorfman's example dumps the entire raw response but if you are like me you want to get it into data objects using php
Here are some helpful tips:
$r->serialize() to access just the raw XML response
to convert to JSON use this:
$xml = simplexml_load_string($r->serialize());
echo json_encode($xml);
Related
I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>
So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse.
Here is the code:
//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';
//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';
$page = join("",file("$csv_location"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$destination = $kw[$i];
echo $destination;
$raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
$request_url = str_replace(' ', '', $raw_url);
$getJson = file_get_contents($request_url);
$routes = json_decode($getJson);
$result = $routes->routes[0]->legs[0]->distance->value;
echo $result . '<br>';
}
The result I get looks like this:
Distance by Post Code Generator v0.1 by Phil Hughes
RG12 0GA
RG12 0GB
RG12 0GC
RG12 0GD4066
Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see.
Please help.
Your
join("",file("$csv_location"));
concatenated all lines feom the file to a single line without separator. The following explode() sees no newlines any more. So you are working on one line only. count($kw) always evaluates to 1 and your loop runs only one time.
I downloaded Product Advertising PHP Soap Library and was going through the sample codes. I configured the value of 'AWS_API_KEY', 'AWS_API_SECRET_KEY', 'AWS_ASSOCIATE_TAG', 'AWS_ANOTHER_ASSOCIATE_TAG' in sampleSettings.php file. I'm getting the below mentioned error in my browser while trying to access 'sampleItemSearch.php'.
SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl' : Start tag expected, '<' not found
I tried to take help help from Link: https://forums.aws.amazon.com/thread.jspa?messageID=270273 but it did not work.
Note: I have tried to run the below url in browser and got the following output:
$request="http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AssociateTag=ASSOCIATETAG01-20&AWSAccessKeyId=MY_ACCESS_KEY_ID&Operation=ItemSearch&Version=2011-08-01&SearchIndex=Books&Keywords=harry%20potter&Timestamp=2013-04-10T12%3A44%3A42.000Z&Signature=ASasd5645AdSG878asdHsaHJ9YTefl1F6i0%3D";
Please suggest what I should do.
I solved it at last. Below mentioned code is working fine.
AWSAccessKeyId = "*******************";
$SecretAccessKey = "******************************";
$AssociateTag = "***************";
$ItemId = '****'; //10 or 13 digit isbn
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$Timestamp = str_replace(":", "%3A", $Timestamp);
$ResponseGroup = "ItemAttributes,Images";
$ResponseGroup = str_replace(",", "%2C", $ResponseGroup);
$String = "AWSAccessKeyId=$AWSAccessKeyId&AssociateTag=$AssociateTag&IdType=ISBN&ItemId=$ItemId&Operation=ItemLookup&ResponseGroup=$ResponseGroup&SearchIndex=Books&Service=AWSECommerceService&Timestamp=$Timestamp&Version=2011-08-01";
$String = str_replace("\n", "", $String);
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$PrependString = $Prepend . $String;
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = str_replace("+", "%2B", $Signature);
$Signature = str_replace("=", "%3D", $Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
$XML = simplexml_load_file($SignedRequest);
print_r($xml); // output
I have looked at most samples of code based on this issue on stack overflow but I still cant get the request to work. I keep getting this error:
<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Here is my code:
$access_key = "ACCESS_KEY";
$associateTag = "AOSSOCIATE_TAG";
$secretkey = "SECRET_KEY";
$keywords = "harry%20potter";
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$operation = "AWSECommerceService";
function createSignature($operation,$timestamp,$secretkey){
$the_string=$operation.$timestamp;
return base64_encode(hash_hmac("sha256",$the_string,$secretkey,true));
}
$signature = createSignature ($operation,$timestamp,$secretkey);
$APIcall =
"http://ecs.amazonaws.com/onca/xml?".
"AWSAccessKeyId=$access_key&".
"AssociateTag=$associateTag&".
"BrowseNode=1000&".
"ItemPage=1&".
"Keywords=$keywords&".
"Operation=ItemSearch&".
"ResponseGroup=Medium&".
"SearchIndex=Books&".
"Service=AWSECommerceService&".
"Timestamp=$timestamp&".
"Version=2011-08-01&".
"Signature=$signature";
$response = simplexml_load_file($APIcall);
Can anyone help?
I had this issue long time and it worked for me with this code :
require_once 'Crypt/HMAC.php';
require_once 'HTTP/Request.php';
$keyId = "adasdasd";
$secretKey = "asdasdasdasdasd+";
function hex2b64($str) {
$raw = '';
for ($i=0; $i < strlen($str); $i+=2) {
$raw .= chr(hexdec(substr($str, $i, 2)));
}
return base64_encode($raw);
}
function constructSig($str) {
global $secretKey;
$str = utf8_encode($str);
$secretKey = utf8_encode($secretKey);
$hasher =& new Crypt_HMAC($secretKey, "sha1");
$signature = hex2b64($hasher->hash($str));
return ($signature);
}
$expire = time()+1000;
$resource = "/demo/files/clouds.jpg";
$date = gmdate("D, d M Y G:i:s T");
$mime = "image/jpeg";
$stringToSign = "PUT\n";
$stringToSign .= "\n";
$stringToSign .= "$mime\n";
$stringToSign .= "$date\n";
$stringToSign .= $resource;
$req =& new HTTP_Request("http://nameofmine.s3.amazonaws.com/files/clouds.jpg");
$req->setMethod("PUT");
$req->addHeader("Date",$date);
$req->addHeader("Authorization", "AWS " . $keyId . ":" . constructSig($stringToSign));
$req->addHeader("Content-Type",$mime);
$req->setBody(file_get_contents($file_path));
$req->sendRequest();
$responseCode = $req->getResponseCode();
$responseString = $req->getResponseBody();
echo $responseCode;
As you see you have to use Crypto, HTTP pear plugins
The function seems ok (it is the same as the one used in amazon AWS SDK) so make sure that there is no whitespace in front or after the copied key.
When I typed in my credentials by hand, I got the same error a couple of times.
Then I tried Console for Windows so I could copy/paste my credentials. This removed the error message. Either I sucked at typing, or sucked at reading.
Long story short: Don't type by hand, copy and past credentials to avoid typos.
EDIT:
My problem was when trying to add my credentials via EB CLIx3.
I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you