yii2 how can I access post value - php

I have the following code in my controller trying to get it to work before adding validation etc
This code is from here however I will be adapting it anyway
$email = $_POST['Newsletter[email]'];
$session->save_email($email);
// Subscribe User to List
$api_key = new sammaye\mailchimp\Mailchimp(['apikey' => 'xxxxxxxxxxx']);
$list_id = "xxxxxxxxxxx";
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => $email ) );
However I get the following error (Does this mean my most data is in an array newbie)
Undefined index: Newsletter[email]
Is this something I need to set within my yii2 form so that instead of the name field being Newsletter[email] its just email?

You can do this as follows:
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$email = $data['NewsLetter']['email'];
}

As was already stated you can either use $_POST or the request-object.
That object encompasses everything that enters your application on startup. So yes, \Yii::$app->request->post() gives you all incoming POST-data and \Yii::$app->request->post('name') will give you a single one. Same with the get function.
However given your code that is not how you should be using Yii. The name of your variables suggests that the post is done using a model, so you might want to use that again, makes it a lot easier on validation.
If you don't have the model, it can look like so:
class Newsletter extends \yii\base\Model
{
public $email;
public function rules()
{
return array(
array('email', 'email', 'skipOnEmpty' => false)
);
}
}
The actual code in your controller could be more amongst the lines:
$request = \Yii::$app->request;
if ($request->isPost) {
$newsletter = new Newsletter;
if ($newsletter->load($request->post()) && $newsletter->validate()) {
// do your thing
}
}

It means, it is inside an array.
Try to do the following instead :
// Using isset will make sure, you don't trigger a Notice (when the variable does not exist)
$email = isset($_POST['Newsletter']['email']) ? $_POST['Newsletter']['email'] : null;
// Make sure you are receiving an email address
if ($email && filter_var($email, FILTER_VALIDATE_EMAIL))
{
$session->save_email($email);
// Subscribe User to List
$api_key = new sammaye\mailchimp\Mailchimp(['apikey' => 'xxxxxxxxxxx']);
$list_id = "xxxxxxxxxxx";
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => $email ) );
}
// Display an error message ?
else
{
// #todo
}

If the HTML form field is as below
<input name="Newsletter[email]" type="text">
then the code with in controller should be
$data = Yii::$app->request->post();
$email= $data['Newsletter']['email'];

The inline solution is:
if(is_null($email = Yii::$app->request->post('Newsletter')['email']))
throw new BadRequestHttpException('newsletter email must set');
if so if email isn't set it throws Bad Request and notice that $_POST isn't good solution when you are using a PHP framework and it's security isn't provided by framework but Yii::$app->request->post is secured by Yii.

You should simply try $_POST['Newsletter']['email'].

Related

Returning Values through HTTP Post within Infusionsoft Campaign API

The specific objective here is as follows -
Using Infusionsoft API (iSDK),
I need to create and host a file instructing infusionsoft to return the value of a 'Name / Value' pair from an HTTP Post to a contact specific Custom Field.
This is become increasing challenging as most of my experience revolves around HTML, CSS and basic Javascript and I am completely at a loss.
My HTTP Post url points to the following php file.
<?php require("isdk.php");
$app = new iSDK;
$connInfo = array(
"appname:appname:i:myapikey:appname.infusionsoft.com"
);
$returnFields = array('numberId');
$conDat = $app->loadCon('numberId', $returnFields);
$returnId = $conDat['numberId'];
$update = array('_customField' => 'numberId');
$conID = $app->updateCon($contactId, $update);
/*
And some additional code I don't know how to apply
$app->updateCustomField($, $numberId)
{
$carray = array(
php_xmlrpc_encode((int)$fieldId),
php_xmlrpc_encode($fieldValues));
return $this->methodCaller("DataService.updateCustomField", $carray);
}
*/

How to add Account name to a contact in Dynamics 365

I am using Alexa-php-toolkit for Dynamics 365 https://github.com/AlexaCRM/php-crm-toolkit, using this I can successfully create new contact but I can't add an account name with the contact, when I try I get this error:
Notice: Property accountid of the contact entity cannot be set in ../vendor/alexacrm/php-crm-toolkit/src/Entity.php on line 263.
Here is my script.
<?php
//URL: https://github.com/AlexaCRM/php-crm-toolkit
/**
* Use init.php if you didn't install the package via Composer
*/
use AlexaCRM\CRMToolkit\Client as OrganizationService;
use AlexaCRM\CRMToolkit\Settings;
require_once '../vendor/autoload.php';
require_once '../vendor/alexacrm/php-crm-toolkit/init.php';
require_once 'config.php';
require_once 'includes/db.php';
$db = new DB();
$options = getAuth();
$serviceSettings = new Settings( $options );
$service = new OrganizationService( $serviceSettings );
$accountId = 'a2536507-018d-e711-8115-c4346bac0a5f';
// create a new contact
$contact = $service->entity( 'contact' );
$contact->accountid = $accountId;
$contact->firstname = 'Test';
$contact->lastname = 'Contact12';
$contact->jobtitle = 'Business Analyst';
$contact->mobilephone = '1002345679';
$contact->fax = '9902345679';
$contact->emailaddress1 = 'john.doe1#example.com';
$contact->address1_line1 = '119 Cambridge';
$contact->address1_line2 = 'Apt 22';
$contact->address1_city = 'Houston';
$contact->address1_stateorprovince = 'TX';
$contact->address1_postalcode = '77009';
$contact->address1_country = 'US';
$contactId = $contact->create();
echo $contactId;
?>
There is this line of your code in a question:
$contact->accountid = $accountId;
First, the parent account on a contact is saved in the parentcustomerid field that is a special lookup field that can store link to both account or contact entity.
The fields accountid and parentcontactid help to handle this in background, but are not generaly available. You need to work with parentcustomerid field.
Second, another problem when working with lookups (foreign keys) is you need to pass entity type (table name).
The correct code might look like this:
$accountRef = $client->entity( 'account' );
$accountRef->ID = $accountId;
$contact->parentcustomerid = $accountRef;
or
$contact->parentcustomerid = new EntityReference( 'account', $accountId );
Those examples are taken from the issue list, adjusted, but not tested. I hope it is working example, not functionality request.

Send link with variable using Zend_Mail

I am triyng to send a email with a link when the user complete registration.
The link should have a variable $id with the id of the user.
I tried different things but my link always appear as
http://localhost/users-data/activate/.php?id=>
I am using Zend_Mail.
What I am trying to do, is for example: send to user id =1 a link http://localhost/users-data/activate1. For then I can take the last number of url, which should correspond to id, and set the status to this user in my activate script.
Could you show me what I doing wrong?
This is my registerAction
public function registerAction()
{
// action body
$request = $this->getRequest();
$form = new Application_Form_UsersData();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$comment = new Application_Model_UsersData($form->getValues());
$mapper = new Application_Model_UsersDataMapper();
$mapper->save($comment);
// send email
$id = $comment -> getId();
$formValues = $this->_request->getParams();
$mail = new Application_Model_Mail();
$mail->sendActivationEmail($formValues['email'], $id,$formValues['name']);
$this->_redirect('/users-data/regsuccess');
}
}
$this->view->form = $form;
}
This is my Application_Model_Mail
class Application_Model_Mail
{
public function sendActivationEmail($email, $id,$name)
{
require_once('Zend/Mail/Transport/Smtp.php');
require_once 'Zend/Mail.php';
$config = array('auth' => 'login',
'username' => '*******#gmail.com',
'password' => '******',
'port' => '587',
'ssl' => 'tls');
$tr = new Zend_Mail_Transport_Smtp('smtp.gmail.com',$config);
Zend_Mail::setDefaultTransport($tr);
$mail = new Zend_Mail();
$mail->setBodyText('Please click the following link to activate your account '
. '<a http://localhost/users-data/activate/.php?id='.$id.'>'.$id.'</a>')
->setFrom('admin#yourwebsite.com', 'Website Name Admin')
->addTo($email, $name)
->setSubject('Registration Success at Website Name')
->send($tr);
}
}
You go from $request to $_request. The latter is not defined anywhere, so its values are null.
Try this
$mail->setBodyHtml("Please click the following link to activate your".
"account<a href='http://localhost/users-data/activate.php?id=$id'>$id</a>")
The HTML link you create is incorrect:
'<a http://localhost/users-data/activate/.php?id='.$id.'>'
In HTML, a valid link is (note the href attribute):
...
So your script should construct the link like this:
'<a href="http://localhost/users-data/activate/.php?id='.$id.'">'
Also, I suppose http://localhost/users-data/activate/.php is not what you want: your script has probably a name before the php extension.

Laravel mail cannot send from field

Im trying to send mail from laravel and when i add the dynamic from field i get this error:
"Expected response code 250 but got code "501", with message "501 A syntax error was encountered in command argument.."
this is the code:
$user = Input::get('user');
Mail::send('template.contact', $user , function($message) use ($user)
{
$email = $user['email'];
$message->from($email , 'name'); thats doesnt
//$message->from('us#example.com', 'Laravel'); that work
$message->to('test#gmail.com', 'contact us' )->subject($user['subject']);
});
and the user is coming from angular -
service:
this.sendConatctMail = function(data) {
return $http.post('send-contact-mail', {user: data});
}
and controller:
contactService.sendConatctMail($scope.user);
Here's one way you can solve this.
Let's assume the data on this.sendConatctMail = function(data) { is a object like this:
var data {
email: 'some#email.com',
// other field: values
}
Right before you post it, you should convert it into JSON string like this:
return $http.post('send-contact-mail', {user: JSON.stringify(data)});
Then on Laravel/PHP side, decode that back into an array and use it like this:
if (Input::has('user'))
{
// Decode json string
$user = #json_decode(Input::get('user'), true);
// Proceed if json decoding was success
if ($user)
{
// send email
Mail::send('template.contact', $user , function($message) use (&$user)
{
$message->from($user['email'], 'name')
->to('test#gmail.com', 'contact us')
->subject($user['subject']);
});
}
}
I don't know if this will help you, but whenever I send emails through Laravel, I need to alter the use(...) section a bit. You have:
$user = Input::get('user');
Mail::send('template.contact', $user , function($message) use ($user)
...
Try changing it to this and see what happens:
$user = Input::get('user');
Mail::send('template.contact', array('user' => $user), function($message) use (&$user) {
$message->from($user['email'], $user['name']);
$message->to('test#gmail.com', 'contact us')->subject($user['subject']);
}
2 changes I made:
array('user' => $user)
and
use(&$user)
I don't know if that will help you, but I have working emails on my application that look almost identical to yours, except for the &$variable instead of just $variable
Good luck!
The problem is with your $email = $user['email'];
try checking your $user['email']
if $message->from('us#example.com', 'Laravel'); this works
then
$email = $user['email'];
$message->from($email , 'name');
this must work...
I have tried the same without much trouble...
In my application I needed to pass the _token variable in all my ajax request any such problems??

Token Issue with recurring payments with Payum

I am trying to run the example code here
But I am getting this error:
Payum\Core\Exception\InvalidArgumentException: A token with hash `RVpxpP1m3HnTWcj2oL19SQ38NWvCDIz5qeUwfr283kY` could not be found. in /var/www/test/vendor/payum/core/Payum/Core/Security/PlainHttpRequestVerifier.php on line 47
My code looks like this:
namespace Paypal\Model;
use Payum\Core\Model\ArrayObject;
class AgreementDetails extends ArrayObject {
}
namespace Paypal\Model;
use Payum\Core\Model\Token;
class PaymentSecurityToken extends Token
{
}
namespace Paypal\Model;
use Payum\Core\Model\ArrayObject;
class RecurringPaymentDetails extends ArrayObject{
}
config.php
use Buzz\Client\Curl;
use Payum\Paypal\ExpressCheckout\Nvp\PaymentFactory;
use Payum\Paypal\ExpressCheckout\Nvp\Api;
use Payum\Core\Registry\SimpleRegistry;
use Payum\Core\Storage\FilesystemStorage;
use Payum\Core\Security\PlainHttpRequestVerifier;
use Payum\Core\Security\GenericTokenFactory;
$tokenStorage = new FilesystemStorage('/home/vagrant/tmp', 'Paypal\Model\PaymentSecurityToken');
$requestVerifier = new PlainHttpRequestVerifier($tokenStorage);
$agreementDetailsClass = 'Paypal\Model\AgreementDetails';
$recurringPaymentDetailsClass = 'Paypal\Model\RecurringPaymentDetails';
$storages = array(
'paypal' => array(
$agreementDetailsClass => new FilesystemStorage('/home/vagrant/tmp',$agreementDetailsClass),
$recurringPaymentDetailsClass => new FilesystemStorage('/home/vagrant/tmp',$recurringPaymentDetailsClass)
)
);
$payments = array(
'paypal' => PaymentFactory::create(new Api(new Curl, array(
'username' => 'REPLACE WITH YOURS',
'password' => 'REPLACE WITH YOURS',
'signature' => 'REPLACE WITH YOURS',
'sandbox' => true
)
)));
$registry = new SimpleRegistry($payments, $storages, null, null);
$tokenFactory = new GenericTokenFactory(
$tokenStorage,
$registry,
'https://'.$_SERVER['HTTP_HOST'],
'capture.php',
'notify.php'
);
prepare.php
use Payum\Paypal\ExpressCheckout\Nvp\Api;
include 'config.php';
$storage = $registry->getStorageForClass($agreementDetailsClass, 'paypal');
$agreementDetails = $storage->createModel();
$agreementDetails['PAYMENTREQUEST_0_AMT'] = 0;
$agreementDetails['L_BILLINGTYPE0'] = Api::BILLINGTYPE_RECURRING_PAYMENTS;
$agreementDetails['L_BILLINGAGREEMENTDESCRIPTION0'] = $subscription['description'];
$agreementDetails['NOSHIPPING'] = 1;
$storage->updateModel($agreementDetails);
$captureToken = $tokenFactory->createCaptureToken('paypal', $agreementDetails, 'create_recurring_payment.php');
$agreementDetails['RETURNURL'] = $captureToken->getTargetUrl();
$agreementDetails['CANCELURL'] = $captureToken->getTargetUrl();
$storage->updateModel($agreementDetails);
header("Location: ".$captureToken->getTargetUrl());
capture.php
use Payum\Core\Request\BinaryMaskStatusRequest;
use Payum\Core\Request\SecuredCaptureRequest;
use Payum\Core\Request\RedirectUrlInteractiveRequest;
include 'config.php';
$token = $requestVerifier->verify($_REQUEST);
$payment = $registry->getPayment($token->getPaymentName());
$payment->execute($status = new BinaryMaskStatusRequest($token));
if (false == $status->isNew()) {
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
if ($interactiveRequest = $payment->execute(new SecuredCaptureRequest($token), true)) {
if ($interactiveRequest instanceof RedirectUrlInteractiveRequest) {
header("Location: ".$interactiveRequest->getUrl());
die();
}
throw new \LogicException('Unsupported interactive request', null, $interactiveRequest);
}
$requestVerifier->invalidate($token);
header("Location: ".$token->getAfterUrl());
create_recurring_payment.php
same as here
I have confirmed that file storage class is able to write data to files, but on capture step it fails to verify the token.
Any sort of help is appreciated to get this code running.
Token storage is not configured correctly (not your fault the doc is wrong too). It has to use hash model field as id. Try:
<?php
$tokenStorage = new FilesystemStorage('/home/vagrant/tmp', 'Paypal\Model\PaymentSecurityToken', 'hash');
About the exception you've gotten. It tries to find token by id and uses for that token's hash. Ofcouce it is could not be found.

Categories