When I want to update the endpoint, I got the error:
ErrorException: Creating default object from empty value in file /var/www/html/app/Http/Controllers/CasesController.php on line 208
below the code:
public function accept(Request $request)
{
$id_case = $request->id_case;
$case = Cases::find($id_case);
$maxAgent = 0;
switch ($id_case[0]) {
case 'A':
$maxAgent = 1;
break;
case 'B':
$maxAgent = 3;
break;
case 'C':
$maxAgent = 5;
break;
default:
break;
}
// check the agent receive the case
$accepted_agent = AgentInCase::where('id_case', $id_case)->where('id_agent', auth()->user()->id_user)->get();
if ($accepted_agent) {
$message = 'Agent has accepted the request';
return $this->sendResponse($accepted_agent, $message, 200);
}
// check the max agent in case
$agent_in_case = AgentInCase::where('id_case', $id_case)->get();
if (count($agent_in_case) < $maxAgent) {
$agent = Agent::find(auth()->user()->id_user);
$agent->is_in_case = true;
$agent->save();
$agent = AgentInCase::create([
'id_case' => $id_case,
'id_agent' => auth()->user()->id_user
]);
//send FCM to customer that request confirmed
$message = [
'title' => 'accept_agent',
'body' => 'New Agent Come To Help ',
'payment' => 'Rp 15.000'
];
$this->sendNotificationFirebase('customer', $case->id_customer, $message, $agent);
$message = 'Successfully accepted request';
return $this->sendResponse($case, $message, 200);
}
$message = 'Failed to accept request';
$errors = 'Case has been handled by another agent';
return $this->sendError($message, 400, $errors);
}
The error in line:
$agent->is_in_case = true;
I'm trying to solve this error and I just get one reference:
Creating default object from empty value in PHP?.
But, I can't yet to solving this.
Could you help me to solve this? What I must do?
For every request that you want to select by an ID, you should catch and error if requested id is not exists .
In my opinion clean way to do that in laravel is using validation .
For example if you want to find a user by its ID validation should be something like :
'ID' => 'exists:users,ID',
First Id is in your request and second one is your column name in database.
Related
I have built a PHP form, but want an email to be sent to whatever country the user chooses on a dropdown.
E.g. If they choose UK on dropdown, send an email to our UK account. If they choose US, send to our US account etc...
The entire form is working perfectly at the moment, I just need this little feature to work then it would be perfect. Thank you for looking, its appreciated!
This is my code so far:-
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'A new client has registered their details <noreply#emailaddress.com>';
// an email address that will receive the email with the output of the form
$sendTo = '<scott#emailaddress.com>';
// subject of the email
$subject = 'New Registered Form:';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = [
'firstname' => 'First Name', 'lastname' => 'Last Name', 'company' => 'Company', 'email' => 'Email Address', 'jobrole' => 'Job Role',
'postcode' => 'Postcode', 'country' => 'Country',
];
// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for registering.';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = 'AAAA';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if ( ! empty($_POST))
{
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if ( ! isset($_POST['g-recaptcha-response']))
{
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost);
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ( ! $response->isSuccess())
{
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "This person has registered their details \n=============================\n";
foreach ($_POST as $key => $value)
{
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key]))
{
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = [
'Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
];
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = ['type' => 'success', 'message' => $okMessage];
}
}
catch (\Exception $e)
{
$responseArray = ['type' => 'danger', 'message' => $e->getMessage()];
}
if ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else
{
echo $responseArray['message'];
}
?>
Thank you very much in advance!!
Scott Geere
Personally I would do something like this:
switch ($_POST['country']):
case 'UK':
$sendTo = '<UK#emailaddress.com>';
break;
case 'US';
$sendTo = '<US#emailaddress.com>';
break;
default:
$sendTo = '<scott#emailaddress.com>';
endswitch;
Which means you could change:
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
$sendTo = '<scott#emailaddress.com>';
To:
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
switch ($_POST['send_to']):
case 'UK':
$sendTo = '<UK#emailaddress.com>';
break;
case 'US';
$sendTo = '<US#emailaddress.com>';
break;
default:
$sendTo = '<scott#emailaddress.com>';
endswitch;
Please do not forget: never trust the user. So do not just do stuff on $_POST data, make sure you validate the given input before you use it.
Another side note:
Instead of using this raw code in yours, you could make it a function (so you can reuse it somewhere else as well).
For example:
function getSendToEmail($country)
{
switch ($country):
case 'UK':
return '<UK#emailaddress.com>';
break;
case 'US';
return '<US#emailaddress.com>';
break;
default:
return '<scott#emailaddress.com>';
endswitch;
}
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
$sendTo = $this->getSendToEmail($_POST['country']);
Documentation:
http://php.net/manual/en/control-structures.switch.php // Switch
http://php.net/manual/en/functions.user-defined.php // Functions
http://php.net/manual/en/filter.examples.validation.php // Validation
if (isset($_POST['country'])) {
$country = $_POST['country'];
if ($country === 'France') {
$sendTo = 'france#emailadress.com';
} elseif ($country === 'England') {
$sendTo = 'england#emailadress.com';
}
}
You can put it before the mail function.
You can also use an array like that:
$emailList = [
'France' => 'france#emailadress.com',
'England' => 'england#emailadress.com'
];
if (isset($_POST['country'])) {
// Get email from the key
$sendTo = $emailList[$_POST['country']];
}
I have this contact form but I am confused as to how I can insert PHPMailer (without Composer) into the script?
I am not sure how to properly add it so that way, once it processes and sends the form it alerts the user. I do not have the ability to utilize composer, so I would need to upload PHPMailer into the directory.
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
$data = http_build_query([
"secret" => $secret,
"response" => $clientResponse,
"remoteip" => $clientIp,
]);
$options = [
"http" => [
"header" =>
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($data)."\r\n",
"method" => "POST",
"content" => $data,
],
];
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify",
false,
stream_context_create($options)
);
if($response === false)
{
return false;
}
else if(($arr = json_decode($response, true)) === null)
{
return false;
}
else
{
return $arr["success"];
}
}
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['captcha'] = 'Captcha is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Without autoloader:
<?php
//You shall use the following exact namespaces no
//matter in whathever directory you upload your
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Now include the following following files based
//on the correct file path. Third file is required only if you want to enable SMTP.
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
?>
You shall add the following class to initiate the mailer after checking if your query or condition is executed.
<?php
$mail = new PHPMailer(true);
?>
You shall find a nice and simple example at https://github.com/PHPMailer/PHPMailer/blob/master/README.md to start with.
I hope it helps.
I have tool using the REST API SDK for PHP that captures payments for multiple companies in PayPal. If I Post one or more transactions to capture from different companies. The transactions are marked 'Captured' within PayPal everything is great. The issue is trying to capture multiple transactions from the same company within the same Post. What happens is only the first transaction in the array gets marked as 'Captured' in PayPal but any other transaction in that same array does not. Seemingly they get ignored.
The PayPal logs with the application do not show any errors. Here is the method that grabs the POST transaction Ids:
if(isset($_POST['toCapture']) && ! empty($_POST['toCapture'])){
// Array of transaction ids to capture
$idsToCapture = $_POST['toCapture'];
for($i = 0; $i < $arrayCount; $i++) {
// Transaction id for current iteration in the loop
$theId = $idsToCapture[$i]; //transactionId
// Function call to get information for transaction id being processed in current iteration of loop
$infoToCapture = getInfoToCapture($theId);
$theCompany = $infoToCapture['Company'];
$theAmt = number_format($infoToCapture['DocumentAmount'], 2); // DocAmt formatted to two decimal places
$ohId = $infoToCapture['OrderHeaderId'];
try {
// Setting $theId to $authId
$authId = $theId;
// Maing sure the ids to be processed do not have an acknoledgement from PayPal
$checkAckNull = isAckNull($authId);
// Setting the amount we want to capture
$amt = new Amount();
$amt->setCurrency("USD")
->setTotal($theAmt);
// If there is no acknowledgment from PayPal, process the capture
if($checkAckNull == NULL){
### Capture
$capture = new Capture();
$capture->setId($authId)
->setAmount($amt);
// it is the $apiContexts that are different for each company
switch ($theCompany) {
case "BLL":
allTheImportantStuff( $apiContextBLL, $authId, $ohId, $capture, $theCompany );
break;
case "LOT":
allTheImportantStuff( $apiContextLOT, $authId, $ohId, $capture, $theCompany );
break;
case "SNA":
allTheImportantStuff( $apiContextSNA, $authId, $ohId, $capture, $theCompany );
break;
case "FAB":
allTheImportantStuff( $apiContextFAB, $authId, $ohId, $capture, $theCompany );
break;
case "STS":
allTheImportantStuff( $apiContextSTS, $authId, $ohId, $capture, $theCompany );
break;
case "MIA":
allTheImportantStuff( $apiContextMIA, $authId, $ohId, $capture, $theCompany );
break;
}
} // end if
else {
}
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
echo '<pre>'; var_dump( $ex->getData() ); echo '</pre>';
$fail = "failure";
insertFail($theCompany, $ohId, $theId, $fail);
} // end try/catch
} // end for loop
}
Here is the allTheImportantStuff method:
function allTheImportantStuff( $apiContext, $authId, $ohId, $capture, $theCompany ){
global $mode;
// Lookup the authorization.
$authorization = Authorization::get($authId, $apiContext);
// Perform a capture
$getCapture = $authorization->capture($capture, $apiContext);
// Get acknowledgment from capture
$ack = $getCapture->getId();
// Get state from capture
$state = $getCapture->getState();
return insertAck($theCompany, $ohId, $ack, $authId, $state);
}
Up until (roughly) a few weeks ago this code worked. I am not using the latest version of the REST API SDK for PHP but trying to avoid updating because other tools are using the SDK as well and work fine. I hope I have explained the issue thoroughly enough. Any thoughts or ideas on what may be going on or how to fix would be greatly appreciated.
I'm trying to authenticate on Bing Ads Api but I'm getting this message:
Authentication failed. Either supplied credentials are invalid or the account is inactive
This is my code:
$UserName = "xxx#hotmail.com";
$Password = "xxx";
$DeveloperToken = "xxx";
$CustomerId = xxx;
$AccountId = xxx;
$wsdl = "https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/V10/CampaignManagementService.svc?singleWsdl";
try
{
$proxy = ClientProxy::ConstructWithAccountAndCustomerId($wsdl, $UserName, $Password, $DeveloperToken, $AccountId, $CustomerId, null);
// Specify one or more campaigns.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Winter Clothing " . $_SERVER['REQUEST_TIME'];
$campaign->Description = "Winter clothing line.";
$campaign->BudgetType = BudgetLimitType::MonthlyBudgetSpendUntilDepleted;
$campaign->MonthlyBudget = 1000.00;
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaign->DaylightSaving = true;
// Used with FinalUrls shown in the ads that we will add below.
$campaign->TrackingUrlTemplate =
"http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";
$campaigns[] = $campaign;
// Add the campaign, ad group, keywords, and ads
$campaignIds = AddCampaigns($proxy, $AccountId, $campaigns);
PrintCampaignIdentifiers($campaignIds);
}
catch (SoapFault $e)
{
// Output the last request/response.
print "\nLast SOAP request/response:\n";
print $proxy->GetWsdl() . "\n";
print $proxy->GetService()->__getLastRequest()."\n";
print $proxy->GetService()->__getLastResponse()."\n";
// Campaign Management service operations can throw AdApiFaultDetail.
if (isset($e->detail->AdApiFaultDetail))
{
// Log this fault.
print "The operation failed with the following faults:\n";
$errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
? $e->detail->AdApiFaultDetail->Errors->AdApiError
: array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
// If the AdApiError array is not null, the following are examples of error codes that may be found.
foreach ($errors as $error)
{
print "AdApiError\n";
printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
switch ($error->Code)
{
case 105: // InvalidCredentials
break;
case 117: // CallRateExceeded
break;
default:
print "Please see MSDN documentation for more details about the error code output above.\n";
break;
}
}
Sorry for the delayed reply. I noticed that you are setting the UserName to ***#hotmail.com. If you are using an email address login i.e. Microsoft account, then you must use OAuth i.e. set the AuthenticationToken header element instead of setting the UserName/Password fields.
// Process the forms
if (($this->getRequest()->isPost())
&& ($this->getRequest()->isXmlHttpRequest())) {
// Initiate response
$status = false;
$msg = '';
$zf = null;
// Error test
$form->getElement('no')->addError('This is the error message');
if ($form->isValid($this->getRequest()->getPost())) {
// Everything is good
$status = true;
} else {
// Get the error messages
$zf = $form->getMessages();
}
// Setup the response
$result = json_encode(array('status' => $status,
'msg' => $msg,
'zf' => $zf));
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout()->disableLayout();
$this->getResponse()->setHeader('Content-Type', 'application/json');
$this->getResponse()->setBody($result);
return;
} else {
// Populate the form
}
As you can see, I've used $form->getElement('no')->addError('This is the error message'); to force error on the form element, but $form->getMessages(); would still return NULL. So, what should I do to force error on the selected form element?
I think you've got the get the ErrorMessages()
$form->getErrorMessages()
I've opened a bug report for this issue: http://framework.zend.com/issues/browse/ZF-11088. I'll update this question if there's any new progress.