how to use triggers(observers ) in magento for user registration - magento

I need to change customer status after registration.So when a user try to login in my site after admin approval he can access the account and same time i want to use trigger and change the status of that customer and that update given to my Another SAP server database So here I need know what event will be triggered during customer status is changed status..?Please any one answer my question..

Here am using Netzarbeiter_CustomerActivation code
****** Code************
public function customerSaveAfter($observer)
{
/** #var Mage_Customer_Model_Customer $customer */
$customer = $observer->getEvent()->getCustomer();
$helper = Mage::helper('customeractivation');
$storeId = $helper->getCustomerStoreId($customer);
if (! $helper->isModuleActive($storeId)) {
return;
}
$groupId = $customer->getGroupId();
$defaultStatus = $helper->getDefaultActivationStatus($groupId, $storeId);
try {
if (Mage::app()->getStore()->isAdmin()) {
if (!$customer->getOrigData('customer_activated') && $customer->getCustomerActivated()) {
// Send customer email only if it isn't a new account and it isn't activated by default
if (!($customer->getCustomerActivationNewAccount() && $defaultStatus)) {
$helper->sendCustomerNotificationEmail($customer);
*** Added Code Here **********
Getting user details and after admin approval customer details will be send through your API to another server
$CustomerID=$customer->getId();
$FirstName=$customer->getFirstname();
$MiddleName=$customer->getMiddlename();
$LastName=$customer->getLastname();
$Gender=$customer->getGender();
$EmailID=$customer->getEmail();
$WebSite=$customer->getWebsiteId();
$GroupID=$customer->getGroupId();
$DOB=$customer->getDob();
$TaxVat=$customer->getTaxvat();
$date= date("Ymd", strtotime($DOB));
$url = "http://server/WebSAPApi/Service1.asmx/CreateCustomer?CustomerID=$CustomerID&FirstName=$FirstName&MiddleName=$MiddleName&LastName=$LastName&Gender=$Gender&EmailID=$EmailID&WebSite=$WebSite&GroupID=$GroupID&DOB=$date&TaxVat=$TaxVat";
function httpGet($url)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$msg = httpGet($url);
Mage::log($url.$msg, null, 'mylog.log', true);**
****** End of the Added code**********
}
}
} else {
if ($customer->getCustomerActivationNewAccount()) {
// Only notify the admin if the default is deactivated or the "always notify" flag is configured
$alwaysNotify = Mage::getStoreConfig(self::XML_PATH_ALWAYS_NOTIFY_ADMIN, $storeId,$d);
if (!$defaultStatus || $alwaysNotify) {
$helper->sendAdminNotificationEmail($customer);
}
}
$customer->setCustomerActivationNewAccount(false);
}
} catch (Exception $e) {
Mage::throwException($e->getMessage());
}
}

Related

How to generate PayPal order pay link to email

I'm trying to generate PayPal link to email, where user can pay for their order later. I'am using paypal/rest-api-sdk-php. For example using this route:
Route::get('/order/pay/{hash}', 'Frontend\PaymentController#orderPay')->name('order.pay');
My code for payment creation works (see code). When user cancel the payment or payment is unsuccessful, how can I return to the incomplete transaction and try to pay for it again? Should I create new payment everytime user goes to order pay route? Or can I simply identify the incomplete transaction in PayPal and redirect to some(?) PayPal link then?
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectURLs;
use PayPal\Api\Payment;
/*
* #param \App\Order $order
* #return string
*/
public function createPayment($order)
{
$transaction = $this->getTransactionByOrderHash($order->hash);
if ($transaction) {
if ($transaction->is_refunded) {
return 'Paymant has already been refunded';
}
if ($transaction->is_payed) {
return 'Paymant has already been payed';
}
}
$price = $order->to_pay;
$currencyCode = $order->currency->iso_code;
try {
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item
->setName(__('invoice.pfa_title'))
->setCurrency($currencyCode)
->setQuantity(1)
->setSku($order->vs)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details
->setShipping(0)
->setTax(0)
->setSubtotal($price);
$amount = new Amount();
$amount
->setCurrency($currencyCode)
->setTotal($price)
->setDetails($details);
$transaction = new Transaction();
$transaction
->setAmount($amount)
->setItemList($itemList)
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls
->setReturnUrl(route('paypal.success', $order->hash))
->setCancelUrl(route('paypal.cancel'));
$payment = new Payment();
$payment
->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$payment->create($this->apiContext);
$approvalUrl = $this->getApprovalUrl($payment);
if ($approvalUrl) {
session([
'approval_url' => $approvalUrl,
'transaction_id' => $payment->getId(),
]);
return 'payment was successful';
}
} catch (PayPalConnectionException $ex) {
return json_decode($ex->getData());
} catch (Throwable $e) {
return $e->getMessage();
}
return 'payment was unsuccessful';
}
Why use the deprecated v1/payments PayPal-PHP-SDK, instead of the current v2/checkout/orders Checkout-PHP-SDK ?
In any case, yes you can create a new Payment/Order object everytime the customer attempts a checkout. Just set the invoice_id field to your own same but unique invoice/order number for the thing that customer is paying for, so that if the customer does happen to be trying to make a duplicate payment attempt for such a # that has already resulted in a successful transaction on your PayPal account before, it will be blocked by default (according to your PayPal account settings)

Class not found in Laravel 7

I have installed a package for Laravel 7, the package in question is this http://paypal.github.io/PayPal-PHP-SDK/ to manage payments with Paypal.
I created everything, controller, web route, everything.
But the moment I go to the page to test I can't find the class.
Target class [App\Http\Controllers\PaypalController] does not exist.
PaypalController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
// use to process billing agreements
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\Plan;
use PayPal\Api\ShippingAddress;
class PaypalController extends Controller
{
private $apiContext;
private $mode;
private $client_id;
private $secret;
private $plan_id;
// Create a new instance with our paypal credentials
public function __construct()
{
// Detect if we are running in live mode or sandbox
if(config('paypal.settings.mode') == 'live'){
$this->client_id = config('paypal.live_client_id');
$this->secret = config('paypal.live_secret');
$this->plan_id = env('PAYPAL_LIVE_PLAN_ID', '');
} else {
$this->client_id = config('paypal.sandbox_client_id');
$this->secret = config('paypal.sandbox_secret');
$this->plan_id = env('PAYPAL_SANDBOX_PLAN_ID', '');
}
// Set the Paypal API Context/Credentials
$this->apiContext = new ApiContext(new OAuthTokenCredential($this->client_id, $this->secret));
$this->apiContext->setConfig(config('paypal.settings'));
}
public function paypalRedirect(){
// Create new agreement
$agreement = new Agreement();
$agreement->setName('App Name Monthly Subscription Agreement')
->setDescription('Basic Subscription')
->setStartDate(\Carbon\Carbon::now()->addMinutes(5)->toIso8601String());
// Set plan id
$plan = new Plan();
$plan->setId($this->plan_id);
$agreement->setPlan($plan);
// Add payer type
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$agreement->setPayer($payer);
try {
// Create agreement
$agreement = $agreement->create($this->apiContext);
// Extract approval URL to redirect user
$approvalUrl = $agreement->getApprovalLink();
return redirect($approvalUrl);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
}
public function paypalReturn(Request $request){
$token = $request->token;
$agreement = new \PayPal\Api\Agreement();
try {
// Execute agreement
$result = $agreement->execute($token, $this->apiContext);
$user = Auth::user();
$user->role = 'subscriber';
$user->paypal = 1;
if(isset($result->id)){
$user->paypal_agreement_id = $result->id;
}
$user->save();
echo 'New Subscriber Created and Billed';
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo 'You have either cancelled the request or your session has expired';
}
}
}
Routes
Route::get('/subscribe/paypal', 'PaypalController#paypalRedirect');
Route::get('/subscribe/paypal/return', 'PaypalController#paypalReturn');
I can't understand what the problem is! Thank you all
Just run:
composer dump-autoload
to regenerate all classes, see: https://getcomposer.org/doc/03-cli.md
Mention the Laravel 7 route:
Route::post('create_paypal_plan','App\Http\Controllers\PaypallController#create_plan');
just like this.

Check mail is sent successfully or not on Laravel 5

I have a function that can send mail on Laravel5 using this
/**
* Send Mail from Parts Specification Form
*/
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject('Learning Laravel test email');
});
return redirect()->back();
}
/**
* Return message body from Parts Specification Form
* #param object $data
* #return string
*/
private function getMessageBody($data) {
$messageBody = 'dummy dummy dummy dummy';
}
and is sent successfully. But how to check if it was sent or not? Like
if (Mail::sent == 'error') {
echo 'Mail not sent';
} else {
echo 'Mail sent successfully.';
}
I'm just guessing that code.
I'm not entirely sure this would work but you can give it a shot
/**
* Send Mail from Parts Specification Form
*/
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject('Learning Laravel test email');
});
// check for failures
if (Mail::failures()) {
// return response showing failed emails
}
// otherwise everything is okay ...
return redirect()->back();
}
Hope this helps
The Mail::failures() will return an array of failed emails.
Mail::send(...)
if( count(Mail::failures()) > 0 ) {
echo "There was one or more failures. They were: <br />";
foreach(Mail::failures() as $email_address) {
echo " - $email_address <br />";
}
} else {
echo "No errors, all sent successfully!";
}
source : http://laravel.io/forum/08-08-2014-how-to-know-if-e-mail-was-sent
For Laravel 9.11.0
Mail::failures() // is deprecated in laravel 9.11.0
To check if your email was sent successfully one could wrap mail send in a try catch block:
try {
Mail::to($userEmail)->send($welcomeMailable);
} catch (Exception $e) {
//Email sent failed.
}
or since Mail::to($email)->send($mailable) on success returns an instance of : SentMessage one could check:
$welcomeEmailSent = Mail::to($userEmail)->send($welcomeMailable);
if ($welcomeEmailSent instanceof \Illuminate\Mail\SentMessage) {
//email sent success
} else {
//email sent failed
}
You may additionally can make use "Swift_TransportException" to identify any errors.
try{
//code to send the mail
}catch(\Swift_TransportException $transportExp){
//$transportExp->getMessage();
}
You can use the Mail::failures() function for that.
It will have a collection of failed mails if it exists so you can use the code below to check for it.
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) use ($messageBody) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject($messageBody);
});
// check for failed ones
if (Mail::failures()) {
// return failed mails
return new Error(Mail::failures());
}
// else do redirect back to normal
return redirect()->back();
}

send transactional email magento

I'm trying to send a confirmation email when a subscription order is created in magento but is not sending anything.
i know email configuration its fine because when i buy a regular product i do receive the email.
i created a template on System -> Transactional Emails , template with id=12, then on code on class AW_Sarp2_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage i call to send subs email method but it never sends any email
class AW_Sarp2_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
{
public function saveOrder()
{ Mage::log("checkout/onepage",null,"onepageemail.log");
$isQuoteHasSubscriptionProduct = Mage::helper('aw_sarp2/quote')->isQuoteHasSubscriptionProduct(
$this->getQuote()
);
if (!$isQuoteHasSubscriptionProduct) //HERE I ASK IF IS A SUBSCRIBE PRODUCT {Mage::log("checkout/onepage34",null,"onepageemail.log");
return parent::saveOrder();
}
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:Mage::log("checkout/onepage40",null,"onepageemail.log");
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:Mage::log("checkout/onepage43",null,"onepageemail.log");
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:Mage::log("checkout/onepage47",null,"onepageemail.log");
$this->_prepareCustomerQuote();
break;
}
if ($this->getQuote()->getCustomerId()) {Mage::log("checkout/onepage52",null,"onepageemail.log");
$this->getQuote()->getCustomer()->save();
}
#AW_SARP2 override start
$service = Mage::getModel('aw_sarp2/sales_service_profile', $this->getQuote());Mage::log("checkout/onepage56",null,"onepageemail.log");
$service->submitProfile();Mage::log("checkout/onepage57",null,"onepageemail.log");
#AW_SARP2 override end
$this->getQuote()->save();Mage::log("checkout/onepage60",null,"onepageemail.log");
if ($isNewCustomer) {Mage::log("checkout/onepage61",null,"onepageemail.log");
try {
$this->_involveNewCustomer();Mage::log("checkout/onepage63",null,"onepageemail.log");
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
->setLastSuccessQuoteId($this->getQuote()->getId())
->clearHelperData();Mage::log("checkout/onepage71",null,"onepageemail.log");
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();Mage::log("checkout/onepage73",null,"onepageemail.log");
if ($profiles) {Mage::log("checkout/onepage74",null,"onepageemail.log");
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}Mage::log("checkout/onepage78",null,"onepageemail.log");
$this->sendSubscribeEmail2();Mage::log("checkout/onepage79",null,"onepageemail.log");
$this->_checkoutSession->setLastRecurringProfileIds($ids);
Mage::log("checkout/onepage82",null,"onepageemail.log");
}
return $this;
}
public function sendSubscribeEmail2(){ //HERE I TRY TO SEND THE EMAIL
$templateId = 12;
// Set sender information
$senderName = Mage::getStoreConfig('trans_email/ident_support/name');
$senderEmail = Mage::getStoreConfig('trans_email/ident_support/email');
$sender = array('name' => $senderName,
'email' => $senderEmail);
// Set recepient information
$recepientEmail = 'minorandres#gmail.com';
$recepientName = 'Test Test';
// Get Store ID
$storeId = Mage::app()->getStore()->getId();
// Set variables that can be used in email template
$vars = array('customerName' => 'test',
'customerEmail' => 'minorandres#gmail.com');
$translate = Mage::getSingleton('core/translate');Mage::log("checkout/onepage103",null,"onepageemail.log");
// Send Transactional Email
Mage::getModel('core/email_template')
->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId);Mage::log("checkout/onepage106",null,"onepageemail.log");
if (!Mage::getModel('core/email_template')->getSentSuccess()) {
Mage::log("EXCEPTION!!!! =( checkout/onepage107",null,"onepageemail.log");
}
is there something in xml files that i have to do or other place?, please help me
Since i am dealing with subscription products they are handle by a different SMTP provider, on the exception.log i got and error "Mandril cant send email" something like that then i went to Admin Panel and under system>transactional emails has a subtab called mandril i configured that tool and create an account on mandril, then i put the API key indicaded by mandril into system>configuration>mandril(on left side).

Magento User Sub-Accounts for Impersonation

I have a requirement for a Magento project that accounts are hierarchical. That is one account can "own" multiple other accounts. If one account owns another account it is allowed to impersonate that account: create orders, view account information, and view previous orders.
I'm not sure where to begin. If you have any thoughts, could you please point me in the right direction?
One solution would be to set up a Multiple Select attribute and populate it with the user ids of the users allowed to impersonate. You could then create either a separate php file that runs magento and logs in the user based on who they select, or integrate it into the cms.
Here is my custom 'login' code that lets my sso users from my Microsoft Database login to magento.
You call this function and pass it a 'user' you want to login as. Seems to work pretty well, however you will need to modify it to your needs. Don't expect it to work out of the box!
FYI: if you don't pass in all the junk that magento needs about the dispatchevents() then the user will not login properly. I had to reverse engineer this whole dern thing, so don't expect to see it anywhere else besides here and bits and pieces of magento core :)
$userId = 5;
$user = Mage::getModel('customer/customer')->load($userId)->setWebsiteId(1);
$this->LoginToMagento($user, null);
function LoginToMagento($user, $noAddress) {
// Must include this file in order to use the object
include ('/var/www/app/code/core/Mage/Customer/controllers/AccountController.php');
// Configure Magento to think its using the frontend
Mage::getSingleton("core/session", array("name" => "frontend"));
Mage::getConfig()->init();
Mage::getConfig()->loadEventObservers('frontend');
Mage::app()->addEventArea('frontend');
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
// Grab the request and modify it with my emulated controller's information
$request = Mage::app()->getRequest();
$request->setRouteName('customer');
$request->setControllerModule('Mage_Customer');
$request->setRoutingInfo('');
$request->setModuleName('customer');
$request->setControllerName('account');
$request->setModuleKey('module');
$request->setControllerKey('account');
$request->setActionName('loginPost');
$request->setActionKey('action');
// Grab the response
$response = Mage::app()->getResponse();
// Feed the request and response into a new accountcontroller object
$accountControl = new Mage_Customer_AccountController($request, $response);
// Dispatch events related to the controller actions for predispatch
Mage::dispatchEvent('controller_action_predispatch', array('controller_action' => $accountControl));
Mage::dispatchEvent('controller_action_predispatch_customer', array('controller_action' => $accountControl));
Mage::dispatchEvent('controller_action_predispatch_customer_account_loginPost', array('controller_action' => $accountControl));
// Grab an instance of the customer session model
$session = Mage::getSingleton('customer/session');
try{
// Attempt to login the user
$session->setCustomerAsLoggedIn($user);
$session->renewSession();
} catch (Mage_Core_Exception $e) {
// Lets hope to never get here
$message = $e->getMessage();
error_log($message);
Mage::getSingleton('core/session')->addError($message);
}
// Perform the postdispatch events for 'after emulation of the controller'
Mage::dispatchEvent('controller_action_postdispatch_customer_account_loginPost', array('controller_action'=>$accountControl));
Mage::dispatchEvent('controller_action_postdispatch_customer', array('controller_action'=>$accountControl));
Mage::dispatchEvent('controller_action_postdispatch', array('controller_action'=>$accountControl));
$customer = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array('eq' => $user->getId()))
->getFirstItem();
try
{
// Prepare a collection of required values that the customer *should* have been set from netforum
$collection = Mage::getModel('eav/entity_attribute')->getCollection();
$collection->addFieldToFilter('entity_type_id', Mage::getModel('eav/entity')->setType('customer')->getTypeId());
// The var representing if validation has failed
$failedReq = false;
// Loop through each user defined required attribute and if we find one
// on the customer that is not set, forward the user to their account config page
foreach ($collection as $attribute)
{
if ($attribute['is_required'] && $attribute['is_user_defined'])
{
$attrCode = $attribute['attribute_code'];
if (!isset($customer[$attrCode]))
{
$failedReq = true;
}
}
}
// Try to determine where we logged in from (URL)
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
$outputMessage = $session->getData('before_auth_url');
// Proceeed differently based on the existence of addresses
if ($noAddress == true)
{
if ($failedReq)
{
// Customer failed login. To be expected if they are signing in with SSO and never have before
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/account/edit/';
Mage::getSingleton('core/session')->addError('<b>Please fill in the required fields marked with * and click "Save"</b>');
header("Location: $redirect_to");
}
else
{
// Customer checks out ok, but has no addresses. Send them to the address setup screen
Mage::getSingleton('core/session')->addError('<b>Please fill in your address and phone number, then click "Save"</b>');
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/address/edit/';
header("Location: $redirect_to");
}
}
else
{
// Customer has addresses being passed from SSO
$defaultBillingId = $customer->getDefaultBillingAddress()->getId();
$hasPhoneNumber = false;
foreach ($customer->getAddresses() as $address)
{
$addrs = Mage::getModel('customer/address')->load($address->getId());
$magePhone = $addrs->getTelephone();
if ($magePhone)
{
$hasPhoneNumber = true;
}
}
if ($failedReq)
{
// Customer failed login. To be expected if they are signing in with SSO and never have before
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/account/edit/';
Mage::getSingleton('core/session')->addError('<b>Please fill in the required fields marked with * and click "Save"</b>');
header("Location: $redirect_to");
}
else
{
// Customer is has default values filled out
if (!$hasPhoneNumber)
{
// Phone number is missing for an address so redirect there and force em to enter it.
Mage::getSingleton('core/session')->addError('<b>Please fill in the required fields marked with * and click "Save Address"</b>');
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/address/edit/id/' . $defaultBillingId;
header("Location: $redirect_to");
}
else
{
// Everything is ok, so just try to send them back to where they came from, or the account screen
if ($outputMessage)
{
$redirect_to = $outputMessage;
}
else
{
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/account/';
}
header("Location: $redirect_to");
}
}
}
}
catch (Exception $e)
{
if ($outputMessage)
{
$redirect_to = $outputMessage;
}
else
{
$redirect_to = 'https://' . $_SERVER['HTTP_HOST'] . '/customer/account/';
}
header("Location: $redirect_to");
}
}
I know I am late but
http://amasty.com/sales-reps-and-dealers.html
This extension can be helpful to achieve what you are looking for. It will allow to create hierarchical accounts and assign the sales rep/sub admins to the orders and provide the access levels.
Hope this helps.

Resources