I'm gathering information on the location of stores.
The search is:
<?php
...
$url='https://maps.googleapis.com/maps/api/place/search/json?key=[my_key]&location=40.420989,-3.706812&radius=1000030&=&sensor=false';
$body=file_get_contents($url);
...
?>
I return a Json without problems, and indicates that there is another page of results.
I'll be back to make another call as follows
<?php
...
$url2='https://maps.googleapis.com/maps/api/place/search/json?key=[my_key]&pagetoken=ClREAAAAQXKNHPVGCkTC_MdjSqi2T0KBDMWjEu4KF1Ylw1761Po-67AnNSp4zw0wXD4oocGpx4olSl4k2LyklJBl3mBF4VPmxp3IoOCHDRlXVmivaDsSEBuG_V1GvCH1gS5s0LCuy3EaFNXxUzzHhZ5ZRYNfeGHuqewR6Zk7&sensor=false';
$body=file_get_contents($url2);
...
?>
If I run it with the second call I get an error
'status' -> INVALID_REQUEST
But when I paste the ulr2 browser in the result is correct.
How I can fix it?
Thanks
It has something to do with the timing between the requests, if you run them immediately one after the other, the pagetoken isn't valid yet, you have to wait a few seconds between consecutive requests.
This is because google's license terms don't allow you to fetch all the results at once and return them all at once to the user. You should have a user action asking for more results, which adds a delay of a couple of seconds.
sleep(2) between requests will solve the problem
Sleep(1.3) is the shortest amount of time that seemed to work. In other words the next page token becomes active about 1.3 seconds after it is returned in the previous API request.
Please try below code, I have used sleep(2) function for delay between requests, because next pagetoken needs to be validated on google server.
You can even use looping to remove code repetation.
// your query here
$query = "";
// api key here
$api_key = "";
// api call code
try {
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "First set" . "<br>";
print_r($query_results);
$next_page_token = $query_results['next_page_token'];
unset($query_results);
$query_results = array();
sleep(2);
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key . "&pagetoken=" . $next_page_token;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "Second set" . "<br>";
print_r($query_results);
$next_page_token = $query_results['next_page_token'];
unset($query_results);
$query_results = array();
sleep(2);
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key . "&pagetoken=" . $next_page_token;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "Third set" . "<br>";
print_r($query_results);
unset($query_results);
$query_results = array();
} catch (Exception $e) {
$e->getCode();
$e->getLine();
}
The first query will generate 2nd page token.
You just add "&pagetoken=tokenvalue" in your uri.
Sure it work. No alternative option.
Related
I am working with magento and third party payment wallet Mobikwik. I got it working in my development site. But same code in production site does not return success page but return shopping cart empty after payment.
Path of file : community/wallet/controllers/Transactcontroller.php
$session = Mage::getSingleton('checkout/session');
$session->setQuoteId($session->getWalletQuoteId(true));
$walletConfig = Mage::getStoreConfig('payment/wallet');
$statuscode = $postdata['statuscode'];
$orderid = $postdata['orderid'];
$mid = $postdata['mid'];
$amount = $postdata['amount'];
$message = $postdata['statusmessage'];
$checksumReceived = $postdata['checksum'];
$all = "'" . $statuscode . "''" . $orderid . "''" . $amount . "''" . $message . "''" . $mid . "'";
if($checksumReceived != null){
$isChecksumValid = $this -> verifyChecksum($checksumReceived, $walletConfig['secret_key'], $all);
}
if($isChecksumValid){
// success
if ($this->_validateResponse()) {
Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
$order2 = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId());
$order1 = Mage::getModel('sales/order')->load($postdata['orderid']);
$total_amount = (double)$order2->getGrandTotal(); //// total amount from database for an order ////
if( ((double)$postdata['amount'] == (double)$order2->getGrandTotal()) AND ($session->getLastRealOrderId() == $postdata['orderid'])) {
// success code here and redirect to success page
else { // print error message }
$order2 is returning nothing but $order1 returning correct values.
Above code is working in development site. I found that problem is in production database.
Can anyone point me any correct direction!
Can anyone help me with this issue?
I'm making an API call with 50 entries per page.
I get results, but how can i display the next page ?
How to use pagination ? i don't have a clue where to start.
I really need some help here.
Thanks
This is the controller
if (!empty($_POST['submit'])) {
$aaa = $_POST['kikozasearch'];
}else {
$aaa = $_POST['kikozasearch'];
}
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = ''; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = $aaa; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findItemsByKeywords";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&paginationInput.pageNumber=$currentpage";
$apicall .= "&paginationInput.entriesPerPage=50";
//$apicall .= "&paginationOutput.totalPages";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
$pic = $item->galleryURL;
$link = $item->viewItemURL;
$title = $item->title;
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div><img src=\"$pic\"></td><td>$title$pag</div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<div class='alert alert-danger'><h4>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h4></div>";
}
echo "We found: ".$resp->paginationOutput->totalEntries . " resaults!";
echo "<div class='alert alert-info'>".$results."</div>";
// echo $resp->paginationOutput->entriesPerPage;
// echo "<br>";
// echo $resp->paginationOutput->totalEntries;
// echo "<br>";
// echo $resp->paginationOutput->totalPages;
echo $currentpage;
echo "/".$resp->paginationOutput->totalPages;
echo "<br />";
$totalpages = $resp->paginationOutput->totalPages;
Here is the post request
<script>
$(document).ready(function(){
$('#form').on('submit', function(info){
info.preventDefault();
$.post('<?php echo base_url();?>index.php/ebayapps/searchitem',
$('#form').serialize(),
function(data){
$('#resaults').html(data);
}
);
}); // keyup
});
</script>
If I understand correctly, you want to load more than one page of results. In this case, you will need to make numerous API requests, depending on the total number of pages you wanted to retrieve in the first place.
So say you want four pages - you need to run your function four times and increment paginationInput.pageNumber in each loop.
I hope this helps.
The problem is with this PHP code that goes through an AJAX function and sends the content of a Form to a specific e-mail.
The essential part of the script is working, but some text appears to be converted in the Inbox when the e-mail arrives. Specifically, single-quotes (') are replaced with double-quotes (").
After searching the web and browsing SO, I couldn't find an answer. Any help would be deeply appreciated.
The code follows.
<?php
require '../config/squareconfig.php';
if($_POST)
{
//check if ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
//check $_POST vars are set, exit if any missingc
if(!isset($_POST["usercName"]) || !isset($_POST["usercEmail"]) || !isset($_POST["usercMessage"]))
{
die();
}
//Sanitize input data using PHP filter_var().
$user_cName = filter_var($_POST["usercName"], FILTER_SANITIZE_STRING);
$user_cEmail = filter_var($_POST["usercEmail"], FILTER_SANITIZE_EMAIL);
$user_cMessage = filter_var($_POST["usercMessage"], FILTER_SANITIZE_STRING);
if(strlen($user_cName)<4) // If length is less than 4 it will throw an HTTP error.
{
header('HTTP/1.1 500 Name is too short or empty!');
exit();
}
if(!filter_var($user_cEmail, FILTER_VALIDATE_EMAIL)) //email validation
{
header('HTTP/1.1 500 Please enter a valid email!');
exit();
}
if(strlen($user_cMessage)<5) //check emtpy message
{
header('HTTP/1.1 500 Too short message! Please enter something.');
exit();
}
//proceed with PHP email.
$headers = 'From: '.$user_cEmail.' ';
$templatemail = PHP_EOL . PHP_EOL . 'User E-mail:' . PHP_EOL . $user_cEmail;
#$sentMail = mail($squarecmail, $squarecsubject, $user_cMessage . PHP_EOL . $templatemail, $user_cName);
if(!$sentMail)
{
header('HTTP/1.1 500 Could not send mail! Sorry..');
exit();
}else{
echo $squarectymessage . '<br>' . '<div class="subagain">' . $squarecontagain . '</div>';
?>
<script type="text/javascript">
$('#contact_form').fadeOut();
</script>
<?php
}
}
I'm uncertain about the "problem", but a reasonable suggestion might be to send the e-mail as HTML, since filter_var() returns html-entities for non-alphanumeric characters. Specify the content type for the e-mail message.
$headers = "From: yomama#jokes.com\r\n";
$headers .= "Reply-To: arenot#always.funny\r\n";
$headers .= "CC: yomamasobig#whenshewearsayellowcoatppleyell.taxi\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$mail_sent = #mail($sender, $subject, $message, $headers);
The above suggestion is based on the fact that FILTER_SANITIZE_STRING causes html-unicode-encoding (or some such) on the mentioned characters.
$ php-shell
PHP-Shell - Version 0.3.1, with readline() support
(c) 2006, Jan Kneschke <jan#kneschke.de>
>> echo filter_var('\' -- "', FILTER_SANITIZE_STRING);
' -- "
First of all I had my sandbox merchant account configured to receive IPN. I will show you the first half of my codes that is sent to Paypal:
function process() {
$my_email = 'jaylimix-facilitator#hotmail.com';
$item_name = $this->input->post('item_name');
$amount = $this->input->post('amount');
$function = $this->input->post('function');
$return_url = base_url() . 'order/'.$function;
$cancel_url = 'http://cancel.com';
$notify_url = base_url() . 'test';
$querystring .= "?business=" . urlencode($my_email) . "&";
$querystring .= "item_name=" . urlencode($item_name) . "&";
$querystring .= "amount=" . urlencode($amount) . "&";
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=" . urlencode($return_url) . "&";
$querystring .= "cancel_return=" . urlencode($cancel_url) . "&";
$querystring .= "notify_url=" . urlencode($notify_url);
header('location:https://www.sandbox.paypal.com/cgi-bin/webscr' . $querystring);
}
The customer is redirected to PayPal to complete payment. When the Pay button is clicked, I checked to see if any POST variable is received:
class Test extends CI_Controller{
function index(){
foreach ($_POST as $key => $value) {
echo $key . ' ' . $value . '<br/>';
}
}
}
But there is none received and I do not know where the problem is. Please give your advices, thanks!
When the Pay button is clicked, I checked to see if any POST variable is received:
It isn't. PayPal invokes the notifyURL separately at a later time, not 'when the Pay button is clicked'. When PayPal returns to your site, all you know is that they have been to PayPal. In any case you shouldn't do anything of value for the customer until PayPal tells you that you actually have the money.
I am trying to create a script that I can access via URL so that it outputs delivery details, specifically the fields I need to display are: orderID, status, gift_message and a custom customer address attribute that is called "delivery_instructions". So far I have the following, but I am stuck with trying to get the delivery instructions, any help would be much appreciated.
<?php
require_once 'app/Mage.php';
Mage::app('default');
$myOrder=Mage::getModel('sales/order');
$orders=Mage::getModel('sales/mysql4_order_collection');
$message = Mage::getModel('giftmessage/message');
$customer = Mage::getModel('customer/customer');
$orders->addFieldToFilter('total_paid',Array('gt'=>0)); //Amount paid larger than 0
//$orders->addFieldToFilter('gift_message_id',Array('gt'=>0));
$allIds=$orders->getAllIds();
foreach($allIds as $thisId) {
$myOrder->reset()->load($thisId);
$shippingAddress = $myOrder->getShippingAddress();
$customerDetails = $myOrder->getCustomer();
//echo $myOrder->shippingaddress->getData('delivery_instructions');
$customer_id = $myOrder->getCustomerId() . "',";
echo $customer_id . "',";
echo "'" . $myOrder->getStatus() . "',";
echo "'" . $myOrder->getIncrementID() . "',";
$gift_message_id = $myOrder->getGiftMessageId();
if(!is_null($gift_message_id)) {
$message->load($gift_message_id);
echo $gift_message = $message->getData('message') . "',";
};
$customer = Mage::getModel('customer/customer')->load( $customer_id);
echo $customer = $customer->getData('incrementId');
echo "\r\n";
echo "<br/ >";
}
?>
You are close with this:
//echo $myOrder->shippingaddress->getData('delivery_instructions');
In order to get the shipping address object you need to use:
$myOrder->getShippingAddress()
and to get the delivery_instruction from the shipping address object:
$myOrder->getShippingAddress()->getDeliveryInstructions()
You can create custom address attributes and custom customer attributes.
Customer attributes can be accessed like this:
// A customer is not mandatory for an order.
if($myOrder->getCustomerId()){
$customer = Mage::getModel(’customer/customer’)->load($myOrder->getCustomerId());
$customer->getDeliveryInstructions();
}
Address attributes can be accessed like this:
$myOrder->getShippingAddress()->getDeliveryInstructions();