I am trying to store data in vtiger leads module. i can send variable via file_get_contents()
but its not working . here is my code
$moduleName = $_POST['moduleName'];
$company = $_POST['company'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$website = $_POST['website'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$code = $_POST['code'];
$post = http_build_query(array(
"firstname" => "$firstname",
"lastname" => "$lastname",
"website"=>"$website",
"phone"=>"$phone",
"email"=>"$email",
"city"=>"$city",
"state"=>"$state",
"code"=>"$code",
"moduleName" => "$moduleName",
"company " => "$company",
));
$context = stream_context_create(array("http"=>array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: ". strlen($post) . "\r\n",
"content" => $post,
)));
$page = file_get_contents("http://vtiger.com/modules/Webforms/post.php", false, $context);
Please help me.
Use web forms correctly, in vtiger 5.4 you can create webforms ealsily with its interface. oru user vtiger webservices to create,edit,delte data
Related
how can I set up a Regular expression for #username and #example on post field form, just like Twitter , when a user uses #hashtag in there post I will like to automatically save it to tag table and when a user uses #john symbol I would like to automatically notify the user he /she has been mentioned , please what is the logic behind this I don't have idea on how to start
im getting this error
BadMethodCallException
Method App\Http\Livewire\createPost::tag does not exist.
public function createPost()
{
if (auth()->check()) {
$this->validate();
$posts = Post::create([
'user_id' => auth()->user()->id,
'school_id' => $this->school,
'body' => $this->body,
'is_anon' => $this->is_anon,
$url = \url(route('posts.show', $this->id)),
]);
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedTags, PREG_SET_ORDER, 0);
foreach($matchedTags as $matchedTag) {
if(!$tag = tag::where('name', $matchedTag[0])->first()) {
$tag = tag::create(['name' => $matchedTag[0]]);
}
$this->tags()->attach($tag->id);
}
assuming your input string is $str, you can use these:
preg_match_all('/(?<=#)(\w+)/mi', $str, $atSignMatches, PREG_SET_ORDER, 0);
preg_match_all('/(?<=#)(\w+)/mi', $str, $poundMatches, PREG_SET_ORDER, 0);
and then you can print the $atSignMatches and $poundMatches which are the resulting values.
More info on https://www.php.net/manual/en/function.preg-match-all.php
Update: Steps
These are the steps to extract users and make notifications.
Get Request payload.
Extract Tags (using #)
Create Tag records in table
Extract mentions (using #)
Create notification for mentioners
public function save(Request $request) {
{
$post = Post::create($request->all());
$content = $post->content;
preg_match_all('/(?<=#)(\w+)/mi', $content, $matchedTags, PREG_SET_ORDER, 0);
foreach($matchedTags as $matchedTag) {
if(!$tag = Tag::where('name', $matchedTag[0])->first()) {
$tag = Tag::create(['name' => $matchedTag[0]]);
}
$post->tags()->attach($tag->id);
}
preg_match_all('/(?<=#)(\w+)/mi', $content, $matchedMentions, PREG_SET_ORDER, 0);
foreach($matchedMentions as $matchedMention) {
if($user = User::where('username', $matchedMention[0])->first()) {
$user->notifications()->create([
'post_id' => $post->id,
'type' => "MENTION",
'seen' => false,
'time' => \Carbon\Carbon::now()
]);
}
}
}
Notes:
Make sure to change the tag and notification creation implementation matching your table structure.
I am using Connecty Cube and following the documentation to get a user session token, however the response is
Client error: POST https://api.connectycube.com/session resulted in a 422 Unprocessable Entity response:
{"errors":["Unexpected signature"]}
I am using the below code to get the session token.
use GuzzleHttp\Psr7;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\TransferException;
$client = new Client();
// Create Connecty Cube Session
$application_id = env('CUBE_APPLICATION_ID');
$auth_key = env('CUBE_APPLICATION_KEY');
$timestamp = time();
$nonce = substr($timestamp, 0, 4);
$response = $client->request('POST', 'https://api.connectycube.com/session', [
'form_params' => [
'application_id' => $application_id,
'auth_key' => $auth_key,
'timestamp' => $timestamp,
'nonce' => $nonce,
'signature' => hash_hmac('sha1',
http_build_query([
'application_id' => $application_id,
'auth_key' => $auth_key,
'nonce' => $nonce,
'timestamp' => $timestamp,
]),
env('CUBE_APPLICATION_SECRET')
),
"user" => [
"email" => <email address>,
"password" => <password>
]
]
]);
$contents = json_decode($response->getBody()->getContents(), true);
var_dump($contents);
Please help me to figure out where I am going wrong. Thank You!
// Application credentials
DEFINE('APPLICATION_ID', 1204);
DEFINE('AUTH_KEY', "HhBrEq4BRgT4R8S");
DEFINE('AUTH_SECRET', "TkpdsDSSWyD6Sgb");
// endpoints
DEFINE('CB_API_ENDPOINT', "https://api.connectycube.com");
DEFINE('CB_PATH_SESSION', "session.json");
// Generate signature
$nonce = rand();
$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."×tamp=".$timestamp;
echo "stringForSignature: " . $signature_string . "<br><br>";
$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);
// Build post body
$post_body = http_build_query(array(
'application_id' => APPLICATION_ID,
'auth_key' => AUTH_KEY,
'timestamp' => $timestamp,
'nonce' => $nonce,
'signature' => $signature
));
// $post_body = "application_id=" . APPLICATION_ID . "&auth_key=" . AUTH_KEY . "×tamp=" . $timestamp . "&nonce=" . $nonce . "&signature=" . $signature;
echo "postBody: " . $post_body . "<br><br>";
// Configure cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, CB_API_ENDPOINT . '/' . CB_PATH_SESSION); // Full path is - https://api.connectycube.com/session.json
curl_setopt($curl, CURLOPT_POST, true); // Use POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response
// Execute request and read responce
$responce = curl_exec($curl);
// Check errors
if ($responce) {
echo $responce . "\n";
} else {
$error = curl_error($curl). '(' .curl_errno($curl). ')';
echo $error . "\n";
}
// Close connection
curl_close($curl);
I am writing a wordpress-plugin which queries data from the vTiger Webservice-API. I read the tutorial (https://wiki.vtiger.com/index.php/Webservices_tutorials#QueryResult) and know the reference (https://wiki.vtiger.com/index.php/Webservice_reference_manual). In the tutorial the use Zend-JSON and HTTP_Client. I use cURL (because it was installed and I thought it was worth a try to use before I install other utilities). It works quite well and I am able to Login to vTiger with our API-User and send the queries. What I receive is something like this:
array(2) {
["success"]=>
bool(true)
["result"]=>
array(4) {
["sessionName"]=>
string(21) "4d103e2058f9d365c22ff"
["userId"]=>
string(4) "19x9"
["version"]=>
string(4) "0.22"
["vtigerVersion"]=>
string(5) "6.5.0"
}
}
Looks very good to me but the Thing I am missing is the actual data from my query.
This is my PHP-Code:
$vtiger->initCurl();
$challengeToken = $vtiger->getChallengeToken();
$sessionId = $vtiger->getSessionId($challengeToken);
$result = $vtiger->query($sessionId, "SELECT firstname FROM 'Contacts' WHERE lastname = 'XXX';");
$wpdb->replace( $wpdb->prefix.$_CONFIG['dbtable'], array( 'id' => 1, 'syncfields' => $result), array('%d', '%s') );
$vtiger->logout($sessionId);
$vtiger->closeCurl();
$result = json_decode($result, true);
return var_dump(($result['success']) ? $result : "Error");
What am I missing to get the firstname (or any other value from the vTiger-DB)?
In the Code I am just writing the Response to the wp-db (extra-Table).
Thanks,
Nico
Vtiger Result Return in array format. you should change your code
$vtiger->initCurl();
$challengeToken = $vtiger->getChallengeToken();
$sessionId = $vtiger->getSessionId($challengeToken);
$result = $vtiger->query($sessionId, "SELECT firstname FROM 'Contacts' WHERE lastname = 'XXX';");
$syncfield = result['0'];
$wpdb->replace( $wpdb->prefix.$_CONFIG['dbtable'], array( 'id' => 1, 'syncfields' => $syncfield), array('%d', '%s') );
$vtiger->logout($sessionId);
$vtiger->closeCurl();
$result = json_decode($result, true);
return var_dump(($result['success']) ? $result : "Error");
َAlso You Can Use vtiger CRM Webservice Client Library
http://forge.vtiger.com/projects/vtwsclib/
I’ve a problem with the Coupon API when i make :
$couponCode = "test";
$resultCartCoupon = $proxy->call($sessionId, "cart_coupon.add", array($shoppingCartId, $couponCode));
I always got : Uncaught SoapFault exception: [1083] Coupon is not valid if i try the coupon code in the front end there is no problem. Is there anyone who have ever used this API part with success ?
Thanks.
This error comes from Mage_Checkout_Model_Cart_Coupon_Api::_applyCoupon()
if ($couponCode) {
if (!$couponCode == $quote->getCouponCode()) {
$this->_fault('coupon_code_is_not_valid');
}
}
This looks like it could be a bug, instead it should be if ($couponCode != $quote->getCouponCode()) { but I'm not certain.
It could be that the cart (quote) you're trying to apply the coupon to isn't valid, i.e. doesn't have the qualifying items it needs to receive the coupon. Are you sure $shoppingCartId correctly matches the expected quote in Magento's sales_flat_quote table?
I noticed that the error is in this excerpt:
try {
$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCouponCode(strlen($couponCode) ? $couponCode : '')
->collectTotals()
->save();
} catch (Exception $e) {
$this->_fault("cannot_apply_coupon_code", $e->getMessage());
}
In this specific line: ->collectTotals() By removing this stretch , not of error , but not applied the coupon.
After debugging 2-3 hour on API, I have solved this error at my-end. Check below code which i have used in Coupon API.
<?php
$mage_url = 'http://yoursiteurl/api/soap?wsdl';
$mage_user= "API_User"; //webservice user login
$mage_api_key = "API_PASSWORD"; //webservice user pass
$client = new SoapClient($mage_url);
$couponCode = 'couponCode'; // a coupon to be apply
$shoppingCartId = '35'; // a cart Id which i have put test id
$sessionId = $client->login($mage_user, $mage_api_key);
$result = $client->call($sessionId,'cart_coupon.add',array($shoppingCartId,$couponCode));
print_r($result);
?>
The above code gives error that "Uncaught SoapFault exception: [1083] Coupon is not valid". When i debugg the core code i came to know that magento cart.create API insert wrong store id in sales_flat_quote table. I have changed the store id value in sales_flat_quote table manually and again run the Coupon API and after that it works perfectly. So here is the my solution. When you create cart id just run the below update query to change the store id.
<?php
$shoppingCartId = $soap->call( $sessionId, 'cart.create');
$mageFilename = '../app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
$db_write1 = Mage::getSingleton('core/resource')->getConnection('core_write');
$updateQue = "update sales_flat_quote set store_id='1' where entity_id ='".$shoppingCartId."'";
$db_write1->query($updateQue);
// Now run the Coupon API here
?>
Code taken from here : http://chandreshrana.blogspot.in/2015/11/uncaught-soapfault-exception-1083.html
You do not need to write direct SQL to resolve this issue. Just specify store ID parameter in the API call. Example is below is the demo script to apply discount code using Magento SOAP APIs V2 :
/* Set Discount Code */
try
{
$result = $client->shoppingCartCouponAdd($session, $quoteId, 'test123',$storeId);
echo "<br>Apply discount code: ";
var_dump($result);
}
catch(Exception $ex)
{
echo "<br>Discount code Failed: " . $ex->getMessage();
}
To apply discount code, perform following steps :
$quoteId = $client->shoppingCartCreate($session,$storeId);
/* Set cart customer */
$guest = true;
if ($guest)
{
$customerData = array(
"firstname" => "testFirstname",
"lastname" => "testLastName",
"email" => "testEmail#mail.com",
"mode" => "guest",
"website_id" => "1"
);
}
else
{
$customer = array(
"customer_id" => '69301',
"website_id" => "1",
"group_id" => "1",
"store_id" => "1",
"mode" => "customer",
);
}
//Set cart customer (assign customer to quote)
$resultCustomerSet = $client->shoppingCartCustomerSet($session, $quoteId, $customerData,$storeId);
/* Set customer addresses Shipping and Billing */
$addresses = array(
array(
"mode" => "shipping",
"firstname" => "Ahsan",
"lastname" => "testLastname",
"company" => "testCompany",
"street" => "testStreet",
"city" => "Karachi",
"region" => "Sindh",
"postcode" => "7502",
"country_id" => "PK",
"telephone" => "0123456789",
"fax" => "0123456789",
"is_default_shipping" => 0,
"is_default_billing" => 0
),
array(
"mode" => "billing",
"firstname" => "Ahsan",
"lastname" => "testLastname",
"company" => "testCompany",
"street" => "testStreet",
"city" => "Karachi",
"region" => "Sindh",
"postcode" => "7502",
"country_id" => "PK",
"telephone" => "0123456789",
"fax" => "0123456789",
"is_default_shipping" => 0,
"is_default_billing" => 0
)
);
//Set cart customer address
$resultCustomerAddress = $client->shoppingCartCustomerAddresses($session, $quoteId, $addresses,$storeId);
/* Set payment method */
$responsePayment = $client->shoppingCartPaymentMethod($session, $quoteId, array(
'method' => 'cashondelivery',
),$storeId);
/* Set shipping method */
$setShipping = $client->shoppingCartShippingMethod($session, $quoteId, 'flatrate_flatrate',$storeId);
After all above apply discount code,
try
{
$result = $client->shoppingCartCouponAdd($session, $quoteId, 'test123',$storeId);
echo "<br>Apply discount code: ";
var_dump($result);
}
catch(Exception $ex)
{
echo "<br>Discount code Failed: " . $ex->getMessage();
}
i hope someone can help with this. At one point i thought i had this working but cannot figure out why it is not.
The script below does everything but include the Zend_Json::encode. It saves the user in the database it emails the person a link, however the link does not have the encryption included with it.
thanks for your help!
public function contribjoinAction()
{
$request = $this->getRequest();
$conn = XXX_Db_Connection::factory()->getMasterConnection();
$userDao = XXX_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
$userDao->setDbConnection($conn);
if ($request->isPost()) {
$fullname = $request->getPost('full_name');
$username = $request->getPost('username');
$password = $request->getPost('password');
$password2 = $request->getPost('confirmPassword');
$email = $request->getPost('email');
$islegal = $request->getPost('islegal');
$user = new Core_Models_User(array(
'user_name' => $username,
'password' => $password,
'full_name' => $fullname,
'email' => $email,
'is_active' => 0,
'created_date' => date('Y-m-d H:i:s'),
'logged_in_date' => null,
'is_online' => 0,
'role_id' => 2,
'islegal' => $islegal,
));
$id = $userDao->add($user);
$templateDao = XXX_Model_Dao_Factory::getInstance()->setModule('mail')->getTemplateDao();
$templateDao->setDbConnection($conn);
$template = $templateDao->getByName(Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
if ($template == null) {
$message = sprintf($this->view->translator('auth_mail_template_not_found'), Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
throw new Exception($message);
}
$search = array(Mail_Models_Mail::MAIL_VARIABLE_EMAIL, Mail_Models_Mail::MAIL_VARIABLE_USERNAME);
$replace = array($user->email, $user->user_name);
$subject = str_replace($search, $replace, $template->subject);
$content = str_replace($search, $replace, $template->body);
/**
* Replace the reset password link
* #TODO: Add security key?
*/
$encodedLink = array(
'email' => $email,
'user_name' => $username,
);
$encodedLink = base64_encode(urlencode(Zend_Json::encode($encodedLink)));
$link = $this->view->serverUrl() . $this->view->url(array('encoded_link' => $encodedLink), 'core_user_emailactivate');
$content = str_replace('%activate_link%', $link, $content);
/**
* Get mail transport instance
*/
$transport = Mail_Services_Mailer::getMailTransport();
$mail = new Zend_Mail();
$mail->setFrom($template->from_mail, $template->from_name)
->addTo($user->email, $user->user_name)
->setSubject($subject)
->setBodyHtml($content)
->send($transport);
if ($id > 0) {
$this->_helper->getHelper('FlashMessenger')
->addMessage($this->view->translator('user_join_success'));
$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_user_contribjoin'));
}
}
}
I have found the error. I somehow did not put the variable encoded_link into the .ini file for that module under routes.