Amazon.com MWS Integration - php

I am currently developing a very basic site which will, at this time, simply display order information from Amazon's Marketplace.
I have all of the MWS Security Credentials.
I have downloaded and reviewed, with much confusion, the PHP Client Library.
I am kind of new to PHP but I feel like I can handle this project.
I need to know how to install and access information from this API. I feel like I've tried everything. Amazon does not supply enough information to get this going. They make it sound like it takes 5 or 6 easy steps and you can access your information; this is not true.
Is there a detailed tutorial on MWS? I need as much information as possible. If you can help me out, maybe outline the steps required to get it going, that would be very appreciated!!!! I'm pulling my hair out over this. Thanks again

A rough file to get you started. This is taken from several pages, including this one from #Vaidas. I don't have links yet, sorry. My only contribution is to put this together in one place.
None of the PHP code Amazon supplied worked for me out of the box. I'm assuming you have XAMPP with cURL or an equivalent environment. This code SHOULD work out of the box to get you started on what needs to happen. Just plug in your credentials.
<?php
$param = array();
$param['AWSAccessKeyId'] = 'YourAccessKeyID';
$param['Action'] = 'GetLowestOfferListingsForASIN';
$param['SellerId'] = 'YourSellerID';
$param['SignatureMethod'] = 'HmacSHA256';
$param['SignatureVersion'] = '2';
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version'] = '2011-10-01';
$param['MarketplaceId'] = 'YourMarketplaceID';
$param['ItemCondition'] = 'new';
$param['ASINList.ASIN.1'] = 'B00C5XBAOA';
$secret = 'YourSecretKey';
$url = array();
foreach ($param as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
}
sort($url);
$arr = implode('&', $url);
$sign = 'GET' . "\n";
$sign .= 'mws.amazonservices.com' . "\n";
$sign .= '/Products/2011-10-01' . "\n";
$sign .= $arr;
$signature = hash_hmac("sha256", $sign, $secret, true);
$signature = urlencode(base64_encode($signature));
$link = "https://mws.amazonservices.com/Products/2011-10-01?";
$link .= $arr . "&Signature=" . $signature;
echo($link); //for debugging - you can paste this into a browser and see if it loads.
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo('<p>' . $response . '</p>');
print_r('<p>' . $info . '</p>');
?>
Please note that it is VITAL to have the
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
line, at least in my case. CURL was working fine for any page except for the MWS page (it was just giving me a blank page with -1s in the info, and it took me most of a day to figure out I needed that line. It's in the MWS forums somewhere.
For good measure, here's a link to MWS ScratchPad.
Once I get a better handle on working with MWS maybe I'll do a tutorial. Or someone who is better at HTML and has a need for more of the features could do it.

in case you still didn't figure out how to do this, follow these steps
read the Developer Guide
read the Reports API Reference
RequestReport with some ReportType that will return order data (page 51 or so, look the reports api reference)
you can test this with the MWS Scratchpad
you can also post to the Amazon MWS community forum to get additional help
you can even write to the Amazon Tech Support
hope this helps you and other users.

Amazon provides some great sample code at https://developer.amazonservices.com/. I've successfully used their code for my PHP applications.
I agree. It was a nightmare to figure out the MWS API.

Some changes to #Josiah's method to make it work for other marketplaces:
Line:
$sign .= 'mws.amazonservices.com' . "\n";
Change to: your correct MWS endpoint. List here http://docs.developer.amazonservices.com/en_US/dev_guide/DG_Endpoints.html - it'll match your marketplace ID, which could be something like this:
$sign .= 'mws-eu.amazonservices.com' . "\n";
and UK marketplace ID for UK site.
Line:
$link = "https://mws.amazonservices.com/Products/2011-10-01?";
Again, change the start of the url in line with above.
This'll probably give you straight text output in a browser (view source for xml). For XML visible output (easier for checking) do this:
Add an XML content type line to top of file:
header('Content-type: application/xml');
Then comment out:
echo($link);
and
print_r('<p>' . $info . '</p>');

Implementing MWS is easy if you follow the right steps:
1-Download the codebase library from the https://developer.amazonservices.com/ as per your preferred language.
2-Set your seller mws credentials in config.php file under sample folder so that same can be used while running the specific file under the sample folder like: RequestReportSample.php and set the report type and endpoint url for specific seller domain.
3- You can then check submitted request status from scratchpad.
4- You can use GetReportSample file to get the order report data and use the same as per your need.
You can follow the reference as well http://prashantpandeytech.blogspot.com/2015/03/mws-amazon-marketplace-web-service-api.html

Related

Firebase server side validation using PHP scripts

I have 10 ios apps with subscription in app purchases. I need one subscription purchase to be valid accross the 10 apps. Thus I require server-side receipt validation. The flow is like this: When the customer pays for the subscription, the receipt is sent to the Firebase DB and from there, I require a PHP script that takes in the receipt data . as input and sends a 'POST' request to the App store. The App store would then validate the receipt and return a JSON object back. We then overwrite the old receipt with the latest copy. Also, whenever the user logs in to any of the apps, we repeat this process and update the receipt to make sure the subscription of the user is still valid. How do I do this in Firebase? If I cannot, can you please suggest any alternatives?
I have seen on some forums that Firebase 'cloud functions' might be able to such things. However, I am not exactly sure. Also, I am not quite adamant on using PHP. If I am able to achieve the same outcome using a different scripting language, I would be very happy.
Thanks.
Here is a sample of the PHP script:
<?php
function getReceiptData($receipt)
{
$fh = fopen('showme.txt',w);
fwrite($fh,$receipt);
fclose($fh);
$endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $receipt);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
curl_close($ch);
$msg = $response.' - '.$errno.' - '.$errmsg;
echo $response;
}
foreach ($_POST as $key=>$value){
$newcontent .= $key.' '.$value;
}
$new = trim($newcontent);
$new = trim($newcontent);
$new = str_replace('_','+',$new);
$new = str_replace(' =','==',$new);
if (substr_count($new,'=') == 0){
if (strpos('=',$new) === false){
$new .= '=';
}
}
$new = '{"receipt-data":"'.$new.'","password":"<INSERT YOUR IN-APP PURCHASE SHARED SECRET HERE>"}';
$info = getReceiptData($new);
?>

Twilio lookup API not working?

I'm trying to use Twilio's Lookup API to get certain properties of a mobile number via PHP... with very little success:
$twilioClient = new Lookups_Services_Twilio(Credential::TwilioSID, Credential::TwilioToken);
$number = $twilioClient->phone_numbers->get($someNumber);
Note that this is the example code present within their 'Getting Started' page here.
By taking a look at $number in the debugger, I can confirm it is returning something:
The highlighted property of the object is simply recursive with no new information.
Attempting to evaluate $number->phone_number returns null. I have tried this with perhaps half a dozen completely valid numbers now and this is the only response I get.
Attempting to json_encode($number) returns false.
I have no idea why this is not working, but it'd be helpful if I could know what I'm doing wrong.
I would have been also not successful with their code defined so i used CURL to grab their API methods and it worked like a charm for me, you can try following code to get you need
$base_url = "https://lookups.twilio.com/v1/PhoneNumbers/+1XXXXXXXXXX";
$ch = curl_init($base_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$account_sid:$auth_token");
$response = curl_exec($ch);
$response = json_decode($response);
echo "<pre>"; print_r($response); echo "</pre>";
It will return you few parameters (country_code, national_format, carrier)
I'm just gonna go ahead and assume the phone numbers you've tried are neither from the US, nor in international format.
From Twilio's Lookups Quickstart Tutorial:
You'll want to include the country code of the phone number that you would like formatted. If not included, the country code will default to the US.
So your lookup should probably look like:
$number = $twilioClient->phone_numbers->get($someNumber, array('CountryCode' => 'NZ'));
If the phone numbers are from the US, in international format, or if the above still does not work, try whether the lookup succeeds on Twilio's web interface (you'll need the international prefix there).
If it does, your software library might be broken or your Twilio account might have incorrect/broken access rights.
If the web lookup fails as well, you should contact Twilio and report the issue.
Now 9-6-2016 and they still haven't fixed their PHP library...
None the less here is what worked for me. If you want more information like caller name etc you have to enable this in your twilio dashboard first.
require 'includes/twilio/Services/Twilio.php';
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "YOUR-SID";
$token = "YOUR-TOKEN";
$client = new Lookups_Services_Twilio($sid, $token);
// Lookup
$phoneNumber = rawurlencode("(000) 000-0000");
$full_path = $client->phone_numbers->uri . "/$phoneNumber" . "?CountryCode=US&Type=carrier&Type=caller-name";
$number = new $client->phone_numbers->instance_name($client, $full_path);
echo "Caller name:" . $number->caller_name->caller_name;
echo "<br>";
echo "Caller type:" . $number->caller_name->caller_type;
echo "<br>";
echo "Carrier type:" . $number->carrier->type . "\r\n";
echo "<br>";
echo "Carrier name:" . $number->carrier->name;
echo "<br>";
echo "Phone number:" . $number->phone_number;
echo "<br>";
echo "Country code:" . $number->country_code;

Retrieve Amazon MWS Response using php5.2 apis

I have some trouble to get a simple xml answer from Amazon, it reports me always:
Sender
InvalidParameterValue
Either Action or Operation query parameter must be present.
And if I ask their Support, they can't help me they dont see the missing Parameter...
Their suggestion is follow their Examples, but my Webhost only supports php 5.2, so the autoloader doesn't work.
<?php
#header("Content-Type:text/xml");
$sellerID = 'SELLEDERID';
$aws = 'AWSKEY';
$secret = 'SECRET';
$action = 'GetReportList';
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$signature = $action . $timestamp;
$sig = base64_encode(hash_hmac("sha256", $signature, $secret, true));
$service = 'https://mws.amazonservices.com/?';
$url = 'AWSAccessKeyId='.$aws;
$url .= '&Action='.$action;
$url .= '&Merchant='.$sellerid;
$url .= '&SignatureVersion=2';
$url .= '&Timestamp=2013-01-10T12:22:48Z';
$url .= '&Version=2009-01-01';
$url .= '&Signature='.$sig;
$url .= '&SignatureMethod=HmacSHA256';
$awsURL = $service.urlencode($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $awsURL,
CURLOPT_USERAGENT => 'Request'
));
$resp = curl_exec($curl);
curl_close($curl);
echo "<pre>";
var_dump($resp);
var_dump($awsURL);
echo "</pre>";
?>
The "we see no error in your request" probably referred to the request you put into Scratchpad, and not to the request you made through php, because your signature calculation is way off.
See this StackOverflow question or the MWS Developers Guide (page 12, "If you create your own client library") on how to calculate the sig.
The actual error message seems weird. I expect it to change once you've got your signature right. Please also note that quite a few MWS API calls require a HTTP POST, so if you intend to reuse that code in other places you're probably better off changing your code accordingly.

Using FB PHP API to post status update to news feed

I run a music search engine, I already use basic Facebook intergration, like the like button, but my next aim is to create deeper intergration,
I'm aiming that when a user searches for something($q which I set as a cookie $_COOKIE['q'] ), a status update will appear, saying what they searched for and a link to my site.
I can allow a user login to facebook through JavaScript but I presume I would need to do it the PHP way.
I need to use PHP, as, after the user gives permission, I would like it that the user isn't pestered again. I have the Facebook PHP SDK and have created an app on Facebook. Online tutorials haven't really helped and i'm still on square 1, even though my PHP is okayish.
I would really appreciate if anyone gave me some guidelines/ ideas or helped code it.
Thanks in advance!
Niall
Well What you need to do is relatively easy. I think you already have the right java script for this but I'll add that in aswell, just incase!
Okay! First we need to add the php script at the top of your page that gets the information if the user has logged-in to their facebook:
define('FACEBOOK_APP_ID', 'YOUR APP ID');
define('FACEBOOK_SECRET', 'YOUR APP SECRET');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE['fbs' . $app_id], '"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$fbcookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$fb_access_token = $fbcookie['access_token'];
I'm presuming you know about the app ID and secret etc etc... fill those out under the define section.
Next we need to add a couple of things into the html for the javascript login:
FB.init({appId: 'YOUR APP ID AGAIN', status: true,
cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
That goes into your body script.
The next part is the facebook login button:
?fb:login-button perms="publish_stream,offline_access" onlogin="window.location.reload(true);" autologoutlink="true"? ?/fb:login-button?
(the question marks are the <> symbols as these conflict with the coding symbols in Stackoverflow)
Now you may wonder about the need for offline access. That's easy... I wonder about that too! lol I'm not 100% sure why that occurs but I think it's my webserver (a tad odd it is) so try it without offline permissions first and if that doesn't work then add it back in.
So that's all you have to do for the login aspect and posting aspect is a curl script:
$url = "https://graph.facebook.com/me/feed";
$ch = curl_init();
$attachment = array( 'access_token' => '' . $fb_access_token . '',
'message' => "just searched " . $q . " at http://domain.com",
);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result= curl_exec($ch);
curl_close ($ch);
So did you see what I did? don't forget to add if statements depending on your website layout etc etc so that users don't keep posting "i just searched at http:// domain.com" lol although that would spark that human curiosity ;) due to no searching being done thus $q=NULL and thus it'll still send nothing lol so maybe ad an if statement for when you have a query lol :P (Yes i know I added a space in the url from my 'print' version however stackoverflow is picky about how many url's I can post v_v" lol).
Please ask me if you need me to explain an other parts any further.
Good luck and happy searching!
Jon

how to find the total no.of inbound and outbound links of a website using php?

how to find the total no.of inbound and outbound links of a website using php?
To count outbound links
parse html for webpage
parse all links using regex
filter links which starts with your domain or "/"
To inbound link
Grab google results page
http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=site:
parse similarly
For outbound links, you will have to parse the HTML code of the website as some here have suggested.
For inbound links, I suggest using the Google Custom Search API, sending a direct request to google can get your ip banned. You can view the search api here. Here is a function I use in my code for this api:
function doGoogleSearch($searchTerm)
{
$referer = 'http://your-site.com';
$args['q'] = $searchTerm;
$endpoint = 'web';
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
$args['v'] = '1.0';
$key= 'your-api-key';
$url .= '?'.http_build_query($args, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
//decode and return the response
return json_decode($body);
}
After calling this function as: $result = doGoogleSearch('link:site.com'), the variable $result->cursor->estimatedResultCount will have the number of results returned.
PHP can't determine the inbound links of a page through some trivial action. You either have to monitor all incoming visitors and check what their referrer is, or parse the entire internet for links that point to that site. The first method will miss links not getting used, and the second method is best left to Google.
On the other hand, the outbound links from a site is doable. You can read in a page and analyze the text for links with a regular expression, counting up the total.
function getGoogleLinks($host)
{
$request = "http://www.google.com/search?q=" . urlencode("link:" . $host) ."&hl=en";
$data = getPageData($request);
preg_match('/<div id=resultStats>(About )?([\d,]+) result/si', $data, $l);
$value = ($l[2]) ? $l[2] : "n/a";
$string = "" . $value . "";
return $string;
}
//$host means the domain name

Categories