I am using codeigniter-restserver by Phil Sturgeon,
https://github.com/chriskacerguis/codeigniter-restserver
here is an problem I encountered:
When I do PUT request, everything works, but when I do POST, I got
"500 Internal Server Error"
<div id="container">
<h1>An Error Was Encountered</h1>
<p>The action you have requested is not allowed.</p>
</div>
my code is the following:
function test_post()
{
$this->response('ok', 200); // 200 being the HTTP response code
}
function test_get()
{
$this->response('ok', 200); // 200 being the HTTP response code
}
the working GET handelling can be found in the following URL
https://manage.pineconetassel.com/index.php/api/example/test/
NOTE that I allowed https only.
I used hurl.it to test the POST method, and it does not work.
here is the rest.php config:
$config['force_https'] = TRUE;
$config['rest_default_format'] = 'json';
$config['rest_status_field_name'] = 'status';
$config['rest_message_field_name'] = 'error';
$config['enable_emulate_request'] = TRUE;
$config['rest_realm'] = 'REST API';
$config['rest_auth'] = false;
$config['auth_source'] = 'ldap';
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
$config['rest_valid_logins'] = array('admin' => '1234');
$config['rest_ip_whitelist_enabled'] = false;
$config['rest_ip_whitelist'] = '';
$config['rest_ip_blacklist_enabled'] = false;
$config['rest_ip_blacklist'] = '';
$config['rest_database_group'] = 'default';
$config['rest_keys_table'] = 'keys';
$config['rest_enable_keys'] = FALSE;
$config['rest_key_column'] = 'key';
$config['rest_key_length'] = 40;
$config['rest_key_name'] = 'X-API-KEY';
$config['rest_logs_table'] = 'logs';
$config['rest_enable_logging'] = FALSE;
$config['rest_access_table'] = 'access';
$config['rest_enable_access'] = FALSE;
$config['rest_logs_json_params'] = FALSE;
$config['rest_limits_table'] = 'limits';
$config['rest_enable_limits'] = FALSE;
$config['rest_ignore_http_accept'] = FALSE;
$config['rest_ajax_only'] = FALSE;
Did I do something wrong or use a wrong way to test the POST or I need to configure something?
set $config['csrf_protection'] = FALSE; in config/config.php
Note it is not uder config/rest.php
The accepted answer is right.
But if you don't want to disable $config['csrf_protection'] in case you need it for web form, you need to exclude the REST API URIs, for example, your REST url starts with /api/, simply set
$config['csrf_exclude_uris'] = array(
'api/[a-z0-9/_-]+'
);
It is also under config/config.php. I use regular expression to make it simple.
Related
I am trying to implement google reCAPTCHA. The issue is even when ($Return->success == true && $Return->score >= 0.5) is equal to true, when i should be getting $isOK = true, I get $isOK = false.
I tried a lot, but I am still getting this value set to false. Is there something I am doing wrong over here?
$captchaVerified = false;
if(isset($_POST['tokenVal'])){
function getCaptcha($tokenV,$secretKey){
$Response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".urlencode($secretKey)."&response=".urlencode($tokenV));
$Return = json_decode($Response);
/* global $captchaVerified;*/
if ($Return->success == true && $Return->score >= 0.5) {
$captchaVerified = true;
} else {
$captchaVerified = false;
}
return $captchaVerified;
}
$isOK = getCaptcha($_POST['tokenVal'],$secretKey);
}
The given Response code is performing a GET request to the api server.
The api server is expecting a POST request.
$Response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".urlencode($secretKey)."&response=".urlencode($tokenV));
To make POST request to the server you can follow these steps .
The overall reference has been taken from verify recaptcha
my RESTapi is outputting following json string
{"chat":[{"id":100,"chat_id":38,"created_at":"2016-09-07 08:48:17","updated_at":"2016-09-07 08:48:17","messageContent":"Hi there","sender":"client"},{"id":101,"chat_id":38,"created_at":"2016-09-07 08:48:29","updated_at":"2016-09-07 08:48:29","messageContent":"hello sir","sender":"admin"},{"id":102,"chat_id":38,"created_at":"2016-09-07 09:14:24","updated_at":"2016-09-07 09:14:24","messageContent":"test","sender":"client"},{"id":103,"chat_id":38,"created_at":"2016-09-07 09:16:06","updated_at":"2016-09-07 09:16:06","messageContent":"test","sender":"client"}],"currentChatId":38,"senderName":"Client name"}
Notice the sender column. These are all coming from db. Now I am writing an algorithm which checks this and finds the sender name to the view instead of just sender type.
I am having problem regarding this..any suggestion?
Here is the controller function
public function getAllChat(Request $request)
{
// $chatList = chatMessage::where();
$clientId = $request->session()->get('userId');
//current chat id7
$currentChatId = $request->session()->get('currentChatId');
//find who sent it admin/client
$chatMessageList = chatMessage::where('chat_id',$currentChatId)->get();
//sender
foreach($chatMessageList as $cht)
{
//find out sender
$sender = $cht->sender;
if($sender=="client")
{
$chtP = chatParticipants::find($currentChatId)->first();
$clientId = $chtP->client_id;
//find client name
$client = Client::find($clientId);
$ch->sender = $client->name;
}
elseif($sender=="admin")
{
$chtP = chatParticipants::find($currentChatId)->first();
$adminId = $chtP->admin_id;
//find client name
$admin = Admin::find($clientId);
$name = $admin->name;
$ch->sender = $admin->name;
}
}
return response()->json([
"chat"=> $chatMessageList,
"currentChatId" => $currentChatId,
"senderName"=>$name
]);
}
Error : Creating default object from empty value empty value
You don't have $ch variable defined anywhere - I guess you wanted to use $cht variable instead.
Replace
$ch->sender = $client->name;
with
$cht->sender = $client->name;
and
$ch->sender = $admin->name;
with
$cht->sender = $admin->name;
It was a typo.
$cht->sender=$name;
instead of
$ch->sender=$name;
In magento as we use the rest url to access the data, as http://localhost/magento/api/rest/products it returns in xml format instead of that I need JSON.
I have tried below code, but no use
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($jsonData);
in the folder \magento\app\code\core\Mage\Api\Controller\Action.php
vinox, you should override the default file Request.php. copy \app\code\core\Mage\Api2\Model\Request.php to your local directory and add the following code just before end of the getAcceptTypes() Method.
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
in other way your getAcceptTypes() method should look like this.
public function getAcceptTypes(){
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
return array_keys($orderedTypes);
}
I guess your $jsonData is not actually JSON. Try using a json helper
$jsonData = Mage::helper('core')->jsonEncode($data)
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.
Hi we have a CRM System that needs to change SMTP server once updated by the admin.
We have a table that returns a set of data that contains the SMTP Settings that has a status of 1 needed. The problem is it still relays to the localhost smtp even i've sent the SMTP settings to the htmlMimeMail.php (class) Here is my code:
function sendEmail($txtFrom, $subject, $to, $cc = NULL, $bcc = NULL, $strHTML, $txtModel='')
{
$sql = "SELECT * FROM smtp_server WHERE status='1'";
$rstemp = $this->cn2->Execute($sql);
while(!$rstemp->EOF)
{
$SMTPid = $rstemp->fields['id'];
$SMTPServer = $rstemp->fields['server'];
$SMTPPort = $rstemp->fields['port'];
$SMTPusername=$rstemp->fields['user'];
$SMTPpass=$rstemp->fields['pass'];
$SMTPauth = $rstemp->fields['auth'];
$rstemp->MoveNext();
}
$rstemp->Close();
$fromEmail = $txtFrom;
$from = $fromEmail;
$mail = new htmlMimeMail();
$mail->setTextCharset('utf-8');
$mail->setHtmlCharset('utf-8');
$mail->setHeadCharset('utf-8');
$mail->setSMTPParams($SMTPServer, $SMTPPort,$SMTPid,base64_encode($SMTPusername),base64_encode($SMTPpass),$SMTPServer);
$mail->setReturnPath($fromEmail);
$mail->setFrom($from);
$mail->setSubject($subject);
$mail->setHTML($strHTML);
if(trim($txtModel) != '')
{
$file = strtoupper($txtModel).".pdf";
if(file_exists($this->dir.$file))
{
$attachment = $mail->getFile($this->dir.$file);
$mail->addAttachment($attachment, $file, "application/pdf");
}
}
if (!is_null($cc) && $cc != '')
{
//$arrEmail = explode(",", $cc);
$mail->setCc($cc);
//unset($arrEmail);
}
$mail->setBcc($bcc.', sample#email.com');
$arrEmail = explode(",", $to);
ini_set("SMTP",$SMTPServer);
$result = $mail->send($arrEmail);
return $result;
}
Am i missing something in my code?
I also added ini_set
Here is the function that receives the parameters.
function setSMTPParams($host = null, $port = null, $auth = null, $user = null, $pass = null,$helo = null)
{
if (!is_null($host)) $this->smtp_params['host'] = $host;
if (!is_null($port)) $this->smtp_params['port'] = $port;
if (!is_null($helo)) $this->smtp_params['helo'] = $helo;
if($auth == 4){
if (!is_null($auth)) $this->smtp_params['auth'] = true;
}else{
if (!is_null($auth)) $this->smtp_params['auth'] = false;
}
if (!is_null($user)) $this->smtp_params['user'] = $user;
if (!is_null($pass)) $this->smtp_params['pass'] = $pass;
}
Table definition
________________________________________
id|server |port|user|pass|auth |status
________________________________________
1 |localhost |25 |null|null|false|0
4 |somesmtp#mail.com|25 |user|pass|true |1
________________________________________
From what I can see, you sent the SMTP data to the class, but you neglected to tell the class to use that data:
$result = $mail->send( $a_to, 'smtp' )
Failing to set the second parameter in send results in the class defaulting to 'mail' as send type.
function send($recipients, $type = 'mail')
which then results in your system using the default PHP:
$result = mail($to, $subject, $this->output, implode(CRLF, $headers));
in the:
case 'mail':
of function send()
I'm not clear on why the setup resorted to the SMTP defaults that are set when htmlMimeMail class is launched, there may be some further modification of the code that creates that result, I can't say.
I realize this question is a bit old and the current htmlMimeMail won't run without errors on current PHP anyway, but figured might as well give an answer.