Add new product in Magento through REST API - php

I'm running Magento sample code for a REST API
(http://www.magentocommerce.com/api/rest/introduction.html)
I achieved a correct authentication, with an authentication token, and after the POST I got feedback of a correct upload with this message:
Array (
[url] => http://magentohost.pt/magento/api/rest/products
[http_code] => 200
[download_content_length] => 37
[content_type] => text/html
[size_download] => 37
[size_upload] => 250
)
However, the sent data doesn't appear in database/magento.
In any of the sample codes on the Magento API REST page, I get communication with the API but not the changes on products/customers data of the database.
What am I doing wrong ?

This is how you can create products using REST API
<?php
/**
* Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://magentohost/oauth/token';
$apiUrl = 'http://magentohost/api/rest';
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$productData = json_encode(array(
'type_id' => 'simple',
'attribute_set_id' => 4,
'sku' => 'simple' . uniqid(),
'weight' => 1,
'status' => 1,
'visibility' => 4,
'name' => 'Simple Product',
'description' => 'Simple Description',
'short_description' => 'Simple Short Description',
'price' => 99.95,
'tax_class_id' => 0,
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
print_r($oauthClient->getLastResponseInfo());
}
} catch (OAuthException $e) {
print_r($e);
}
Reference: http://www.magentocommerce.com/api/rest/introduction.html#RESTAPIIntroduction-CreateasimpleproductasanAdminuserwithOAuthauthentication

Related

Accessing google drive by running cron job

Here I am using google drive to backup my data on drive and for that I wrote a script which i want to run through cronjob. but it needs access_token to access google drive. I am keeping access token in my db and providing it to backup file but that token is not getting updated through cronjob . but when I am running it on browser then working fine. I want to update token through cronjob which didn't get updated.
oauth2callback.php
<?php
require_once '../inc/google/vendor/autoload.php';
require_once '../classes/dbconnection.class.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType("offline");
$client->setRedirectUri('https://******/controllers/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE);
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$token_data = $client->getAccessToken();
update_token($token_data);
$redirect_uri = 'https://******/controllers/db_backup.php?action=backup';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function update_token($data){
$db = new dbconnection;
$conn = $db->connect('pf_central');
$update_token = $conn->query("UPDATE google_drive_token SET access_token = '{$data['access_token']}', token_type = '{$data['token_type']}', expires_in = '{$data['expires_in']}', created = '{$data['created']}' WHERE id = '1'");
}
?>
db_backup.php
<?php
date_default_timezone_set('Asia/Kolkata');
require_once '../classes/dbconnection.class.php';
$week = array(
'Sun' => '0',
'Mon' => '1',
'Tue' => '2',
'Wed' => '3',
'Thu' => '4',
'Fri' => '5',
'Sat' => '6'
);
$folder = array(
'Sun' => '0B7nanNCGzXwLbmx3emVQNFBLNlU',
'Mon' => '0B7nanNCGzXwLb0hDTWFLVmNza3c',
'Tue' => '0B7nanNCGzXwLaVFtRkVRcUU0NFE',
'Wed' => '0B7nanNCGzXwLdlFwQVZuOURSZjA',
'Thu' => '0B7nanNCGzXwLSUhBMnVQVWpVUzQ',
'Fri' => '0B7nanNCGzXwLUGJmOFJId19TVGs',
'Sat' => '0B7nanNCGzXwLcnhhV2tvMUdFNkk'
);
if($_GET['action'] == 'backup' || $_GET['action'] == 'Backup' || $_GET['action'] == 'BACKUP' || $_GET['action'] == 'backup#'){
require_once '../inc/google/vendor/autoload.php';
require_once '../classes/dumper.class.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType("offline");
$client->addScope(Google_Service_Drive::DRIVE);
$db = new dbconnection;
$conn = $db->connect('pf_central');
$token_data = $conn->query("SELECT access_token,token_type,expires_in,created FROM google_drive_token WHERE id = '1'")->fetch_assoc();
//var_dump($token_data);
if (isset($token_data) && $token_data) {
$client->setAccessToken($token_data);
$drive_service = new Google_Service_Drive($client);
// $files_list = $drive_service->files->listFiles(array())->getFiles();
$timestamp = strtotime(date("Y-m-d"));
$day = date("D", $timestamp);
$backup_result = $conn->query("SELECT `cd`.`db_name`,`b`.`backup`,`b`.`id`,`b`.`file_id`,`b`.`file_name` FROM `client_db` AS `cd` INNER JOIN `backup` AS `b` ON `cd`.`id` = `b`.`client_id` WHERE `b`.`backup` <> '2' AND `day_code` = '{$week[$day]}' ");
if($backup_result->num_rows ){
while ($row = $backup_result->fetch_assoc()){
try {
if($row['backup'] == 0){
if(isset($row['file_id']) && !empty($row['file_id']))
deleteFile($drive_service,$row['file_id']);
$world_dumper = Shuttle_Dumper::create(array(
'host' => 'localhost',
'username' => 'Joeroot',
'password' => '*****',
'db_name' => $row['db_name'],
));
$zipFilename = $row['db_name'].'.sql.gz';
$world_dumper->dump($zipFilename); // if dump is not working then please check a folder perimission and change it to '777'
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '1',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
$file = new Google_Service_Drive_DriveFile(array(
'name' =>$zipFilename ,
'parents' => array($folder[$day])
));
$result = $drive_service->files->create($file, array(
'data' => file_get_contents($zipFilename),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
));
if($result['id']){
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '2',`file_id`='{$result['id']}',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
unlink($zipFilename);
}
}
else if($row['backup'] == 1){
$file = new Google_Service_Drive_DriveFile(array(
'name' =>$row['file_name'] ,
'parents' => array($folder[$day])
));
$result = $drive_service->files->create($file, array(
'data' => file_get_contents($row['file_name']),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
));
if($result['id']){
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '2',`file_id`='{$result['id']}',`file_name`='{$row['file_name']}' WHERE `id` = '{$row['id']}' ");
unlink($row['file_name']);
}
}
} catch(Shuttle_Exception $e) {
//$update_backup = $conn->query("UPDATE `backup` SET `backup`= '0',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
}
}
}
else
echo "No data to backup";
} else {
$redirect_uri = 'https://papa.fit/controllers/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
else if ($_GET['action'] == 'reSchedule' || $_GET['action'] == 'RESCHEDULE' || $_GET['action'] == 'reschedule' ) {
$db = new dbconnection;
$conn = $db->connect('pf_central');
$timestamp = strtotime(date("Y-m-d"));
$day = date("D", $timestamp);
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '0' WHERE `day_code` = '{$week[$day]}' ");
if($update_backup)
echo "Resheduled databases for next backup";
}
function deleteFile($service, $fileId) {
try {
$service->files->delete($fileId);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>

Magento 2.0 REST API Oauth error

The below php script is our rest api to retrieve customer info as admin
-The script is getting the admin login and authorize page correctly but after the authorize it is giving the error
OAuthException Object ( [message:protected] => Invalid auth/bad
request (got a 403, expected HTTP/1.1 20X or a redirect)
[string:Exception:private] => [code:protected] => 403 [file:protected]
=> /home/xxxx/public_html/oauth_admin.php [line:protected] => 39 [trace:Exception:private] => Array ( [0] => Array ( [file] =>
/home/xxxxx/public_html/oauth_admin.php [line] => 39 [function] =>
fetch [class] => OAuth [type] => -> [args] => Array ( [0] =>
http://www.xxxxx.com/api/rest/customers [1] => Array ( ) [2] => GET
[3] => Array ( [Content-Type] => application/xml [Accept] => / ) ) ) )
[previous:Exception:private] => [lastResponse] =>
{"messages":{"error":[{"code":403,"message":"Access denied"}]}}
[debugInfo] => Array ( [sbs] => xxxxx [body_recv] =>
{"messages":{"error":[{"code":403,"message":"Access denied"}]}} ) ))
I have tried every blog/post to try get this working and at this stage no doubt its something very obvious but I cant spot it...help greatly appreciated!
<?php
$callbackUrl = "http://www.site2.com/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://www.site1.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'https://www.site1.com/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://www.site1.com/oauth/token';
$apiUrl = 'http://www.site1.com/api/rest';
$consumerKey = 'xxxxx';
$consumerSecret = 'xxxxx';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/customers";
//$oauthClient->fetch($resourceUrl);
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/xml', 'Accept' => '*/*'));
$customers = json_decode($oauthClient->getLastResponse());
print_r($customers);
}
} catch (OAuthException $e) {
print_r($e);
}
Can't comment yet, but does the user have the correct roles? Had the same problem and it turned out to be a user that wasn't allowed to access parts of Magento.
Here's a link to the documentation of Magento which explains this: http://devdocs.magento.com/guides/m1x/api/rest/permission_settings/permission_settings.html
Also: go to System > Permissions and check if the user you use to connect to the api has the proper permissions.

Paypal: Change amount after transaction is instantiated

This is the scenario, User instantiate a paypal transaction (eg.$100) but returns to the site without cancelling from paypal and decided to choose a different amount (eg.$25). When it redirects to paypal it still charges $100. Is there any way of updating that amount?
//CODE SNIPPET
$transactionDetails = array(
"amount" => array(
"total" => $total,
"currency" => PAYPAL_CURRENCY
),
"description" => "Adding $".$total.PAYPAL_CURRENCY
);
$returnUrl = site_url('referral/addFundForUser');
$cancelUrl = site_url('referral/');
$paymentMethod = "paypal";
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => $returnUrl,
"cancel_url" => $cancelUrl
),
"payer" => array(
"payment_method" => $paymentMethod
),
"transactions" => array($transactionDetails)
);
$header = array(
'Content-Type: application/json',
'Authorization: '.$tokenType. ' '.$accessToken
);
$url = $this->url.'v1/payments/payment';
return $this->doCurlCall($url,$data,$header);
FYI:
I was saving user $transactionDetails in Session so that when paypal redirects back to me, I can update my payment Log.
if (!$this->getTransactionInfo() ){
$newTransaction = $this->paypal->startSale($this->getTokenType(),$this->getAccessToken(),$transactionDetails);
$transactionInfo = array(
"paymentTransactionId" => $newTransaction->id,
"total" => $total
);
foreach($newTransaction->links as $key=>$value){
if (strcmp($value->rel,'self') == 0){
$transactionInfo['self'] = $value->href;
}else if (strcmp($value->rel,'approval_url') == 0){
$transactionInfo['approval'] = $value->href;
$data['approval_url'] = $value->href;
}else if (strcmp($value->rel,'execute') == 0){
$transactionInfo['execute'] = $value->href;
}
}
$this->setTransactionInfo($transactionInfo,true);//SAVES IN SESSION
$paymentTransactionId = $newTransaction->id;
}else{
$newTransaction = $this->getTransactionInfo();
$paymentTransactionId = $newTransaction['paymentTransactionId'];
}
$successMsg = "Paypal Transaction Instantiated";
if ($this->insertPaymentLog($paymentTransactionId,$total,$payerId="",false,$successMsg,"",$transactionType)){
}
$data['transactionDetails'] = $transactionDetails;
$approval = $this->getTransactionInfo()['approval'];
redirect($approval);
FIX
if (!$this->getTransactionInfo() || $total != $this->getTransactionInfo()['total']){

SOAP connection with Royal Mail, Could not connect to host

I'm trying to connect to Royal Mail shipping API, but I'm receiving the famous Could not connect to host.
$api_password = "****";
$api_username = "****";
$api_application_id = "****";
$api_service_type = "D";
$api_service_code = "SD1";
$api_service_format = "";
$api_certificate_passphrase = "****";
$time = gmdate('Y-m-d\TH:i:s');
$created = gmdate('Y-m-d\TH:i:s\Z');
$nonce = mt_rand();
$nonce_date_pwd = xyz(copy from sample);
$passwordDigest = zyz(copy from sample);
$ENCODEDNONCE = zyz(copy from sample);
$soapclient_options = array();
$soapclient_options['cache_wsdl'] = 'WSDL_CACHE_NONE';
$soapclient_options['local_cert'] = "CA2+Splash+Felipe+RM10001654+usr.p12";
$soapclient_options['passphrase'] = $api_certificate_passphrase;
$soapclient_options['trace'] = true;
$soapclient_options['ssl_method'] = 'SOAP_SSL_METHOD_SSLv3';
$soapclient_options['location'] = '****';
//launch soap client
$client = new SoapClient("SAPI/ShippingAPI_V2_0_8.wsdl", $soapclient_options);
$client->__setLocation($soapclient_options['location']);
(setting header)
$HeaderObject = new SoapVar( $HeaderObjectXML, XSD_ANYXML );
//push soap header
$header = new SoapHeader( 'oasis-200401-wss-wssecurity-utility-1.0.xsd', 'Security', $HeaderObject );
$client->__setSoapHeaders($header);
(setting request part)
if($api_service_enhancements != "") {
$request['requestedShipment']['serviceEnhancements'] = array('enhancementType' => array('serviceEnhancementCode' => array('code' => $api_service_enhancements)));
}
//try make the call
try {
$response = $client->__soapCall('createShipment', array($request), array('soapaction' => '***api-link***') );
} catch (Exception $e) {
//catch the error message and echo the last request for debug
echo $e->getMessage();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
die;
}
Is it correct the way I'm setting the connection and the local cert?
Is any information I'm missing?
Thanks & Regards
Follow my final code :) this one works for sure. Even have the retry in case the server is buzy, enjoy.
<?php
//ini_set('soap.wsdl_cache_enabled', '1');
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
class royalmaillabelRequest
{
private $apiapplicationid = "insert urs";
private $api_password = "insert urs";
private $api_username = "insert urs"; //"rxxxxxAPI"
private $api_certificate_passphrase = "insert urs";
private $locationforrequest = 'https://api.royalmail.com/shipping/onboarding'; //live 'https://api.royalmail.com/shipping' onbording 'https://api.royalmail.com/shipping/onboarding'
private $api_service_enhancements = "";
private function preparerequest(){
//PASSWORD DIGEST
$time = gmdate('Y-m-d\TH:i:s');
$created = gmdate('Y-m-d\TH:i:s\Z');
$nonce = mt_rand();
$nonce_date_pwd = xyz(copy from sample);
$passwordDigest = nyz(copy from sample);
$ENCODEDNONCE = (copy from sample);
//SET CONNECTION DETAILS
$soapclient_options = array();
$soapclient_options['cache_wsdl'] = 'WSDL_CACHE_NONE';
$soapclient_options['stream_context'] = stream_context_create(
array('http'=>
array(
'protocol_version'=>'1.0'
, 'header' => 'Connection: Close'
)
)
);
$soapclient_options['local_cert'] = dirname(__FILE__) . "/certificate.pem";
$soapclient_options['passphrase'] = $this->api_certificate_passphrase;
$soapclient_options['trace'] = true;
$soapclient_options['ssl_method'] = 'SOAP_SSL_METHOD_SSLv3';
$soapclient_options['location'] = $this->locationforrequest;
$soapclient_options['soap_version'] = 'SOAP_1_1';
//launch soap client
$client = new SoapClient(dirname(__FILE__) . "/SAPI/ShippingAPI_V2_0_8.wsdl", $soapclient_options);
$client->__setLocation($soapclient_options['location']);
//headers needed for royal mail//D8D094Fd2716E3Es142588808s317
$HeaderObjectXML = '<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-D8D094FC22716E3EDE14258880881317">
<wsse:Username>'.$this->api_username.'</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">'.$passwordDigest.'</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">'.$ENCODEDNONCE.'</wsse:Nonce>
<wsu:Created>'.$created.'</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>';
//push the header into soap
$HeaderObject = new SoapVar( $HeaderObjectXML, XSD_ANYXML );
//push soap header
$header = new SoapHeader( 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', 'Security', $HeaderObject );
$client->__setSoapHeaders($header);
return $client;
}
public function CreateShippiment($data){
$request = $this->buildCreateshippiment($data);
$type = 'createShipment';
return $this->makerequest($type, $request);
}
public function PrintLabel($shipmentNumber,$order_tracking_id){
$time = gmdate('Y-m-d\TH:i:s');
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $order_tracking_id
)
),
'shipmentNumber' => $shipmentNumber,
'outputFormat' => 'PDF',
);
$type = 'printLabel';
$response = $this->makerequest($type, $request);
return $response->label;
}
private function makerequest($type, $request){
$client = $this->preparerequest();
$response = false;
$times = 1;
while(true){
try {
$response = $client->__soapCall( $type, array($request), array('soapaction' => $this->locationforrequest) );
// echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
} catch (Exception $e) {
print_r($e);
if($e->detail->exceptionDetails->exceptionCode == "E0010" && $times <= 25){
sleep(1.5);
$times++;
continue;
}else{
echo $e->getMessage();
echo "<pre>";
print_r($e->detail);
echo $client->__getLastResponse();
echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
}
}
break;
}
return $response;
}
private function buildCreateshippiment($data2) {
$time = gmdate('Y-m-d\TH:i:s');
$data = new ArrayObject();
foreach ($data2 as $key => $value)
{
$data->$key = $value;
}
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $data->order_tracking_id
)
),
'requestedShipment' => array(
'shipmentType' => array('code' => 'Delivery'),
'serviceOccurrence' => 1,
'serviceType' => array('code' => $data->api_service_type),
'serviceOffering' => array('serviceOfferingCode' => array('code' => $data->api_service_code)),
'serviceFormat' => array('serviceFormatCode' => array('code' => $data->api_service_format)),
'shippingDate' => date('Y-m-d'),
'recipientContact' => array('name' => $data->shipping_name, 'complementaryName' => $data->shipping_company),
'recipientAddress' => array('addressLine1' => $data->shipping_address1, 'addressLine2' => $data->shipping_address2, 'postTown' => $data->shipping_town, 'postcode' => $data->shipping_postcode),
'items' => array('item' => array(
'numberOfItems' => $data->order_tracking_boxes,
'weight' => array( 'unitOfMeasure' => array('unitOfMeasureCode' => array('code' => 'g')),
'value' => $data->order_tracking_weight,
)
)
),
//'signature' => 0,
)
);
if($data->api_service_enhancements == 6 && $data->api_service_type == 1){
$request['requestedShipment']['serviceEnhancements'] = array('enhancementType' => array('serviceEnhancementCode' => array('code' => $data->api_service_enhancements)));
}
return $request;
}
}
docs.oasis-open.org is slow and doesn't respond in time.
Download oasis-200401-wss-wssecurity-utility-1.0.xsd and modify ShippingAPI_V2_0_8.wsdl to use local version.
Your location looks wrong..
$soapclient_options['location'] = '****';
Shouldn't this look like this..
$soapclient_options['location'] = 'https://api.royalmail.com/shipping/onboarding';

Google latitude returns empty location resource. Anything wrong in this Oauth flow?

using examples I have this code. It works fine, authorizes the proper scopes and everything:
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
session_start();
set_include_path('/home/library/'.get_include_path());
require_once 'Zend/Oauth/Consumer.php';
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => 'ivana.2x.to',
'consumerSecret' => '*********',
'signatureMethod' => 'HMAC-SHA1',
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/latitude/apps/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken',
'callbackUrl' => 'http://ivana.2x.to/geo/?show=callback',
);
$consumer = new Zend_Oauth_Consumer($oauthOptions);
if (!isset($_SESSION['ACCESS_TOKEN_GOOGLE'])) {
if (!empty($_GET)) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN_GOOGLE']));
$_SESSION['ACCESS_TOKEN_GOOGLE'] = serialize($token);
} else {
$token = $consumer->getRequestToken(array('scope'=>'https://www.googleapis.com/auth/latitude'));
$_SESSION['REQUEST_TOKEN_GOOGLE'] = serialize($token);
$customparams = array('domain' => 'ivana.2x.to', 'granularity' => 'best', 'location' => 'current');
$consumer->redirect($customparams );
exit;
}
} else {
$token = unserialize($_SESSION['ACCESS_TOKEN_GOOGLE']);
//$_SESSION['ACCESS_TOKEN_GOOGLE'] = null; // do not use, we want to keep the access token
}
$client = $token->getHttpClient($oauthOptions);
$client->setUri('https://www.googleapis.com/latitude/v1/currentLocation');
$client->setMethod(Zend_Http_Client::GET);
$response = $client->request();
$body = $response->getBody();
header('Content-Type: ' . $response->getHeader('Content-Type'));
echo $response->getBody();
No my problem is that i get an empty location resource. It just looks like this:
{"data":{"kind":"latitude#location"}}
The data is missing. But no error or anything.
I am logged in and my location is set and google guarantees lon and lat to be returned.
Any ideas?
I was a little miss guided by the api description. Once i passed the granularity parameter, everything worked fine. I also had to add it with $client->addParameterGet('granularity','best'), because oterhwise the oauth signing would not work.

Categories