Suitecrm create user using api - suitecrm

My question is when i create new user in SUITECRM, i want to insert data in another application and other CodeIgniter database.
Please help me, about how to solve above problem.
I have create custom insert insert api like:
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once '../config/database.php';
// instantiate product object
include_once '../objects/product.php';
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
//get posted data
$data = (object) $_POST;
//$data = json_decode(file_get_contents("php://input"));
// set product property values
$product->name = $data->name;
$product->description = $data->description;
$product->price = $data->price;
$product->category_id = $data->category_id;
$product->created = date('Y-m-d H:i:s');
// create the product
if($product->create()){
echo '{';
echo '"message": "Product was created."';
echo '}';
}
// if unable to create the product, tell the user
else{
echo '{';
echo '"message": "Unable to create product."';
echo '}';
}
?>

Related

React-App Axios POST to php.file with sentMail ->works from localhost but empty $_Post['***'] from Server

I have an mail.php file in root on my hosting space.
Do I call mail.php with axios from my localhost from within the development server (npm start) it works fine.
The form who triggers the POST sends the data to my Email address.
After the build process and the upload on my web space, I still receive an email but there the input is missing.
Axios POST:
const formData = new FormData();
// formData.append('name', datas.name);
// formData.append('email', datas.email);
// formData.append('message', datas.message);
// formData.append('nice', nice)
formData.append('name', 'Klara');
formData.append('email', 'klara#gmail.com');
formData.append('message', 'Hallo');
//POST data to the php file
try{
axios.post('https://salevsky.net/mail.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
} catch(error) {
PHP file:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: multipart/form-data');
$to = "blablub#webyy.net";
$subject = "Contact Us";
// // Email Template
$message .= "<b>Message : </b>".$_POST['name']."<br>";
$message .= "<b>Email Address : </b>".$_POST['email']."<br>";
$message .= "<b>Message : </b>".$_POST['message']."<br>";
$header = "From:".$_POST['email']." \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
// // message Notification
if( $retval == true ) {
echo json_encode(array(
'success'=> true,
'message' => 'Message sent successfully'
));
}else {
echo json_encode(array(
'error'=> true,
'message' => 'Error sending message'
));
}
?>
I tried various DataTypes and ContentForms.
At least headers: { "Content-Type": "multipart/x-www-form-urlencoded" },
I wonder why content type in request header is not changing. I see this in the Browser under Network. It's application/json all time. But I don't know if it's an important fact.

Single Signon with Magento account from drupal

I have custom Magento script file as below which does login by just passing email and password to that PHP file.
It works fine when i'm making a call from browser.
But, I want to make this call through Drupal Module which i have created.
As i expected call is happening from Drupal module and i'm getting success message too. But login is not happening.
My hunch is that magento have some login restrictions which happening outside magento root folder.
Please find the source below.
Drupal directory - /www/drupal/
Magento directory - /www/drupal/store/
/www/drupal/store/api_config.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once (dirname(dirname(realpath(__FILE__))).'/store/app/Mage.php');
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$response = array();
/www/drupal/store/api_login.php
<?php
require_once "api_config.php";
$session = Mage::getSingleton('customer/session');
//$session->start();
if (isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['password']) && !empty($_GET['password'] )) {
if (!filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
$email = $_GET['email'];
$password = $_GET['password'];
try {
if ($session->login($email, $password )) {
$response['status'] = 'success';
$response['data'] = array($_GET);
$response['message'] = array('User loggedin Successfully.');
} else {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('User login failed.');
}
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($email);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
//$session->addError($message);
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($message);
echo $message;
$session->setUsername($email);
} catch (Exception $e) {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($e);
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Invalid Email address');
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Login and password are required.');
}
print_r(json_encode($response, JSON_FORCE_OBJECT));die;
?>
/www/drupal/sites/all/modules/single_signon/single_signon.module
<?php
function single_signon_user_login(&$edit, $account) {
//store variable values
$postData = array();
$postData['email'] = $account->mail;
$postData['password'] = $edit['input']['pass'];
$inc = 1; //count of registration
if (!empty($postData['email']) && !empty($postData['password'])) {
// use of drupal_http_request
$data = http_build_query($postData, '', '&');
//$url = url('http://127.0.0.1/drupal/store/api_login.php?'.$data);
//$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
//print_r($url);
// the actual sending of the data
$JSONresponse = drupal_http_request('http://127.0.0.1/drupal/store/api_login.php?email=john#example.com&password=password');
//print_r($JSONresponse);die;
$response = json_decode($JSONresponse->data, true);
if ($response['status']=='success') {
$inc+=1;
$message = 'Logged in successfully('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
} else {
$message = 'Logged in failed. Due to '.$response['message'].'('.$inc.')';
drupal_set_message($message, $type = 'error ', $repeat = FALSE);
}
} else {
$message = 'Not able to log inside store('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
}
}
?>
Any suggestions for findings to solve this mystery would be really helpful.
I'm not sure to understand it well : You have a php script using data send in the URL (GET) to connect a user in a session. And you would like the Drupal server to use it to connect directly to your Magento.
I think your code is working, but unfortunately it could not help the user to connect to Magento.
As this is the Drupal server asking for the connection, it would be the Drupal server session that will be connected and not the navigation user one.
If the user have to be connected, in his navigator, to the Magento server, it has to be the navigator witch must call the Magento script directly.
It could be done in an iframe or via Ajax I think.
I think you can also find some other solutions, as OAuth, but it will need a lot more of coding.
EDIT
I found some interesting subject about your problem :
Getting logged in user ID from Magento in external script - multiple session issue?
Magento Session from external page (same domain)
Magento external login will not create session cookie
I think you have to manually create the Magento session cookie on the user navigator, from the Drupal script.
You'll need to send back to Drupal the SessionID from Magento, using this method (I think, you'll have to verify) :
$response['sessionId'] = $session->getEncryptedSessionId();
And inside the Drupal script, you'll have to record a new cookie with the Magento session information. Maybe you have to have a look at a working Magento cookie to see how it is defined and what is its name.
if ($response['status']=='success') {
...
setcookie('frontend', $response['sessionId'], time() + 3600 * 24 * 180, '/');
...
}
You'll probably have to declare, in the settings of Magento, the path for cookies at '/'.
Can you give an example of the structure of the session cookie from Magento ?

Using gson to parse jsonarray and jsonobject

a login api when success return:
{"status":0,"data":{userid:1,username:"abc"},"msg":"login sucess"}
but when error server return:
{"status":0,"data":[],"msg":"login failureļ¼"}
how to define a object, then use gson to parse the data field!
thanks.
Is it json or gson? For example your response is on this variable $response;
You can try:
<?php
$response = '{"status":0,"data":{userid:1,username:"abc"},"msg":"login sucess"}';
// $response = '{"status":0,"data":[],"msg":"login failureļ¼"}';
$response = json_decode($response);
if(empty($response->data){
echo $response->msg;
}
// print_r($response); //you can try to print_r $response here
// if have data to login, do what you want

How do I send email using gmail api php

How do I send email using gmail api php
$msg['raw'] = "This is sample test message";
$msg['To'] = "test.api#gmail.com";
$msg['subject'] = "Sample test subject";
currently i am using $message = $service->users_messages->send('me', $msg);
Where to difine to,subject ?
Based on http://www.pipiscrew.com/2015/04/php-send-mail-through-gmail-api/ here is the answer:
$user = 'me';
$strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');
$strRawMessage = "From: myAddress<myemail#gmail.com>\r\n";
$strRawMessage .= "To: toAddress <recptAddress#gmail.com>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= "this <b>is a test message!\r\n";
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
//The special value **me** can be used to indicate the authenticated user.
$service->users_messages->send("me", $msg);
Swiftmailer has all the tools for building base64 message.
Here is a full sample for sending a email:
// Visit https://developers.google.com/gmail/api/quickstart/php
// for an example of how to build the getClient() function.
$client = getClient();
$service = new \Google_Service_Gmail($client);
$mailer = $service->users_messages;
$message = (new \Swift_Message('Here is my subject'))
->setFrom('myemailaddress#myserver.com')
->setTo(['receiver#someserver.com' => 'Test Name'])
->setContentType('text/html')
->setCharset('utf-8')
->setBody('<h4>Here is my body</h4>');
$msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
->encodeString($message->toString());
$message = new \Google_Service_Gmail_Message();
$message->setRaw($msg_base64);
$message = $mailer->send('me', $message);
print_r($message);
Edit in November 2021
Swiftmailer has reached its end of life. See swiftmailer's author blog post.
From now on you should use the Symfony Mailer component.
I am using the same code and it does work fine except that it always sends a plain text email.
Isn't specifying Content-Type: text/html; enough?

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Resources