These codes throw "Bad Request" error because of parameter. What is the problem of parameter syntax.
try{
$client = new Client();
$response = $client->post("url",
['s' => $s, 'p'=> $p]);
} catch (ClientException $e) {
echo $e->getMessage();
} catch (RequestException $e) {
echo $e->getMessage();
}
You can use Http::post();
use Illuminate\Support\Facades\Http;
$response = Http::post('http://example.com/users',['your data']);
Related
so i was trying to send a mail with a pdf attachment but i get this error No hint path defined for [mail].
here is my buld function syntax
public function build()
{
$pdf = $this->pdf;
return $this->subject("Transaction Request")
->from('finance#vcass.org')
->attachData($pdf, 'transaction.pdf', [
'mime' => 'application/pdf'
])
->markdown('emails.usersingle', ['transaction' => $this->transaction]);
}
and here is my controller code
public function sendtransaction(Request $request)
{
$data = $request->all();
$id = $data['id'];
$transaction = Transaction::find($id);
$pdf = PDF::loadView('emails.usersingle', compact('transaction'));
$pdf = $pdf->output();
try {
Mail::to($data['email'])->send(new MailTransaction($transaction, $pdf));
return redirect()->back()->with('success', 'transaction sent to mail, check your mail');
} catch (\Swift_TransportException $e) {
return redirect()->back()->with('warning', 'Sorry mail couldnt be sent, please try again');
} catch (\Exception $e) {
dd($e);
}
}
please I need help on this fast!
I am using stripe payment gateway in my project. I am trying to display exception errors when a user entered expired card number. but instead of showing me error of exception it shows me laravel error.
Note: it is not working with any kind of exception not only expired card number.
I am using the exception provided by Stripe.
public function recharge(Request $request)
{
$this->validate($request, [
'amount' => 'required',
]);
$amount = $request->input('amount');
\Stripe\Stripe::setApiKey('key_here');
try {
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => $amount * 100,
'currency' => 'usd',
'description' => 'Example charge',
'source' => $token,
]);
$user = User::find(Auth::user()->id);
$user->deposit($amount);
Session::flash('success', 'Your Wallet is recharged!');
return back();
} catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\InvalidRequest $e) {
return "error";
} catch (\Stripe\Error\Authentication $e) {
return "error";
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
return "error";
} catch (\Stripe\Error\Base $e) {
return "error";
} catch (Exception $e) {
return "error";
}
}
I want to display the error defined by me in the catch block.
Stripe API Document on errors has pretty much everything we can get. here is the Code block you can put while using stripe library.
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
You are not catching the Stripe\Exception\CardException exception. You are probably not actually catching Exception either, unless you have aliased Exception at the top of your file.
Add use Exception; before the class declaration at the top or adjust Exception in the catch to \Exception.
Looks like the newer version of stripe-php library throws Exceptions from Stripe\Exception and no longer has a namespace Stripe\Error FYI.
Stripe API Reference - Handling Errors
The issue got fixed by including use Exception;
I am able to parse HTMl that uses blade template variables through the following code:
$generated = Blade::compileString($string);
ob_start();
try
{
eval($generated);
}
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
And it works fine as long as i don't use blade variables within. Which on being parsed give me undefined variable error. How can i make sure that blade variables are available in my custom parsing method?
This works for me with the latest version of Laravel 5.7. Notice how I include the __env var so that functions like #include, #foreach, etc can work.
public static function renderBlade($string, $data = null)
{
if (!$data) {
$data = [];
}
$data['__env'] = app(\Illuminate\View\Factory::class);
$php = Blade::compileString($string);
$obLevel = ob_get_level();
ob_start();
extract($data, EXTR_SKIP);
try {
eval('?' . '>' . $php);
} catch (Exception $e) {
while (ob_get_level() > $obLevel) {
ob_end_clean();
}
throw $e;
} catch (Throwable $e) {
while (ob_get_level() > $obLevel) {
ob_end_clean();
}
throw new FatalThrowableError($e);
}
return ob_get_clean();
}
Turns out I was not passing the arguments array to the method that parses the Blade structure. My assumption was that the Mail::send method takes care of making variables available which it takes in as a second parameter. I also had to extract($args, EXTR_SKIP).
$generated = Blade::compileString($string);
ob_start(); extract($args, EXTR_SKIP)
try
{
eval($generated);
}
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
I have created custom module and I am working on record deletion but its not working. Code which I am using is
$keyId=$params = $this->getRequest()->getParams('id');
$model = Mage::getModel('groupprice/groupprice');
try {
$model->setId($keyId)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
Is anything wrong ?
This code is working in a simple request but not working with ajax request .
You should change code and use getPost
$keyId=$params = $this->getRequest()->getPost('id');
Hope this wil help.
Try this code :
$keyId=$params = $this->getRequest()->getParam('id');
$model = Mage::getModel('groupprice/groupprice');
try
{
$model->setId($keyId)->delete();
echo "Data deleted successfully.";
}
catch (Exception $e)
{
echo $e->getMessage();
}
How to send email in magento writing an action in index controller?
my index controller;
public function postAction()
{
$post = $this->getRequest()->getPost();
if(!$post) exit;
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Please enter a valid email address. For example johndoe#domain.com.').'</div>';
exit;
}
$storeId = Mage::app()->getStore()->getStoreId();
$emailId = Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE);
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
->setReplyTo($post['email'])
->sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
if (!$mailTemplate->getSentSuccess()) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').'</div>';
exit;
}
$translate->setTranslateInline(true);
echo '<div class="success-msg">'.Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.').'</div>';
}
catch (Exception $e) {
$translate->setTranslateInline(true);
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').$e.'</div>';
exit;
}
}
is there any wrong..
please help me to out of this..
Thanks in advance..
Here's another way, if you don't need templates.
Call from a controller.
<?php
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('John Customer');
$mail->setToEmail('customer#email.com');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('yourstore#url.com');
$mail->setFromName("Your Name");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
It looks like there are a few problems with the way you are calling sendTransactional(). First off, $templateId is not defined, it looks like you've actually stored the template id in $emailId. Also, $sender, $email, and $name are undefined. You can try something like this:
->sendTransactional($emailId, 'general', $post['email'], "Need a send to name here")
This is only going to work if you are getting a valid template id back from your call to getStoreConfig(). You'll also need to set the last name param correctly.
There could be other issues, but that's what I noticed with a quick glance anyway.
Finally i created a function for sending mail by using zend
public function sendMail()
{
$post = $this->getRequest()->getPost();
if ($post){
$random=rand(1234,2343);
$to_email = $this->getRequest()->getParam("email");
$to_name = 'Hello User';
$subject = ' Test Mail- CS';
$Body="Test Mail Code : ";
$sender_email = "sender#sender.com";
$sender_name = "sender name";
$mail = new Zend_Mail(); //class for mail
$mail->setBodyHtml($Body); //for sending message containing html code
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname); //can set cc
//$mail->addBCc($bcc, $bccname); //can set bcc
$mail->setSubject($subject);
$msg ='';
try {
if($mail->send())
{
$msg = true;
}
}
catch(Exception $ex) {
$msg = false;
//die("Error sending mail to $to,$error_msg");
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($msg));
}
}