Integrate Sitelink using php - php

I want to integrate Sitelink with my website using php. For demo they have just provided this code
echo '<p>Testing SiteLink...</p>';
define( 'SITELINK_URL', "https://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define( 'SITELINK_CORP_CODE', "CCTST" );
define( 'SITELINK_LOC_CODE', "Demo" );
define( 'SITELINK_CORP_LOGIN', "Administrator" );
define( 'SITELINK_CORP_PASS', "Demo" );
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
try
{
$units = $client->SiteInformation( $params );
$result = $units->SiteInformationResult;
}
catch (Exception $e )
{
die( 'Error: '.$e->getMessage().'<br>'.$e );
}
echo htmlentities( $result->any );
But I am not able to understand how to fecth the data and process it using php. I have to Fetch unit sizes and their respective prices. Any help is greatly appreciated. Thanks in advance.

You are not trying to get Units you are getting SiteInformation
add type for $params first:
$params = new stdClass; // as stdClass
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
then:
$units = $client->UnitTypePriceList($params);
$result = $units->UnitTypePriceListResult->any;
and you have to parse the data with DOMDocument, check the tag name you want to display and print it out:
$dom = new DOMDocument;
$dom->loadXML($result);
$xpath = new DOMXPath($dom);
$el = $xpath->query('//Table');
foreach($el as $units){
$UnitID = $xpath->query('UnitID_FirstAvailable', $units)->item(0)->nodeValue;
echo $UnitID;
}
I don't know what are your desired values, but I took UnitID_FirstAvailable as example.

SiteInformation is expecting array not Object and your $params was never declared
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient(SITELINK_URL);
$params = array("sCorpCode" => SITELINK_CORP_CODE,"sLocationCode" => SITELINK_LOC_CODE,"sCorpUserName" => SITELINK_CORP_LOGIN,"sCorpPassword" => SITELINK_CORP_PASS);
try {
$units = $client->SiteInformation($params);
header("Content-Type: text/xml");
print($units->SiteInformationResult->any);
} catch ( Exception $e ) {
die('Error: ' . $e->getMessage() . '<br>' . $e);
}
See Live DEMO

I know this is kind of old, but I've been doing some extensive work with the API. First off, you'll want this: SiteLink API Documentation
To get all available units, you could do something like this:
// define API connection credentials
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
$params->lngLastTimePolled = 0;
$params->bTestMode = true;
try
{
$units = $client->UnitsInformationAvailableUnitsOnly_v2($params);
$result = $units->UnitsInformationAvailableUnitsOnly_v2Result;
}
catch (Exception $e)
{
die( 'Error: '.$e->getMessage().'<br />'.$e );
}
echo '<table>';
$formatUnits = new SimpleXMLElement($result->any);
foreach($formatUnits->NewDataSet->Table as $unit){
echo "<tr>\r\n";
echo "<td><a href='#' data-unit-number='".$unit->sUnitName."' data-unit-id='".$unit->UnitID."' data-rate='".$rate."' class='res-unit-link'>".$unit->sUnitName."</a></td>\r\n";
echo "<td>".$unit->sTypeName."</td>\r\n";
echo "</tr>\r\n";
}
echo '</table>';
You could do var_dump($formatUnits) to see all available data in the object that gets returned by SiteLink. The above code is an example from something I made where I used jQuery to grab all of the data- attributes from the link to use for the rental/reservation process.
I hope this helps somebody. I really could have used it when I first started using the API.

Related

Prestashop Webservice to add simple product

I am writing a script that will add products through the webservice.
I`m having some dificulties for a couple of hours so I seek for help.
This is what I have now.
require_once("config.php");
require_once("PSWebServiceLibrary.php");
try {
$webService = new PrestaShopWebservice(SITE_URL, WEBSERVICE_AUTH_KEY, DEBUG_MODE);
$xml = $webService->get(array('url' => SITE_URL.'/api/products?schema=synopsis'));
$product = $xml->children()->children();
$product->price = 99;
$product->wholesale_price = 89;
$product->active = '1';
$product->on_sale = 0;
$product->show_price = 1;
$product->available_for_order = 1;
$product->name->language[0][0] = "Produit webservice";
$product->name->language[0][0]['id'] = 1;
$product->name->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->description->language[0][0] = "Description produit webservice";
$product->description->language[0][0]['id'] = 1;
$product->description->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->description_short->language[0][0] = "Descr. courte";
$product->description_short->language[0][0]['id'] = 1;
$product->description_short->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->reference = "ref_product_webservice";
$product->depends_on_stock = 0;
$category_id = 3;
$product->associations->categories->addChild('category')->addChild('id', $category_id);
$product->id_category_default = $category_id;
//
$opt = array('resource' => 'products');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
}
catch (PrestaShopWebserviceException $ex) {
echo "Error:<br>";
echo $ex->getMessage();
exit(1);
}
I have my webservice all set up , but I keep getting this error :
This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.
Please tell me what I am doing wrong.
Enable debug mode in your Prestashop. You will receive exactly which field are you setting wrong and why.
Enable Pretashop debug mode
Good luck.
Changed the schema to blank , and now it`s working.
The initial error was:
Attribute "href" bound to namespace

mongoDB, ajax, php to only display new messages

It might be a silly question, but I think it will be useful for all new mongoDB users and not just myself.
I am currently working on a live chat script as a way to learn about mongoDB. I am having trouble with only loading new messages into chat rather than loading all messages and replacing old ones. This is what I have.
My PHP:
try
{
$m = new Mongo(); // connect
$db = $m->selectDB("local");
}
catch ( MongoConnectionException $e )
{
echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
exit();
}
$collection = $db->selectCollection("message");
echo "".$collection." selected";
$cursor = $collection->find();
// iterate cursor to display title of documents
foreach ($cursor as $document) {
echo $document["sender"].": ". $document["message"] . "<br>";
My JS:
function get_new(){
var messages = $.ajax({
type: "POST",
url: "ajax/receive.php",
async: false
}).success(function(){
setTimeout(function(){get_new();}, 10000);
}).responseText;
$('div.messages').html(messages);
}
My messages collection:
"createdAt" => $now,
"sender" => $sender,
"message" => $message
I know that my JS would eventually start using .append(messages), but I really don't know what to do with my PHP. So how do I change my php to only find new messages (older than last set of messages)
Found the answer. Use sessions to store the time of last update. So The PHP code will look like this:
$now = date("Y-m-d H:i:s");
$last = $_SESSION["last_message_ts"];
$session_last = new MongoDate(strtotime($last));
$session_now = new MongoDate(strtotime($now));
$_SESSION["last_message_ts"]=$now;
try
{
$m = new Mongo(); // connect
$db = $m->selectDB("local");
}
catch ( MongoConnectionException $e )
{
echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
exit();
}
$collection = $db->selectCollection("message");
$cursor = $collection->find(array("createdAt" => array('$gt' => $session_last, '$lte' => $session_now)));
// iterate cursor to display title of documents
foreach ($cursor as $document) {
echo $document["sender"].": ". $document["message"];
}

libphonenumber for php

I am using https://github.com/davideme/libphonenumber-for-PHP for formatting phonenumbers
I am having issue with 1800 numbers
$formatnumber = "1800123456"
$country = "AU";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
$NumberProto = $phoneUtil->parse( $formatnumber , $country );
} catch ( NumberParseException $e ) {
echo $e;
}
$formattedNumber = $phoneUtil->format( $NumberProto, PhoneNumberFormat::NATIONAL );
What I am expecting to get back from $formattedNumber is "1800 123456"
What I get back is an unformatted number "1800123456"
If there something I need to do doing to get it to format correctly?
It works for me with pretty much your code:
<?php
require __DIR__ . '/vendor/autoload.php';
$formatnumber = "1800123456";
$country = "AU";
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
$NumberProto = $phoneUtil->parse($formatnumber, $country);
} catch (NumberParseException $e) {
echo $e;
}
$formattedNumber = $phoneUtil->format($NumberProto, \libphonenumber\PhoneNumberFormat::NATIONAL);
echo $formattedNumber;
Response:
1800 123 456
I am using my version of libphonenumber-for-php though: https://github.com/giggsey/libphonenumber-for-php

Exporting Invoices from Magento

I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source

Getting Menu Parameters from Joomla

I'm trying to get parameters from the menu table in Joomla. What I have below is working in the sense that it is returning the parameters.
$menu = &JSite::getMenu();
$item = $menu->getItem($menuId)->params;
print $items;
However, It's returning them in plain text, as if I had just queried the column and returned the params contents.
Can someone tell me how to return this as an Object or Array so that I can use something like:
$myParam = $item->getParams('theParamIwant');
I think JParameter is obsolete in Joomla! 3.x, so the answer now is something like:
$app = JFactory::getApplication();
$menuitem = $app->getMenu()->getActive(); // get the active item
$menuitem = $app->getMenu()->getItem($theid); // or get item by ID
$params = $menuitem->params; // get the params
print_r($params); // print all params as overview
You can get the menu_image variable by doing:
echo $params->get('menu_image');
Or first check if it's filled in and, if it is, echo it:
// using get() with a second parameter makes it fall back to this if nothing is found
$menu_image = $params->get('menu_image', false);
if ($menu_image && strlen($menu_image)) {
echo "<img src='$menu_image'/>";
}
Or, using a tertiary operator:
$menuimg = $params->get('menu_image')
echo strlen($menuimg) ? "<img src='$menuimg'/>" : '';
You need to use the JParameter class to read the params. Try something like this:
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');
It doesn't work
Try to use this:
$params = $menus->getParams($menuId);
$myParam = $params->get('theParamIwant');
$app = JFactory::getApplication();
$params = $app->getParams();
$yourParameter = $params->get('YOURPARAMETERNAME');
($currentMenuId = JSite::getMenu()->getActive()->id ; // `enter code here`
$document =& JFactory::getDocument(); // `enter code here`
$app = JFactory::getApplication(); // `enter code here`
$menuitem = $app->getMenu()->getItem($currentMenuId); // or get item by ID `enter code here`
$params = $menuitem->params; // get the params `enter code here`
$params->get('menu-meta_keywords');
if($document->description == '') // 116 is the ID number of the menu pointing to the component `enter code here`
{
$this->setMetaData( 'description', $params->get('menu-meta_description') );
$this->setMetaData( 'keywords', $params->get('menu-meta_keywords') );
}
else
{
// do nothing
})
Working in 3.5.1
$app = JFactory::getApplication();
$currentMenuId = JSite::getMenu()->getActive()->id;
$menuitem = $app->getMenu()->getItem($currentMenuId);
$params = $menuitem->params;
echo $params['menu_image'];
Shows menu item image
JParameter is deprecated in Joomla 2.5, so to get Kevin's code to work add
jimport( 'joomla.html.parameter' ) before i.e
jimport( 'joomla.html.parameter' );
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');

Categories