Create an odoo order and invoice it via external API - php

I'm trying to integrate an third party application with odoo, the application should create the order and confirm it, to generate the invoice, the order creation works perfectly, when executing the create_invoices nothing shows and no errors appears.
require_once('ripcord/ripcord.php');
$url = "http://127.0.0.1:8069";
$db = "odoo";
$password = "";
$username = "";
$common = ripcord::client("$url/xmlrpc/2/common");
$uid = $common->authenticate($db, $username, $password, array());
$models = ripcord::client("$url/xmlrpc/2/object");
$order_data = array(
'partner_id' => 12, // Customer ID
'date_order' => date('Y-m-d'), // Order Date
// 'pricelist_id' => 1, // Price List ID
'state' => 'draft', // Order Status (draft)
'order_line' => array(array(0, 0, array( // Order Line Items
'product_id' => 2, // Product ID
'name' => 'Product Name', // Product Name
'product_uom_qty' => 5.00, // Quantity of Product
'price_unit' => 10.00, // Unit Price of Product
)))
);
$order_id = $models->execute_kw($db, $uid, $password, 'sale.order', 'create', array($order_data));
// Confirm Order and Create Invoice
if ($order_id) {
$confirmOrder = $models->execute_kw($db, $uid, $password, 'sale.order', 'action_confirm', array($order_id));
if ($confirmOrder) {
$invoiceCreate = $models->execute_kw(
$db,
$uid,
$password,
'sale.advance.payment.inv',
'create_invoices',
array(
'sale_order_ids' =>
array(
0 =>
array(
0 => 6,
1 => false,
2 =>
array(
0 => $order_id,
),
),
),
'advance_payment_method' => 'delivered',
'deduct_down_payments' => true,
'product_id' => false,
'fixed_amount' => 0,
'amount' => 0,
'deposit_account_id' => false,
'deposit_taxes_id' =>
array(
0 =>
array(
0 => 6,
1 => false,
2 => array(),
),
),
)
,
array(
"context" => array(
'active_model' => "sale.order",
"allowed_company_ids" => array(1),
'active_id' => $order_id, "active_ids" => array($order_id)
)
)
);
if ($invoiceCreate) {
echo "Order and Invoice #$invoiceCreate for Order #$order_id created successfully!\n";
} else {
echo "Error creating invoice!";
}
} else {
echo "Error confirming order!";
}
} else {
echo "Error creating order!";
}

When calling create_invoices, Odoo will consider the first parameter as ids, to see the function call details change the log_level to debug
You should see the following debug message:
DEBUG demo16 odoo.api: call sale.advance.payment.inv('s', 'a', 'l', 'e', '_', 'o', 'r', 'd', 'e', 'r', '_', 'i', 'd', 's').create_invoices('advance_payment_method', 'deduct_down_payments', 'product_id', 'fixed_amount', 'amount', 'deposit_account_id', 'deposit_taxes_id')
Odoo will fail to call create_invoices function.
To fix the issue you can call the create function to get a wizard record id then call the create_invoices
Example:
$wizard_ids = $models->execute_kw(
$db,
$uid,
$password,
'sale.advance.payment.inv',
'create',
array(array(
'sale_order_ids' => array($order_id),
)),
array(
"context" => array(
'active_model' => "sale.order",
"allowed_company_ids" => array(1),
'active_id' => $order_id, "active_ids" => array($order_id)
)
)
);
$invoiceCreate = $models->execute_kw($db, $uid, $password, 'sale.advance.payment.inv', 'create_invoices', array($wizard_ids));

Related

Drupal 8 Custom Module - From dynamic data (API) to store at Fields (Content type) Drupal DB

I've created a custom module in Drupal 8 that grab some data from an API, and puts them in the Drupal DB creating a new table.
I want to add this data as the contents of a specific content type.
How can I do that?
here is my code :
<?php
/**
* Implements hook_cron().
*/
function ods_cron() {
$message = 'Cron run: ' . date('Y-m-d H:i:s');
$ods = \Drupal::service('ods.ods');
$conf = \Drupal::service('ods.ods_configuration_request');
if ($conf->isDevelopment()) {
// Development
$response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
$response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
} else {
// Production
$parameters_bond = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyBond(),
];
$parameters_mf = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyMutualFund(),
];
$response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
$response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
}
$raw_result_bond = json_decode($response_bond);
$raw_result_mf = json_decode($response_mf);
// Development
if ($conf->isDevelopment()) {
$raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
$raw_result_mf = json_decode($raw_result_mf[0]->field_api);
}
$BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
$MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;
// Bond data store to internal
if ($BondsProductList !== null) {
$bond_datas = [];
foreach ($BondsProductList as $row => $content) {
$bond_datas[] = [
'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
'CouponFreqCode' => $content->CouponFreqCode,
'CouponFreqID' => number_format($content->CouponFreqID),
'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
'IDCurrency' => $content->IDCurrency,
'LastCoupon' => $content->LastCoupon,
'MaturityDate' => $content->MaturityDate,
'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
'MultipleOfUnit' => number_format($content->MultipleOfUnit),
'NextCoupon' => $content->NextCoupon,
'Penerbit' => $content->Penerbit,
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductAlias' => $content->ProductAlias,
'RiskProfile' => $content->RiskProfile,
'SellSettle' => $content->SellSettle
];
}
$insert_data = $ods->setData(
'bond',
[
'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
],
$bond_datas
);
if ($insert_data) {
// make response as JSON File and store the file
$ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
}
}
// Mutual Fund data store to internal
if ($MFProductInqList !== null) {
$mf_datas = [];
foreach ($MFProductInqList as $row => $content) {
$mf_datas[] = [
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductCategory' => $content->ProductCategory,
'ProductType' => $content->ProductType,
'Currency' => $content->Currency,
'Performance1' => $content->field_1_tahun_mf,
'Performance2' => $content->Performance2,
'Performance3' => $content->Performance3,
'Performance4' => $content->Performance4,
'Performance5' => $content->Performance5,
'UrlProspektus' => $content->UrlProspektus,
'UrlFactSheet' => $content->UrlFactSheet,
'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
'RiskProfile' => $content->RiskProfile,
'FundHouseName' => $content->FundHouseName,
'NAVDate' => $content->NAVDate,
'NAVValue' => $content->NAVValue
];
}
$insert_data_mf = $ods->setData(
'mutual_fund',
[
'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
'NAVDate', 'NAVValue'
],
$mf_datas
);
if ($insert_data_mf) {
// make response as JSON File and store the file
$ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
}
}
// console log
\Drupal::logger('ods')->notice($message);
}
So can I store the data to pristine drupal 8 table?
First, you need to create the content type in the Drupal 8 backend going to Structure > Content type.
Second you can add a node programmatically like this
use Drupal\node\Entity\Node;
$node = Node::create(array(
'type' => 'your_content_type',
'title' => 'your title',
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'body'=> 'your body',
));
$node->save();

Laravel inserts two user records at register, how to prevent this?

I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}

Fault Code:SOAP-ENV:Server String:Fault in Fedex Rate Service Response

require_once('modules/FedEx/RateAvailableServicesService_v18_php/library/fedex-common.php5');
$path_to_wsdl = PATH."modules/FedEx/RateAvailableServicesService_v18_php/RateService_v18.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
//'ParentCredential' => array(
//'Key' => $this->getProperty('key'),
//'Password' => $this->getProperty('password')
//),
'UserCredential' => array(
'Key' => $this->getProperty('key'),
'Password' => $this->getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => $this->getProperty('shipaccount'),
'MeterNumber' => $this->getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '18',
'Intermediate' => '0',
'Minor' => '1'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
// Service Type and Packaging Type are not passed in the request
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['Shipper'] = array(
'Address'=> array('StreetLines' => array($UL->str_add1,$UL->str_add2),'City' => $UL->city_name,'StateOrProvinceCode' => $UL->state_name,'PostalCode' => $UL->zipcode,'CountryCode' => $UL->country_code));
$request['RequestedShipment']['Recipient'] = array(
'Address'=>array('StreetLines' => array($this->session->get('shipping_address1'),$this->session->get('shipping_address2')),'City' => $shipping_city,'StateOrProvinceCode' => $shipping_state,'PostalCode' => $this->session->get('shipping_postal_code'),'CountryCode' => $country_code,'Residential' => false));
$request['RequestedShipment']['ShippingChargesPayment'] = array(
'PaymentType' => 'SENDER',
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => $this->getProperty('billaccount'),
'Contact' => null,
'Address' => array(
'CountryCode' => COUNTRY_CODE
)
)
)
);
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = array(
'0' => array(
'SequenceNumber' => 1,
'GroupPackageCount' => 1,
'Weight' => array(
'Value' => $UL->weight//,
//'Units' => 'LB'
),
'Dimensions' => array(
'Length' => $UL->length,
'Width' => $UL->width,
'Height' => $UL->height//,
//'Units' => 'IN'
)
)
);
try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
echo 'Rates for following service type(s) were returned.'. Newline. Newline;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td>';
if(is_array($response -> RateReplyDetails)){
foreach ($response -> RateReplyDetails as $rateReply){
$this->printRateReplyDetails($rateReply);
}
}else{
$this->printRateReplyDetails($response -> RateReplyDetails);
}
echo '</table>'. Newline;
printSuccess($client, $response);
}else{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
Here is error exception which i am getting
Fault
Code:SOAP-ENV:Server
String:Fault
Request
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v18"><SOAP-ENV:Body><ns1:RateRequest><ns1:WebAuthenticationDetail><ns1:UserCredential><ns1:Key>AndJurrJfCvvWZWn</ns1:Key><ns1:Password>Rps8Pl4jF9zGp5wiEpDRhKiHo</ns1:Password></ns1:UserCredential></ns1:WebAuthenticationDetail><ns1:ClientDetail><ns1:AccountNumber>631140688</ns1:AccountNumber><ns1:MeterNumber>107714405</ns1:MeterNumber></ns1:ClientDetail><ns1:TransactionDetail><ns1:CustomerTransactionId> *** Rate Available Services Request using PHP ***</ns1:CustomerTransactionId></ns1:TransactionDetail><ns1:Version><ns1:ServiceId>crs</ns1:ServiceId><ns1:Major>18</ns1:Major><ns1:Intermediate>0</ns1:Intermediate><ns1:Minor>1</ns1:Minor></ns1:Version><ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit><ns1:RequestedShipment><ns1:ShipTimestamp>2016-03-30T18:35:41+05:30</ns1:ShipTimestamp><ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType><ns1:ServiceType>INTERNATIONAL_PRIORITY</ns1:ServiceType><ns1:Shipper><ns1:Address><ns1:StreetLines>SUITE 5A-1204</ns1:StreetLines><ns1:StreetLines>799 E DRAGRAM</ns1:StreetLines><ns1:City>TUCSON</ns1:City><ns1:StateOrProvinceCode>AZ</ns1:StateOrProvinceCode><ns1:PostalCode>94040</ns1:PostalCode><ns1:CountryCode>US</ns1:CountryCode></ns1:Address></ns1:Shipper><ns1:Recipient><ns1:Address><ns1:StreetLines>795 E</ns1:StreetLines><ns1:StreetLines>DRAGRAM</ns1:StreetLines><ns1:City>TUCSON</ns1:City><ns1:StateOrProvinceCode>AZ</ns1:StateOrProvinceCode><ns1:PostalCode>94040</ns1:PostalCode><ns1:CountryCode>US</ns1:CountryCode><ns1:Residential>false</ns1:Residential></ns1:Address></ns1:Recipient><ns1:ShippingChargesPayment><ns1:PaymentType>SENDER</ns1:PaymentType><ns1:Payor><ns1:ResponsibleParty><ns1:AccountNumber>631140688</ns1:AccountNumber><ns1:Address><ns1:CountryCode>KWI</ns1:CountryCode></ns1:Address></ns1:ResponsibleParty></ns1:Payor></ns1:ShippingChargesPayment><ns1:PackageCount>1</ns1:PackageCount><ns1:RequestedPackageLineItems><ns1:SequenceNumber>1</ns1:SequenceNumber>
<ns1:GroupPackageCount>1</ns1:GroupPackageCount><ns1:Weight>
<ns1:Value>20</ns1:Value></ns1:Weight><ns1:Dimensions>
<ns1:Length>8</ns1:Length><ns1:Width>10</ns1:Width>
<ns1:Height>10</ns1:Height></ns1:Dimensions></ns1:RequestedPackageLineItems>
</ns1:RequestedShipment></ns1:RateRequest></SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Since you have trace on, you should look at the actual request/response data. When I took your raw POST data above (in which you shouldn't have posted your account/key info) I get back a schema validation error. Syntax looks correct but the country code for payor is KWI but should be US. I'd suggest you add some code to log the request and responses...
$soap_response_hdr = $client->__getLastResponseHeaders() ;
$soap_response = $client->__getLastResponse() ;
$soap_request_hdr = $client->__getLastRequestHeaders() ;
$soap_request = $client->__getLastRequest() ;

Prestashop error "invalid security token"

im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.

Fedex Shipping Labels API not sending Address 2

THE SOAP REQUEST AS SENT
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/ship/v12">
<SOAP-ENV:Body>
<ns1:ProcessShipmentRequest>
<ns1:WebAuthenticationDetail>
<ns1:UserCredential>
<ns1:Key>kQyj3MtQGLJ3ZYWG</ns1:Key>
<ns1:Password>66ywMwyasljK5uRkaNENRZCZW</ns1:Password>
</ns1:UserCredential>
</ns1:WebAuthenticationDetail>
<ns1:ClientDetail>
<ns1:AccountNumber>510087682</ns1:AccountNumber>
<ns1:MeterNumber>100154483</ns1:MeterNumber>
</ns1:ClientDetail>
<ns1:TransactionDetail>
<ns1:CustomerTransactionId>*** Express Domestic Shipping Request v12 using PHP ***</ns1:CustomerTransactionId>
</ns1:TransactionDetail>
<ns1:Version>
<ns1:ServiceId>ship</ns1:ServiceId>
<ns1:Major>12</ns1:Major>
<ns1:Intermediate>1</ns1:Intermediate>
<ns1:Minor>0</ns1:Minor>
</ns1:Version>
<ns1:RequestedShipment>
<ns1:ShipTimestamp>2013-03-25T14:33:08+00:00</ns1:ShipTimestamp>
<ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType>
<ns1:ServiceType>FEDEX_GROUND</ns1:ServiceType>
<ns1:PackagingType>YOUR_PACKAGING</ns1:PackagingType>
<ns1:TotalWeight>
<ns1:Units>LB</ns1:Units>
<ns1:Value>17.22</ns1:Value>
</ns1:TotalWeight>
<ns1:Shipper>
<ns1:Contact>
<ns1:PersonName>Shipping Department</ns1:PersonName>
<ns1:CompanyName>Big Dog Treestands</ns1:CompanyName>
<ns1:PhoneNumber>3092636800</ns1:PhoneNumber>
</ns1:Contact>
<ns1:Address>
<ns1:StreetLines>120 E. Detroit Parkway</ns1:StreetLines>
<ns1:City>Morton</ns1:City>
<ns1:StateOrProvinceCode>IL</ns1:StateOrProvinceCode>
<ns1:PostalCode>61550</ns1:PostalCode>
<ns1:CountryCode>US</ns1:CountryCode>
</ns1:Address>
</ns1:Shipper>
<ns1:Recipient>
<ns1:Contact>
<ns1:PersonName>David Sinc</ns1:PersonName>
<ns1:CompanyName>TEST COMPANY</ns1:CompanyName>
<ns1:PhoneNumber>3093701229</ns1:PhoneNumber>
</ns1:Contact>
<ns1:Address>
<ns1:StreetLines>1202 Chalet Ln</ns1:StreetLines>
<ns1:StreetLines>HIDDLY- Test Account</ns1:StreetLines>
<ns1:City>PEORIA</ns1:City>
<ns1:StateOrProvinceCode>IL</ns1:StateOrProvinceCode>
<ns1:PostalCode>61614</ns1:PostalCode>
<ns1:CountryCode>US</ns1:CountryCode>
<ns1:Residential>false</ns1:Residential>
</ns1:Address>
</ns1:Recipient>
<ns1:ShippingChargesPayment>
<ns1:PaymentType>SENDER</ns1:PaymentType>
<ns1:Payor>
<ns1:ResponsibleParty>
<ns1:AccountNumber>510087682</ns1:AccountNumber>
<ns1:Contact/>
<ns1:Address>
<ns1:CountryCode>US</ns1:CountryCode>
</ns1:Address>
</ns1:ResponsibleParty>
</ns1:Payor>
</ns1:ShippingChargesPayment>
<ns1:LabelSpecification>
<ns1:LabelFormatType>COMMON2D</ns1:LabelFormatType>
<ns1:ImageType>PDF</ns1:ImageType>
<ns1:LabelStockType>PAPER_8.5X11_TOP_HALF_LABEL</ns1:LabelStockType>
</ns1:LabelSpecification>
<ns1:RateRequestTypes>ACCOUNT</ns1:RateRequestTypes>
<ns1:PackageCount>1</ns1:PackageCount>
<ns1:RequestedPackageLineItems>
<ns1:SequenceNumber>1</ns1:SequenceNumber>
<ns1:GroupPackageCount>1</ns1:GroupPackageCount>
<ns1:Weight>
<ns1:Units>LB</ns1:Units>
<ns1:Value>17.22</ns1:Value>
</ns1:Weight>
</ns1:RequestedPackageLineItems>
</ns1:RequestedShipment>
</ns1:ProcessShipmentRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Fedex APpplication Code
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 12.0.0
require_once('library/fedex-common.php5');
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "http://bigdog.webdesign309.com/wp-content/themes/bigdogtreestands-new/woocommerce/emails/ShipWebServiceClient/wsdl/ShipService_v12.wsdl";
$uploads = wp_upload_dir();
define('SHIP_LABEL', $uploads['basedir'].'/shippinglabels/shipexpresslabel'.str_replace('#','',$order->get_order_number()).'.pdf'); // PNG label file. Change to file-extension .pdf for creating a PDF label (e.g. shiplabel.pdf)
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' => array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Express Domestic Shipping Request v12 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'ship',
'Major' => '12',
'Intermediate' => '1',
'Minor' => '0'
);
$ships = $order->get_shipping_method();
$shippingType = "FEDEX_GROUND";
if($ships == "Fedex Ground"){
$shippingType = "FEDEX_GROUND";
}
else if( $ships == "Fedex 2 Day"){
$shippingType = "FEDEX_2_DAY";
}
else if($ships == "Fedex Standard Overnight"){
$shippingType = "STANDARD_OVERNIGHT";
}
else if($ships == "Fedex Home Delivery"){
$shippingType = "GROUND_HOME_DELIVERY";
}
function totalOrderWeight($orders) {
$totalWeight = 0;
$items = $orders->get_items();
foreach($items as $item) {
$product = get_product( $item['product_id'] );
$quantity = intval( $item['qty'] );
$totalWeight += $product->get_weight() * $quantity;
}
return $totalWeight;
}
$request['RequestedShipment'] = array(
'ShipTimestamp' => date('c'),
'DropoffType' => 'REGULAR_PICKUP', // valid values REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER and STATION
'ServiceType' => $shippingType, // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
'PackagingType' => 'YOUR_PACKAGING', // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
'TotalWeight' => array('Value' => totalOrderWeight($order), 'Units' => 'LB'), // valid values LB and KG
'Shipper' => addShipper(),
'Recipient' => addRecipient($order),
'ShippingChargesPayment' => addShippingChargesPayment(),
'LabelSpecification' => addLabelSpecification(),
'RateRequestTypes' => array('ACCOUNT'), // valid values ACCOUNT and LIST
'PackageCount' => 1,
'RequestedPackageLineItems' => array(
'0' => addPackageLineItem1(totalOrderWeight($order))
)
);
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client->processShipment($request); // FedEx web service invocation
if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR')
{
printSuccess($client, $response);
$label =
// Create PNG or PDF label
// Set LabelSpecification.ImageType to 'PDF' or 'PNG for generating a PDF or a PNG label
$fp = fopen(SHIP_LABEL, 'wb');
fwrite($fp, $response->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image); //Create PNG or PDF file
fclose($fp);
// echo 'Click Here to Download Shipping Label was generated.';
}
else
{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Shipping Department',
'CompanyName' => 'Big Dog Treestands',
'PhoneNumber' => '3092636800'),
'Address' => array(
'StreetLines' => array('120 E. Detroit Parkway'),
'City' => 'Morton',
'StateOrProvinceCode' => 'IL',
'PostalCode' => '61550',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient($orders){
$residential = get_post_meta($orders->get_order_number(), '_residential-indicator');
/* echo 'Shipping Address 2:'.$orders->shipping_address_2;
echo 'Shipping Address 1:'.$orders->shipping_address_1; */
if($orders->shipping_address_2){
$addressArray = array($orders->shipping_address_1, $orders->shipping_address_2);
/* echo 'Shipping Address 2'; */
/* $addressArray =array('StreetLines' => array('Address Line 1' => $orders->shipping_address_1, 'Address Line 2' => $orders->shipping_address_2)); */
}
else{
$addressArray = array($orders->shipping_address_1);
/* echo 'Shipping Address 1'; */
}
$joy = false;
if($residential == 1){
$joy = true;
}
else{
$joy = false;
}
$recipient = array(
'Contact' => array(
'PersonName' => $orders->billing_first_name . ' ' . $orders->billing_last_name,
'CompanyName' => $orders->shipping_company,
'PhoneNumber' => $orders->billing_phone),
/* 'Address' => array(
'StreetLines' => array($orders->shipping_address_1, $orders->shipping_address_2),
'City' => $orders->shipping_city,
'StateOrProvinceCode' => $orders->shipping_state,
'PostalCode' => $orders->shipping_postcode,
'CountryCode' => 'US',
'Residential' => $joy) */
'Address' => array(
'StreetLines'=>array($orders->shipping_address_1, $orders->shipping_address_2),
//array(utf8_encode($orders->shipping_address_1), utf8_encode($orders->shipping_address_2)),
'City' => $orders->shipping_city,
'StateOrProvinceCode' => $orders->shipping_state,
'PostalCode' => $orders->shipping_postcode,
'CountryCode' => 'US',
'Residential' => $joy)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array('PaymentType' => 'SENDER',
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'Contact' => null,
'Address' => array('CountryCode' => 'US'))));
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_8.5X11_TOP_HALF_LABEL');
return $labelSpecification;
}
function addPackageLineItem1($weight){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => $weight,
'Units' => 'LB')
);
return $packageLineItem;
}
?>
It returns this http://bigdog.webdesign309.com/assets/shippinglabels/shipexpresslabel1303.pdf
I have tried everything even calling fedex and they say that they provide no support for this issue as the code is a convenience rather than a service. If anyone can shed some light on this most puzzling issue as to why the second address field never shows up that would be great.
Any thoughts on this one?
In case anyone else comes across this problem, note that FedEx's test labels from their staging environment do not appear to ever include the second address line.
All of my test labels did NOT have a second address line, but as soon as I switched to the production server, the labels had the second line.
It should have multiple address lines as your XML looks valid. FedEx support should be able to provide assistance based on the SOAP request/response, but will not provide assistance with your PHP coding.
according to the Ship Service Docs, you only have two address lines, I solved like this:
'Address' => array(
'StreetLines' => array($array_recipient["address_1"],$array_recipient["address_2"]),
'City' => $array_recipient["City"],
'StateOrProvinceCode' => $array_recipient["StateOrProvinceCode"],
'PostalCode' => $array_recipient["PostalCode"],
'CountryCode' => 'MX',
'Residential' => true
)
in case you need more "space" you can use CUSTOMER_REFERENCE (rigth after dimensions):
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => $dimension_array["weight"],
'Units' => 'KG'
),
'Dimensions' => array(
'Length' => $dimension_array["length"],
'Width' => $dimension_array["width"],
'Height' => $dimension_array["height"],
'Units' => 'CM'
),
'CustomerReferences' => array(
'CustomerReferenceType' => 'CUSTOMER_REFERENCE',
'Value' => $dimension_array["more_references"]
),
If you make the request in Test Enviroment, the second address will not show, but after to production, the second address will shown.
Hope this help you.

Categories