Set a reminder for a Google Calendar event using PHP - php

I am developing a site to add events to a Google Calendar using code from this blog post.
Now I want to set a reminder for each event that is set 15 minutes before the event.
Can anyone give me some direction on how to achieve this?

Setting a reminder when creating an event is very easy. You just have to add a couple additional lines to the <gd:when></gd:when> tag.
<gd:when startTime='2006-03-30T22:00:00.000Z' endTime='2006-03-30T23:00:00.000Z'>
<gd:reminder minutes='15' method='email' />
<gd:reminder minutes='15' method='alert' />
</gd:when>
Here's an updated addEvent() method that includes support for reminders:
public function addEvent($params) {
$url = "http://www.google.com/calendar/feeds/{$this->getFeedEmail()}/private/full";
//startTime should be a time() value so we can convert it into the correct format
$params["startTime"] = date("c", $params["startTime"]);
//If no end-time is specified, set the end-time to 1 hour after the start-time
if(!array_key_exists("endTime", $params)) {
$params["endTime"] = date("c", strtotime($params["startTime"])+60*60*1);
}
$reminders = '';
if(is_array($params['reminders'])) {
foreach($params['reminders'] as $rem) {
$reminders .= "<gd:reminder minutes='{$rem['minutes']}' method='{$rem['method']}' />"\n;
}
}
$xml = "<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"></category>
<title type="text">{$params["title"]}</title>
<content type="text">{$params["content"]}</content>
<gd:transparency value="http://schemas.google.com/g/2005#event.opaque">
</gd:transparency>
<gd:eventstatus value="http://schemas.google.com/g/2005#event.confirmed">
</gd:eventstatus>
<gd:where valuestring="{$params["where"]}"></gd:where>
<gd:when starttime="{$params["startTime"]}" endtime="{$params["endTime"]}">
{$reminders}
</gd:when>
</entry>";
//Do the initial POST to Google
$ret = $this->calPostRequest($url, $xml);
//If Google sends back a gsessionid, we need to make the request again
$matches = array();
if(preg_match('/gsessionid=(.*?)\s+/', $ret, $matches)) {
$url .= "?gsessionid={$matches[1]}";
$ret = $this->calPostRequest($url, $xml);
}
//Parse the XML response (which contains the newly added entry)
$retFields = explode("\n", $ret);
//print_r($retFields);
$entryXML = simplexml_load_string($retFields[count($retFields)-1]);
//Return an array containing the entry id (url) and the etag
return array(
"id"=> (string)$entryXML->id,
"etag"=> $this->getETagFromHeader($retFields),
"link"=> $this->getEditLinkFromHeader($retFields)
);
}
And you would call it like this:
$entryData = $cal->addEvent(array(
"title"=> "Auto Test event",
"content"=> "This is a test event",
"where"=> "Test location",
"startTime"=> time()+60*60*24*1,
"reminders"=> array(
array("method"=>"email", "minutes"=>"15"),
array("method"=>"alert", "minutes"=>"15"),
)
));

Related

PHP eBay GetOrders API (Unable To fetch Any Data)

I am Trying to fetch ebay orders by using getOrders API, when i execute ebay PHP SDK it print:
"Sorry No entries found in the Time period requested. Change CreateTimeFrom/CreateTimeTo and Try again"
Please Help me...
Official ebay PHP SDK code :
<?php
/* © 2013 eBay Inc., All Rights Reserved */
/* Licensed under CDDL 1.0 - http://opensource.org/licenses/cddl1.php */
?>
<?php require_once('get-common/keys.php') ; //include keys file for auth token and other credentials ?>
<?php require_once('get-common/eBaySession.php') ; //include session file for curl operations ?>
<?php
//SiteID must also be set in the Request's XML
//SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, ....
//SiteID Indicates the eBay site to associate the call with
$siteID = 0;
//the call being made:
$verb = 'GetOrders';
//Time with respect to GMT
//by default retreive orders in last 30 minutes
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-(2*40*24*60*60)); //current time minus 80 Days
//echo "</br>";
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
$requestXmlBody .= "<CreateTimeFrom>".$CreateTimeFrom."</CreateTimeFrom><CreateTimeTo>".$CreateTimeTo."</CreateTimeTo>";
$requestXmlBody .= '<OrderRole>Seller</OrderRole><OrderStatus>All</OrderStatus>';
$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
$requestXmlBody.="<WarningLevel>High</WarningLevel>";
$requestXmlBody .= '</GetOrdersRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//echo "<pre>";
//var_dump($responseXml);
//die;
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//if there are error nodes
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
//Display code and shortmessage
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}else { //If there are no errors, continue
if(isset($_GET['debug']))
{
header("Content-type: text/xml");
print_r($responseXml);
}else
{ //$responseXml is parsed in view.php
include_once 'view.php';
}
}
?>
I would recommend the ebay-sdk-php from devbay.net :
https://github.com/davidtsadler/ebay-sdk-php
https://github.com/davidtsadler/ebay-sdk-examples
As for the date, I could be wrong, but I think it requires DateTime. Something like
CreateTimeFrom = new DateTime('02-10-2016');
CreateTimeTo = new DateTime('02-11-2016');
But I think you will have an easier time with the ebay-sdk-php
edit:
Actually I've been messing around with this more lately.
The default works for me
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-1800); //current time minus 30 minutes
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
or you can hardcode your range like the following:
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
such as the following:
$CreateTimeFrom = '2017-03-20T00:00:00Z'; //GMT
$CreateTimeTo = '2017-03-22T00:00:00Z'; //GMT
Alternatively, you can just simply not use CreatedTimeTo and CreatedTimeFrom and use NumberOfDays instead
which is basically just commenting out CreatedTimeTo and CreatedTimeFrom
//$requestXmlBody .= "<CreateTimeFrom>$CreateTimeFrom</CreateTimeFrom><CreateTimeTo>$CreateTimeTo</CreateTimeTo>";
and directly underneath it use NumberOfDays
$requestXmlBody .= "<NumberOfDays>2</NumberOfDays>";

How to get eBay item URL based on item ID

I would like to get the item URL based on the item ID. After searching, I found that I can use GetSingleItem to achieve my goal. However, I got an error:
eBay returned the following error(s):
2 : Unsupported API call.
The API call "GetSingleItem" is invalid or not supported in this release.
Here is my code (all configuration are correct because I can use GetOrders by using these configs):
$subverb = "GetSingleItem";
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= "<ItemID>111986554711</ItemID>";
$requestXmlBody .= '</GetSingleItemRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $subverb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//if there are error nodes
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
//Display code and shortmessage
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
} else { //If there are no errors, continue
if (isset($_GET['debug'])) {
header("Content-type: text/xml");
print_r($responseXml);
} else {
print("\n; 111986554711: " . $response->Item->ViewItemURLForNaturalSearch);
}
}
Any suggestion? Thank you .
As you discovered, you don't need the API to construct a simple eBay view item landing page URL.
The URL format you discovered works, but it's very old and might not be supported in full or for much longer.
Here's a simple URL format that is pretty current that you can use:
http://www.ebay.com/itm/122225724269
I got an answer without using api. Here is the answer: after I got item ID, I can use "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=".$item_id to show my product on ebay.
I found this uri by using GetOrders API.
OrderArray.Order .TransactionArray.Transaction .Variation .VariationViewItemURL
Tip: "not optimized for natural search"
If anyone has any idea about "GetSingleItem", I am willing to know why my code doesn't work.

Get all items with all details in XML format

I am trying to get all items using the ebay API in XML format.
See the below code for the same.
require_once('config/ebay_config.php');
require_once('helpers/eBaySession.php');
session_start();
//SiteID must also be set in the Request's XML
//SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, ....
//SiteID Indicates the eBay site to associate the call with
$siteID = 0;
//the call being made:
$verb = 'GetSellerList';
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSellerListRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<EndTimeFrom>2015-12-12T11:36:06.487Z</EndTimeFrom>';
$requestXmlBody .= '<EndTimeTo>2016-03-12T11:36:06.487Z</EndTimeTo>';
$requestXmlBody .= '<RequesterCredentials><eBayAuthToken>' . $userToken . '</eBayAuthToken></RequesterCredentials>';
$requestXmlBody .= '<UserID>****</UserID>';
$requestXmlBody .= '<DetailLevel>ItemReturnDescription</DetailLevel>';
$requestXmlBody .= '<Pagination><EntriesPerPage>200</EntriesPerPage><PageNumber>1</PageNumber></Pagination>';
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
$errors = $responseDoc->getElementsByTagName('Errors');
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
echo '<BR/>User Session ID: ' . $_COOKIE["eBaySession"] . '';
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}
else { //no errors
//get the nodes needed
$sellerNode = $responseDoc->getElementsByTagName('Seller');
if ($sellerNode->length > 0) {
echo '<P><B>Seller</B>';
$userIDNode = $sellerNode->item(0)->getElementsByTagName('UserID');
$scoreNode = $sellerNode->item(0)->getElementsByTagName('FeedbackScore');
$regDateNode = $sellerNode->item(0)->getElementsByTagName('RegistrationDate');
echo '<BR>UserID: ', $userIDNode->item(0)->nodeValue;
echo '<BR>Feedback Score: ', $scoreNode->item(0)->nodeValue;
echo '<BR>Registration Date: ', $regDateNode->item(0)->nodeValue;
}
}
It just returns seller info, but give advice for the get all items with all details.
And also one more thing, I'm done with login ebay API, and also get a success message on ebay site from below URL but I want to throw on a particular PHP page with userid.
https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RuName=<?php echo $RuName; ?>&SessID=<?php echo $sessionID; ?>
Presuming that when you say 'All Items' you mean that you want to retrieve all seller listings:
You need to change your DetailLevel node in your initial request to 'ReturnAll'. See the following API page for details. Please note, it is not technically recommended to use the ReturnAll DetailLevel, so you may want to find precisely what you need and only return that level of detail.
eBay GetSellerList
If you are looking for All Items in a category or something (ie not associated with your seller account) you need to use the finding API if I recall correctly.. I originally said advertising but that's not eBay =p

Collect Form Data, insert in xml fields to post to Payment Gateway

I need to take payment information from a form and place it in XML and then post it to the payment gateway server. I am rather a novice at best and I am not sure of the easiest way to do this.
I have successfully been able to post to the payment gateway by manually entering the info into the XML on a static php file, so I know the XML is correct, the only real issue for me would be finding the easiest way to take form data and place into the XML.
Below is a sample of the php file and the XML.
<?php
$TransactionId = intval( date(Yms). rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9). rand(0,9) );
$MerchantId="111111";
$TerminalId="111111";
$ApiPassword="111111";
$private_key="asdfasghgfdhggdfgs";
$ApiPassword_encrypt=hash('sha256',$ApiPassword);
$xmlReq='<?xml version="1.0" encoding="UTF-8" ?>
<TransactionRequest xmlns="https://test.processing.com/securePayments/direct/v1/processor.php">
<Language>ENG</Language>
<Credentials>
<MerchantId>'.$MerchantId.'</MerchantId>
<TerminalId>'.$TerminalId.'</TerminalId>
<TerminalPassword>'.$ApiPassword_encrypt.'</TerminalPassword>
</Credentials>
<TransactionType>LP001</TransactionType>
<TransactionId>'.$TransactionId.'</TransactionId>
<ReturnUrl page="http://www.website.net/response.php">
<Param>
<Key>inv</Key>
<Value>'.$TransactionId.'</Value>
</Param>
</ReturnUrl>
<CurrencyCode>USD</CurrencyCode>
<TotalAmount>44450</TotalAmount>
<CardDetails>
<CardHolderName>John Smith</CardHolderName>
<CardNumber>4653111111111111</CardNumber>
<CardExpireMonth>01</CardExpireMonth>
<CardExpireYear>15</CardExpireYear>
<CardType>VI</CardType>
<CardSecurityCode>030</CardSecurityCode>
<CardIssuingBank>UNKNOWN</CardIssuingBank>
<CardIssueNumber></CardIssueNumber>
</CardDetails>
</TransactionRequest>';
$signature_key=trim($private_key.$ApiPassword.$TransactionId);
$signature=base64_encode(hash_hmac("sha256", trim($xmlReq), $signature_key, True));
$encodedMessage=base64_encode($xmlReq);
markup your static xml with some sort of placeholder like {{key}}. then use this function to fill your xml:
<?php
function fill_template($tpl, $values = array()) {
$find = array();
preg_match_all("/\\{\\{([^}]+)\\}\\}/", $tpl, &$find);
foreach ($find[1] as $x => $key) {
$repl = '';
if (isset($values[$key])) {
$repl = $values[$key];
}
$tpl = str_replace($find[0][$x], $repl);
}
return $tpl;
}
?>
the $values parameter should contain the values from $_POST, along with whatever other values you need to set:
<?php
$payment_map = array('MerchantId' => 'xxx', 'TerminalId' => 'xxx');
$payment_map = array_merge($payment_map, $_POST);
$xml_template = "your markedup xml";
$xml = fill_template($xml_template, $payment_map);
?>
this may not be the most elegant solution but it should get you moving.
(obviously you'll want to validate form data and encode it into proper xml characters if necessary.)

DHL Tracking Api and PHP

I'm currently working on a project, where i have to get the status of a packet (sent with DHL). I read about the DHL API, which return an XML, but somehow there are no good examples out there. I have found some code snippets, but i have no clue where to register for API Key's.
Have anyone some links or examples for me?
Best regards,
Lukas
There is also this PHP client that can be used to consume the DHL XML API. It can handle all the different services exposed by DHL.
https://github.com/alfallouji/DHL-API
This client does not rely or depend on any framework and it should be fairly easy to integrate with your own code. You can check the samples folder for example on how to use it.
https://github.com/jklz/DHL-API-Tracking-PHP
It is used to connect into DHL using the XML-PI to track shipments using the Air Way Bill. it can handle a single tracking number or as many as you feed into it (has been tested with 250 and other then taking a little time to run had no problems). automatically takes and breaks the array of tracking numbers into chunks and then sends the request to DHL making sure not to pass the max number that can be tracked per request then returns the results as a array.
Quick and dirty without any third party lib and using official API:
<?php
$mode = 'sandbox'; // sandbox or production
$username = ''; // dhl developer account name, not email
$password = ''; // dhl developer account pass
$appname = 'zt12345'; // sandbox app
$apppass = 'geheim'; // sandbox app
$endpoint = 'https://cig.dhl.de/services/' . $mode . '/rest/sendungsverfolgung';
$payload = simplexml_load_string( '<?xml version="1.0" encoding="UTF-8" standalone="no"?><data appname="' . $appname . '" language-code="de" password="' . $apppass . '" piece-code="" request="d-get-piece-detail"/>' );
$shipmentids = array(
'00340434161094015902' // in sandbox only special numbers are allowed
);
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Basic " . base64_encode( "$username:$password" )
)
);
$context = stream_context_create( $opts );
foreach ( $shipmentids as $shipmentid ) {
$payload->attributes()->{'piece-code'} = $shipmentid;
$response = file_get_contents( $endpoint . '?' . http_build_query( array( 'xml' => $payload->saveXML() ) ), false, $context );
$responseXml = simplexml_load_string( $response );
$status = null;
// get last state
foreach ( $responseXml->data->data->data as $event ) {
$status = $event->attributes()->{'event-short-status'};
}
echo "Shipment " . $shipmentid . " is in state: " . $status . "\n";
}
There is a nice blog about this. It is unfortunately in German, but the code that is displayed there should still make sense to you.
Source: https://blog.simlau.net/dhl-tracking-api-php.html
Excerpt:
function dhl_tracking($trackingnumber)
{
$data = '<?xml version="1.0" encoding="ISO-8859-1" ?>';
$data .= '<data appname="nol-public" password="anfang" request="get-status-for-public-user" language-code="de">';
$data .= ' <data piece-code="'.$trackingnumber.'"></data>';
$data .= '</data>';
// URL bauen und File hohlen
$xml = simplexml_load_file(sprintf(
'http://nolp.dhl.de/nextt-online-public/direct/nexttjlibpublicservlet?xml=%s', $data
));
// FALSE, wenn Syntax oder HTTP Error
if ($xml === false) return false;
// Wandelt das SimpleXML Objekt in ein Array um
foreach ($xml->data->data->attributes() as $key => $value) {
$return[$key] = (string) $value;
}
return $return;
}
// Aufruf der Funktion
print_r(dhl_tracking($tracking_number));
This function will give back an array that will contain some tracking information:
Array
(
[status] => Die Sendung wurde erfolgreich zugestellt.
[recipient-id-text] => Nachbar
[product-name] => DHL PAKET
[pan-recipient-name] => SIMON LAUGER
)
(In fact, there is WAY more data in there.)
I hope this will help you in some way.

Categories