I am trying to develop a script (using the PHP example app as a basis) that will post a note to Evernote based on GET values.
When I insert this to the end of functions.php's listNotebooks()
$note_obj = new Note(array(
'contents' => $note_contents,
'title' => $title
));
It throws a 500 error. (In my code, $title & $note_contents are defined earlier. I have spent a lot of time trying to find proper documentation for the PHP API but it just seems non-existent. Any information on this topic would be greatly appreciated
Update: I did not realize the API was using PHP Namespaces: This fixed the issue:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
My code to add a note still does not work but I'll post it here once I figure it out.
These classes need to be imported:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
This will define our new note:
$noteAttr = new NoteAttributes();
$noteAttr->sourceURL = "http://www.example.com";
$note = new Note();
$note->guid = null;
$note->title = "My Title";
$note->content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"><en-note>My Content</en-note>';
$note->contentHash = null;
$note->contentLength = null;
$note->created = time()*1000;
$note->updated = time()*1000;
$note->deleted = null;
$note->active = null;
$note->updateSequenceNum = null;
$note->notebookGuid = null;
$note->tagGuids = null;
$note->resources = null;
$note->attributes = $noteAttr;
$note->tagNames = null;
addNote($note);
This function will add a new note:
function addNote($newnote) {
global $noteRet;
if (empty($noteRet)) {
define("noteStoreHost", "sandbox.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");
$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
$noteRet = $noteStore->createNote($_SESSION['accessToken'], $newnote);
return $noteRet;
}
}
Related
In my script this line of code using Bit-Wasp library for PHP gives me the following ERROR:
Deprecated: Non-static method BitWasp\Bitcoin\Key\Factory\PrivateKeyFactory::fromWif() should not be called statically
What can be the problem? Searched Examples from the Lib and many other examples with Bit-Wasp none of it worked. ((
use BitWasp\Bitcoin\Bitcoin;
.......
$addrCreator = new AddressCreator();
$transaction = TransactionFactory::build()
->input('some UTXO', 0)
->payToAddress(1000, $addrCreator->fromString('some addres'))
->payToAddress(1000, $addrCreator->fromString('some addres'))
->get();
$hex = $transaction->getHex();
$privateKey = 'WIF PRiVATE KEY';
$tx = TransactionFactory::fromHex($hex);
$utxos = [];
foreach ($tx->getInputs() as $idx => $input) {
$txid = $input->getOutPoint()->getTxId()->getHex();
$vout = $input->getOutPoint()->getVout();
$scriptPubKey = $input->getScript()->getBuffer()->getHex();
$utxo = new Utxo(new OutPoint(Buffer::hex($txid, 32), $vout), new TransactionOutput(0, ScriptFactory::fromHex($scriptPubKey)));
array_push($utxos, $utxo);
}
$priv = $factory->fromWif($privateKey);
$priv = PrivateKeyFactory::fromWif($privateKey);
$signer = new Signer($tx, Bitcoin::getEcAdapter());
foreach ($utxos as $i => $utxo) {
$signer->sign($i, $priv, $utxo->getOutput());
}
$signed = $signer->get();
echo $signed->getHex() . PHP_EOL;
PS all other functions from the Lib work fine.. just cannot figure out how sign raw tx using WIF private key ((
Any help is highly appreciated.
Thanks!
This is no tested code, just an explanation.
A static method is called on a class directly and not on an instance.
It looks like the library changed. So create an instance and call the method on it like:
$factory = new PrivateKeyFactory();
$key = $factory->fromWif($privateKey);
I use James Armes's PHP-EWS library.
The following code works fine with single attachments, but fails with multiply files.
<?php
$msgRequest->MessageDisposition = 'SaveOnly';
$msgResponse = $ews->CreateItem($msgRequest);
$msgResponseItems = $msgResponse->ResponseMessages->CreateItemResponseMessage->Items;
// Create attachment(s)
$attachments = array();
$i = 0;
foreach ($message_details['attachment'] as $attachment) {
$attachments[$i] = new EWSType_FileAttachmentType();
$attachments[$i]->Content = file_get_contents($attachment['path'] . '/' . $attachment['file']);
$attachments[$i]->Name = $attachment['file'];
$i++;
}
//
// Attach files to message
$attRequest = new EWSType_CreateAttachmentType();
$attRequest->ParentItemId = $msgResponseItems->Message->ItemId;
$attRequest->Attachments = new EWSType_NonEmptyArrayOfAttachmentsType();
$attRequest->Attachments->FileAttachment = $attachments;
$attResponse = $ews->CreateAttachment($attRequest);
$attResponseId = $attResponse->ResponseMessages->CreateAttachmentResponseMessage->Attachments->FileAttachment->AttachmentId;
// Save message id from create attachment response
$msgItemId = new EWSType_ItemIdType();
$msgItemId->ChangeKey = $attResponseId->RootItemChangeKey;
$msgItemId->Id = $attResponseId->RootItemId;
// Send and save message
$msgSendRequest = new EWSType_SendItemType();
$msgSendRequest->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
$msgSendRequest->ItemIds->ItemId = $msgItemId;
$msgSendRequest->SaveItemToFolder = true;
$msgSendResponse = $ews->SendItem($msgSendRequest);
$response = $msgSendResponse->ResponseMessages->SendItemResponseMessage;
?>
$ews->SendItem() returns this error:
Uncaught SoapFault exception: [a:ErrorSchemaValidation] The request
failed schema validation: The required attribute 'Id' is missing.
What do I miss here?
Found the answer here:
https://github.com/jamesiarmes/php-ews/issues/132
Basically Exchange does not use an array if there is only one attachment, so an additional check is required to determine where to get the ID from.
if(!is_array($attResponse->ResponseMessages->CreateAttachmentResponseMessage))
$attResponseId = $attResponse->ResponseMessages->CreateAttachmentResponseMessage->Attachments->FileAttachment->AttachmentId;
else {
$attResponseId = $attResponse->ResponseMessages->CreateAttachmentResponseMessage[0]->Attachments->FileAttachment->AttachmentId;
}
Exchange uses the same structure with recipients. I find this inconsistent, however I am sure there is a reason behind it.
I hope someone will benefit from raising this.
I am trying to get the xml rate soap feed from UPS working.
Currently I am getting the error "Wrong version" (__Soapcall Exeption) or "0FailureHard10002The XML document is well formed but the document is not valid1" (Respons from server or php).
I took the example provided in the developers toolkit. I tried everything =>
Change soap version to 1.2
Grab wsdl from remote url instead of on
the disk
I double checked the endpoint and userid, accesskey, pass,
...
Does anyone have a working script ?, or even better can someone correct my mistake :)
Code:
<?php
class UpsRate{
private $access,$userid,$passwd,$wsdl,$operation,$endpointurl;
public function __construct() {
$this->setConfig();
}
public function setConfig($is_test = true){
$this->access = sfConfig::get('app_shipping_ups_access');
$this->userid = sfConfig::get('app_shipping_ups_userid');
$this->passwd = sfConfig::get('app_shipping_ups_password');
$this->wsdl = sfConfig::get('sf_data_dir').'/wsdl/ups/RateWS.wsdl';
$this->operation = "ProcessRate";
$this->endpointurl = $is_test?'https://wwwcie.ups.com/ups.app/xml/Rate':'https://onlinetools.ups.com/ups.app/xml/Rate';
}
private function processRate(){
//create soap request
$option['RequestOption'] = 'Shop';
$request['Request'] = $option;
$pickuptype['Code'] = '01';
$pickuptype['Description'] = 'Daily Pickup';
$request['PickupType'] = $pickuptype;
$customerclassification['Code'] = '01';
$customerclassification['Description'] = 'Classfication';
$request['CustomerClassification'] = $customerclassification;
$shipper['Name'] = 'Trutec';
$shipper['ShipperNumber'] = 'Y5562A';
$address['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$address['City'] = 'Antwerp';
//$address['StateProvinceCode'] = 'MD';
$address['PostalCode'] = '2100';
$address['CountryCode'] = 'BE';
$shipper['Address'] = $address;
$shipment['Shipper'] = $shipper;
$shipto['Name'] = 'Imani Imaginarium';
$addressTo['AddressLine'] = '21 ARGONAUT SUITE B';
$addressTo['City'] = 'ALISO VIEJO';
//$addressTo['StateProvinceCode'] = 'CA';
$addressTo['PostalCode'] = '92656';
$addressTo['CountryCode'] = 'US';
$addressTo['ResidentialAddressIndicator'] = '';
$shipto['Address'] = $addressTo;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = 'Trutec';
$addressFrom['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$addressFrom['City'] = 'Deurne';
//$addressFrom['StateProvinceCode'] = 'MD';
$addressFrom['PostalCode'] = '2100';
$addressFrom['CountryCode'] = 'BE';
$shipfrom['Address'] = $addressFrom;
$shipment['ShipFrom'] = $shipfrom;
$service['Code'] = '03';
$service['Description'] = 'Service Code';
$shipment['Service'] = $service;
$packaging1['Code'] = '02';
$packaging1['Description'] = 'Rate';
$package1['PackagingType'] = $packaging1;
$dunit1['Code'] = 'IN';
$dunit1['Description'] = 'cm';
$dimensions1['Length'] = '5';
$dimensions1['Width'] = '4';
$dimensions1['Height'] = '10';
$dimensions1['UnitOfMeasurement'] = $dunit1;
$package1['Dimensions'] = $dimensions1;
$punit1['Code'] = 'KG';
$punit1['Description'] = 'KG';
$packageweight1['Weight'] = '4';
$packageweight1['UnitOfMeasurement'] = $punit1;
$package1['PackageWeight'] = $packageweight1;
$shipment['Package'] = array( $package1 );
$shipment['ShipmentServiceOptions'] = '';
$shipment['LargePackageIndicator'] = '';
$request['Shipment'] = $shipment;
return $request;
}
public function getRate(){
try {
//nitialize soap client
$client = new SoapClient($this->wsdl , array('soap_version' => 'SOAP_1_1','trace' => 1));
//set endpoint url
$client->__setLocation($this->endpointurl);
//create soap header
$usernameToken['Username'] = $this->userid;
$usernameToken['Password'] = $this->passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $this->access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
return $client->__soapCall($this->operation ,array($this->processRate()));
}
catch(Exception $ex)
{
echo '<pre>';
return print_r($client->__getLastResponse());
echo '</pre>';
}
}
}
?>
The error notifies that your XML is being correctly formatted but you have included one or more elements that are incompatible. Are you able to dump the XML sent ? This may be easier to determine where the error is being detected.
I wouldn't recommend depending on the examples in the UPS documentation to work, they are for illustrative purposes only and probably have not been updated since the first issue.
I had the same issue, and worked this out:
When I would make test calls, they would work. The endpoint I used for the test calls was
https://wwwcie.ups.com/webservices/Rate
However, when I would change to the live calls, then I would receive the wrong version error. That endpoint is:
https://onlinetools.ups.com/webservices
I reviewed the wsdl document, and found near the end a section that looks like this:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<!-- <soap:address location="https://onlinetools.ups.com/webservices/Rate"/> -->
<!-- CIE (Customer Integration Environment) URL -->
<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>
</wsdl:port>
I noticed that the live version endpoint was commented out, so I changed the section as follows:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<soap:address location="https://onlinetools.ups.com/webservices/Rate"/>
<!-- CIE (Customer Integration Environment) URL -->
<!--<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>-->
</wsdl:port>
I'm not sure this will help anyone else, but this ended up resolving my issues.
Forgive me if this has already been answered/ is extremely basic/ the question is worded incorrectly, I am very new to this and struggling.
Basically I have back end PHP which generates XML, the flash builder then inherits the data. Where I'm stuck is understanding how the flash builder can send a parameter to the PHP through an HttpService e.g
This is what it currently interprets:
http://..../file.php?action=getitems
What I would like the flash builder to send is
&class=fruit (<- the class would be dependant on what is selected from the drop down in the application)
to overall create this string
http://..../file.php?action=getitems&class=fruit
Thank you and apologies if this is nonsense. I'm using Flash Builder 4.
This is actually rather simple in Flex...
var service : HTTPService = new HTTPService();
service.url = "http://localhost/getData.php";
service.method = "POST";
var parameters:Object = new Object();
parameters["action"] = "getitems";
parameters["class"] = "fruit";
service.send(parameters);
... done!
Overall I would use the push method instead of passing a variable, lessens the chance of getting hacked from the middle.
My AS3 Code for the http call:
public function someRequest() : void
{
var service : HTTPService = new HTTPService();
service.url = "http://localhost/getData.php";
service.useProxy = false;
service.method = "POST";
service.contentType = "application/xml"; // Pass XML data.
service.request = "<ID>somevalue</ID>"; // The XML data.
service.resultFormat = "xml"; // Recieve XML data.
service.addEventListener(ResultEvent.RESULT, createFields);
service.addEventListener(FaultEvent.FAULT, handleFault);
service.send();
}
private function createFields(event : ResultEvent) : void
{
var result : String = event.result.toString();
returnData = XML(result);
}
private function handleFault(event : FaultEvent) : void
{
var faultstring : String = event.fault.faultString;
Alert.show(faultstring);
}
As you see toward the middle, there is an XML space for entering a variable. I use this approach to pass data back and forth from the PHP to the AS3.
The PHP is:
<?php
define("DATABASE_SERVER", "localhost");
define("DATABASE_USERNAME", "root");
define("DATABASE_PASSWORD", "**");
define("DATABASE_NAME", "dbName");
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
$Query = "SELECT * from data WHERE employeeID = '" . ($_POST['ID']) . "'";
$Result = mysql_query($Query);
$Return = "<data>";
while ($User = mysql_fetch_object($Result))
{
$Return .= "<user><userid>" . $User->userid . "</userid><username>" . $User->username . "</username><emailaddress>" . $User->emailaddress . "</emailaddress></user>";
}
$Return .= "</data>";
mysql_free_result($Result);
print ($Return)
?>
Hope that helps you on your way.
I generally handle this through [POST] instead of [GET]
In your actionscript function:
private function sendRequest():void {
var obj:Object = new Object();
obj.action="getitems";
obj.class="fruit";
myService.send(obj);
Your httpService
<s:HTTPService id='myService' url='urlToYourPHP' method='POST' result='yourResultHandler' fault='yourFaultHandler' resultFormat='XML'/>
As powelljf3 said, POST is more secure then GET though it can still be gotten to.
I'm trying to use PHP and SoapClient to utilize the UPS Ratings web service. I found a nice tool called WSDLInterpreter to create a starting point library for creating the service requests, but regardless what I try I keep getting the same (non-descriptive) error:
EXCEPTION=SoapFault::__set_state(array(
'message' => 'An exception has been raised as a result of client data.',
'string' => '',
'code' => 0,
Um ok, what the hell does this mean?
Unlike some of the other web service tools I have implemented, the UPS Soap wants a security block put into the header. I tried doing raw associative array data but I wasn't sure 100% if I was injecting the header part correctly.
Using the WSDLInterpreter, it pulls out a RateService class with a ProcessRate method that excepts it's own (instance) datastructure for the RateRequest and UPSSecurity portions, but all of the above generates that same error.
Here's a sample of the code that I'm using that calls classes defined by the interpreter:
require_once "Shipping/UPS/RateService.php"; // WSDLInterpreter class library
class Query
{
// constants removed for stackoverflow that define (proprietary) security items
private $_upss;
private $_shpr;
// use Interpreter code's RateRequest class to send with ProcessRate
public function soapRateRequest(RateRequest $req, UPSSecurity $upss = null)
{
$res = false;
if (!isset($upss)) {
$upss = $this->__getUPSS();
}
echo "SECURITY:\n" . var_export($upss, 1) . "\n";
$upsrs = new RateService(self::UPS_WSDL);
try {
$res = $upsrs->ProcessRate($req, $upss);
} catch (SoapFault $exception) {
echo 'EXCEPTION=' . var_export($exception, 1) . "\n";
}
return $res;
}
// create a soap data structure to send to web service from shipment
public function getRequestSoap(Shipment $shpmnt)
{
$qs = new RateRequest();
// pickup information
$qs->PickupType->Code = '01';
$qs->Shipment->Shipper = $this->__getAcctInfo();
// Ship To address
$qs->Shipment->ShipTo->Address->AddressLine = $this->__getAddressArray($shpmnt->destAddress->address1, $shpmnt->destAddress->address2);
$qs->Shipment->ShipTo->Address->City = $shpmnt->destAddress->city;
$qs->Shipment->ShipTo->Address->StateProvinceCode = $shpmnt->destAddress->state;
$qs->Shipment->ShipTo->Address->PostalCode = $shpmnt->destAddress->zip;
$qs->Shipment->ShipTo->Address->CountryCode = $shpmnt->destAddress->country;
$qs->Shipment->ShipTo->Name = $shpmnt->destAddress->name;
// Ship From address
$qs->Shipment->ShipFrom->Address->AddressLine = $this->__getAddressArray($shpmnt->origAddress->address1, $shpmnt->origAddress->address2);
$qs->Shipment->ShipFrom->Address->City = $shpmnt->origAddress->city;
$qs->Shipment->ShipFrom->Address->StateProvinceCode = $shpmnt->origAddress->state;
$qs->Shipment->ShipFrom->Address->PostalCode = $shpmnt->origAddress->zip;
$qs->Shipment->ShipFrom->Address->CountryCode = $shpmnt->origAddress->country;
$qs->Shipment->ShipFrom->Name = $shpmnt->origAddress->name;
// Service type
// TODO cycle through available services
$qs->Shipment->Service->Code = "03";
$qs->Shipment->Service->Description = "UPS Ground";
// Package information
$pkg = new PackageType();
$pkg->PackagingType->Code = "02";
$pkg->PackagingType->Description = "Package/customer supplied";
// dimensions
$pkg->Dimensions->UnitOfMeasurement->Code = $shpmnt->dimensions->dimensionsUnit;
$pkg->Dimensions->Length = $shpmnt->dimensions->length;
$pkg->Dimensions->Width = $shpmnt->dimensions->width;
$pkg->Dimensions->Height = $shpmnt->dimensions->height;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageServiceOptions->DeclaredValue->MonetaryValue = $shpmnt->dimensions->value;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageWeight->UnitOfMeasurement = $this->__getWeightUnit($shpmnt->dimensions->weightUnit);
$pkg->PackageWeight->Weight = $shpmnt->dimensions->weight;
$qs->Shipment->Package = $pkg;
$qs->CustomerClassification->Code = 123456;
$qs->CustomerClassification->Description = "test_rate_request";
return $qs;
}
// fill out and return a UPSSecurity data structure
private function __getUPSS()
{
if (!isset($this->_upss)) {
$unmt = new UsernameToken();
$unmt->Username = self::UPSS_USERNAME;
$unmt->Password = self::UPSS_PASSWORD;
$sat = new ServiceAccessToken();
$sat->AccessLicenseNumber = self::UPSS_ACCESS_LICENSE_NUMBER;
$upss = new UPSSecurity();
$upss->UsernameToken = $unmt;
$upss->ServiceAccessToken = $sat;
$this->_upss = $upss;
}
return $this->_upss;
}
// get our shipper/account info (some items blanked for stackoverflow)
private function __getAcctInfo()
{
if (!isset($this->_shpr)) {
$shpr = new ShipperType();
$shpr->Address->AddressLine = array(
"CONTACT",
"STREET ADDRESS"
);
$shpr->Address->City = "CITY";
$shpr->Address->StateProvinceCode = "MI";
$shpr->Address->PostalCode = "ZIPCODE";
$shpr->Address->CountryCode = "US";
$shpr = new ShipperType();
$shpr->Name = "COMPANY NAME";
$shpr->ShipperNumber = self::UPS_ACCOUNT_NUMBER;
$shpr->Address = $addr;
$this->_shpr = $shpr;
}
return $this->_shpr;
}
private function __getAddressArray($adr1, $adr2 = null)
{
if (isset($adr2) && $adr2 !== '') {
return array($adr1, $adr2);
} else {
return array($adr1);
}
}
}
It doesn't even seem to be getting to the point of sending anything over the Soap so I am assuming it is dying as a result of something not matching the WSDL info. (keep in mind, I've tried sending just a properly seeded array of key/value details to a manually created SoapClient using the same WSDL file with the same error resulting)
It would just be nice to get an error to let me know what about the 'client data' is a problem. This PHP soap implementation isn't impressing me!
I know this answer is probably way too late, but I'll provide some feedback anyway. In order to make a custom SOAP Header you'll have to override the SoapHeader class.
/*
* Auth Class to extend SOAP Header for WSSE Security
* Usage:
* $header = new upsAuthHeader($user, $password);
* $client = new SoapClient('{...}', array("trace" => 1, "exception" => 0));
* $client->__setSoapHeaders(array($header));
*/
class upsAuthHeader extends SoapHeader
{
...
function __construct($user, $password)
{
// Using SoapVar to set the attributes has proven nearly impossible; no WSDL.
// It might be accomplished with a combined SoapVar and stdClass() approach.
// Security Header - as a combined XSD_ANYXML SoapVar
// This method is much easier to define all of the custom SoapVars with attributes.
$security = '<ns2:Security xmlns:ns2="'.$this->wsse.'">'. // soapenv:mustUnderstand="1"
'<ns2:UsernameToken ns3:Id="UsernameToken-49" xmlns:ns3="'.$this->wsu.'">'.
'<ns2:Username>'.$user.'</ns2:Username>'.
'<ns2:Password Type="'.$this->password_type.'">'.htmlspecialchars($password).'</ns2:Password>'.
'</ns2:UsernameToken>'.
'</ns2:Security>';
$security_sv = new SoapVar($security, XSD_ANYXML);
parent::__construct($this->wsse, 'Security', $security_sv, false);
}
}
Then call the upsAuthHeader() before the soap call.
$client = new SoapClient($this->your_ups_wsdl,
array('trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_1
)
);
// Auth Header - Security Header
$header = new upsAuthHeader($user, $password);
// Set Header
$client->__setSoapHeaders(array($header));