Using php-ews I try to create a calendar event by example (just to get the hang of it):
require $server_path.'scripts/ews/vendor/autoload.php';
use garethp\ews\API;
use garethp\ews\API\Enumeration;
use garethp\ews\API\Type;
$ews = API::withUsernameAndPassword($exchange_host, $_SESSION["user_data"]["u_email"], $_SESSION["user_data"]["u_pwd"]);
Seems to work without errors.
// Start building the request.
$calendar = $ews->getCalendar();
$start = new DateTime('8:00 AM');
$end = new DateTime('9:00 AM');
$request = array(
'Items' => array(
'CalendarItem' => array(
'Start' => $start->format('c'),
'End' => $end->format('c'),
'Body' => array(
'BodyType' => Enumeration\BodyTypeType::HTML,
'_value' => 'This is <b>the</b> body'
),
'ItemClass' => Enumeration\ItemClassType::APPOINTMENT,
'Sensitivity' => Enumeration\SensitivityChoicesType::NORMAL,
'Categories' => array('Testing', 'php-ews'),
'Importance' => Enumeration\ImportanceChoicesType::NORMAL
)
),
'SendMeetingInvitations' => Enumeration\CalendarItemCreateOrDeleteOperationType::SEND_TO_NONE
);
$request = Type::buildFromArray($request);
$response = $ews->CreateItem($request);
I get:
PHP Fatal error: Call to undefined method garethp\ews\API::CreateItem() in
in the execute part ($ews->CreateItem())
Please take a look at my examples/, they cover exactly this. The firs thing to note is that creating Calendar events is incredibly simplified, so your long request isn't entirely needed. That being said, if you want to access the functions directly, you can't do
$response = $ews->CreateItem($request);
you need to do
$response = $ews->getClient()->CreateItem($request);
More info on building requests manually can be found here.
Related
I'm new to SOAP and trying to connect to a SOAP server using PHP's built-in SoapClient. I am receiving this error for days now and didn't find any solution.
This is for a Linux Server. I've tried to include SoapHeaders with timestamps and add different parameters to the request, but still have not succeeded.
This is my code:
$params = array(
'X' => array(
'Y' => '0',
'Z' => '1',
'Q' => array(
'W' => array(
'E' => '1'
)
),
'R' => array(
'T' => 3,
'Y' => array(
'U' => 'x',
'I' => 'y'
)
),
'O' => array(
'P' => '2'
)
),
'A' => array(
'S' => array(
'D' => 'H',
'F' => 'J',
'G' => 'K'
)
)
);
$client = new SoapClient( 'https://path-to-wsdl', array( 'trace' => 1 ) );
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$timestamp_expires = gmdate("Y-m-d\TH:i:s\Z", strtotime( '+1 hour' ) );
$authHeader = new stdClass();
$authHeader->Timestamp->Created = $timestamp;
$authHeader->Timestamp->Expires = $timestamp_expires;
$Headers[] = new SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', $authHeader,TRUE);
// $client->__setSoapHeaders($Headers);
try
{
$response = $client->SoapFunction( $params );
}
catch( SoapFault $fault )
{
echo 'Request : <br/><xmp>',
$client->__getLastRequest(),
'</xmp><br/><br/> Error Message : <br/>',
$fault->getMessage();
die;
}
I expect a response from the server, but receive this error code instead:
No id attribute on element http://schemas.xmlsoap.org/soap/envelope/:Body
Edit:
Code wsse:InvalidSecurity
I believe there should be a certificate security (.pem file) associated with the SOAP API you are calling. Once you pass that certificate path along with SOAP request, it should work.
For adding certificate in your SOAP request, you just need modify your SOAP call like below code.
$client = new SoapClient( 'https://path-to-wsdl', array( 'trace' => 1, local_cert' => dirname(__FILE__) . '/certificatefile.pem'; ) );
I've tried using SoapClient from PHP and maybe it's just me but my experience has been absolutely horrible.
You should give CURL a try. Also, here's the approach I use for WSDL requests:
Make it work on a client like Postman
Once you've got the correct format and headers, you can copy the generated PHP code from postman and focus on making it dynamic within your own environment
Print out your XML requests and compare it to working Postman requests
I know it's not the best approach, but if I had a dollar for every time I started debugging SoapClient requests and switched to CURL, I'd be a millionaire already
It is possible that the authHeader should be a other than stdClass.
Try to use this tool:
https://github.com/wsdl2phpgenerator/wsdl2phpgenerator
It will generate PHP classes out of your wsdl file.
Using these classes it will be easier to follow the structure of how to build a request and what exactly you need to send.
I trying to insert an event in the Google Calendar. The authentication and to fetch events works without any problems. Unfortunately I got the following error message:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Missing end time."
}
],
code: 400,
message: "Missing end time."
}
}
I request the site with cURL in PHP. To count the Content-Length for the request I using the function countArrayChars(). The following is my code:
$start = date("c", strtotime($start));
$end = date("c", strtotime($end));
$data_array = array(
"end"=>array("dateTime"=>$end),
"start"=>array("dateTime"=>$start),
"summary"=>$name
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.googleapis.com/calendar/v3/calendars/primary/events',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array("Content-length: ".countArrayChars($data_array),"Content-type: application/json","Authorization: Bearer $access_token\r\n"),
CURLOPT_POSTFIELDS => $data_array
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
function countArrayChars(array $array){
$charNumber = 0;
array_walk_recursive($array, function($val, $key) use (&$charNumber)
{
$charNumber += strlen($val) + strlen($key);
});
return $charNumber;
}
What I also tried is to set the data as a http_build_query, as well as a json_encode result. Unfortunately this also didn't work.
Thanks for every response.
UPDATE:
$data_array = array(
"end"=>array("dateTime"=>$end,"timeZone"=>"Europe/Zurich"),
"start"=>array("dateTime"=>$start,"timeZone"=>"Europe/Zurich"),
"summary"=>$name
);
UPDATE 2:
This is the output of $end
string(25) "2017-03-10T00:00:00+01:00"
I don't know if this will help you, but this is the code I use to add events to google calendar through the API:
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
You usually need to add a timezone, like I have, which could be your problem. I would suggest trying that out first.
Update:
I can't find anything else that could be wrong with your code, it's probably something having to do with how Google accepts data. All I can offer you now is exactly how I do mine, which I know works:
First, follow the instructions here to setup service account, if not done already. Make sure to create a .p12 file, instead of JSON.
You can download the PHP Google Calendar File here as well, without needing to use composer.
Next, work with the code below to suit your needs, but this should work for you. (The dateTime was properly formatted before it was sent in POST, so you may need to change that)
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$client_email = "clientemail"; //client email setup when you create the authorization in Google Developer Console.
$private_key = file_get_contents("privatekey.p12"); //location on your server where the .p12 file you created is stored
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = "primary"; //This can also be an email address associated with the current gmail login if you don't want to use the default one
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
); //Keep everything in this array the same
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
$service = new Google_Service_Calendar($client);
$calendarId = $useremail;
$event = $service->events->insert($calendarId, $event);
echo json_encode($event);
Check that $start is less than $end.
the error of google is not correct.
you have to check al inputfield for strange symbols. I had Straße in locationfield...that gave the missing endtime error.
Hi the problem may be on special characters in the variable, must try to encode UTF-8.
please try this
'summary' => utf8_encode($summary),
'description' => utf8_encode($descripcion),
'location' => utf8_encode($location),
regards,
Luis
Pretty specific problem, but I'll lay it out as best I can.
I can easily make a POST request to the TradeGecko API (detailed here: http://developer.tradegecko.com/) and get variant prices in return, that part of the interaction is working smoothly.
However, I'm trying to create a new order and I feel like I'm missing something!
Here's what I have:
<?php
$authorizeUrl = 'https://api.tradegecko.com/oauth/authorize';
$accessTokenUrl = 'https://api.tradegecko.com/oauth/token';
$clientId = <MY_CLIENT_ID>;
$clientSecret = <MY_CLIENT_SECRET>;
$redirectUrl = <REDIRECT_URI>;
// https://github.com/adoy/PHP-OAuth2
require("Client.php");
require("GrantType/IGrantType.php");
require("GrantType/AuthorizationCode.php");
$client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT,$userAgent);
$client->setAccessToken(<MY_ACCESS_TOKEN>);
$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);
$params =
array('order' =>
array(
'company_id' => '12345',
'shipping_address_id' => 1,
'billing_address_id' => 1,
'status' => 'active',
'issued_at' => '10-04-2016',
'order_line_items' => array(
array('variant_id' => 123456,
'quantity' => 2),
array('variant_id' => 123457,
'quantity' => 2)
)
)
);
$response = $client->fetch('https://api.tradegecko.com/orders', false, $params);
print_r($response);
?>
I'm hoping that there's something in that code that someone else might spot, I've been staring at it for the better part of 6 hours now, and I can't figure out why this won't go through.
I am using the following php script in mule. When i am running this php file individually(through wamp) i am able to get the required output.
<?php
$client1=new SoapClient('example/v2_soap?wsdl', array('trace' => 1, 'connection_timeout' => 120));
$username = '******';
$password = '******';
//retreive session id from login
$session = $client1->login(
array(
'username' => $username,
'apiKey' => $password,
)
);
$result= $client1->catalogProductInfo(
array(
'sessionId' => $session->result,
'productId' => 1,
)
);
print_r($result);
return $result;
?>
But i want to run the following script through mule. So when i am running it through mule i am getting the following error.
Root Exception stack trace:
com.caucho.quercus.QuercusErrorException: eval::5: Fatal Error: 'SoapClient' is an unknown class name.
at com.caucho.quercus.env.Env.error(Env.java:4480)
at com.caucho.quercus.env.Env.error(Env.java:4399)
at com.caucho.quercus.env.Env.createErrorException(Env.java:4130)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
It says SoapClient is an unknown class. What is the problem here?
Do i have to include some SoapClient here? If so where can i find it. Please help!!
I'm not sure if mule supports php extensions, but that's what it seems by the error. You could try downloading nusoap into your project,
which doesn't require any php extension. The syntaxis is a little bit different though, but shouldn't be harder to adapt your code.
For what it's worth, this is a simple example of a soap request using nusoap (taken from here http://www.richardkmiller.com/files/msnsearch_nusoap.html):
require_once('nusoap/lib/nusoap.php');
$request = array('Request' => array(
'AppID' => 'MSN_SEARCH_API_KEY',
'Query' => 'Seinfeld',
'CultureInfo' => 'en-US',
'SafeSearch' => 'Strict',
'Flags' => '',
'Location' => '',
'Requests' => array(
'SourceRequest' => array(
'Source' => 'Web',
'Offset' => 0,
'Count' => 50,
'ResultFields' => 'All'))));
$soapClient = new soapclient("http://soap.search.msn.com/webservices.asmx?wsdl", false);
$result = $soapClient->call("Search", $request);
print_r($result);
I hope it helps.
I understand there seems to be a problem with running the soap client inside quercus (rather than Mule).
However instead of focusing on it I would suggest to take a look to the CXF client and the Web services consumer. You are running inside of Mule a powerful opensource ESB, there is no need to write a php script to consume a service, you have all that functinality already present.
I need to generate the following XML with SOAP:
...
<InternationalShippingServiceOption>
<ShippingService>StandardInternational</ShippingService>
<ShippingServiceCost currencyID="USD">39.99</ShippingServiceCost>
<ShippingServicePriority>1</ShippingServicePriority>
<ShipToLocation>CA</ShipToLocation>
</InternationalShippingServiceOption>
...
So I have the following SOAP array in PHP to do this:
$params = array(
'InternationalShippingServiceOption' => array(
'ShippingService'=>'StandardInternational',
'ShippingServiceCost'=>39.99,
'ShippingServicePriority'=>1,
'ShipToLocation'=>'CA',
)
)
$client = new eBaySOAP($session); //eBaySOAP extends SoapClient
$results = $client->AddItem($params);
Everything works great, except I am not generating the currencyID="USD" attribute in the ShippingServiceCost tag in the XML. How do I do this?
You don't need to use SoapVar. This works (for me at least):
$params = array(
'InternationalShippingServiceOption' => array(
'ShippingService'=>'StandardInternational',
'ShippingServiceCost' => array('_' => 39.99, 'currencyID' => 'USD')
'ShippingServicePriority'=>1,
'ShipToLocation'=>'CA',
)
)
I'm using this technique with the PayPal SOAP API.
Why, I am glad you asked. I just solved this today.
$shippingsvccostwithid = new SoapVar(array('currencyID' => $whatever),SOAP_ENC_OBJECT, 'ShippingServiceCost', 'https://your.namespace.here.com/');
$params = array("InternationalShippingServiceOption" => array(
"ShippingService" => "StandardInternational",
"ShippingServiceCost" => $shippingsvccostwithid,
"ShippingServicePriority" => 1,
"ShipToLocation" => "CA"
);
And then continue as normal.
Please let me know if you need any more help.