Get result from vTiger webservice - web-services

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/

Related

Regular expression for laravel username and #tags

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.

Batch Insert data into database using web services in yii2 error

I've tried for get data in web services at http://api.rajaongkir.com/dokumentasi/starter. And I was success show data in view browser. When I implementation for insert data with a lot of into database something any wrong. I don't know why.
This code for get data in web service at http://api.rajaongkir.com/dokumentasi/starter. And put in controllers/TestController.php
public function actionGetProvince($id=0)
{
$client = new client();
$addUrl = ($id>0)?'id='.$id:'';
$response = $client->createRequest()
->setFormat(Client::FORMAT_JSON)
->setMethod('get')
->setUrl('http://api.rajaongkir.com/starter/province?'.$addUrl)
->addHeaders(['key' => 'example'])
->send();
if ($response->isOk) {
$content = \Yii\helpers\Json::decode($response->content);
//$content['rajaongkir']['query']
//$content['rajaongkir']['status']
$results = $content['rajaongkir']['results'];
if ($id > 0) {
if (count($results)>0) {
echo $results['province_id'] . ' - ';
echo $results['province'] . '<br>';
}
else {
echo "blank";
}
} else {
foreach ($results as $provinces) {
echo $provinces['province_id']." - ".$provinces['province']."<br>";
}
}
} else {
$content = \Yii\helpers\Json::decode($response->content);
echo $content['rajaongkir']['status']['description'];
}
}
And this code for insert data with a lot of in database, and I put in file same.
Yii::$app->db->createCommand()->batchInsert('province', [
'id_province' => $provinces['province_id'], 'name' => $provinces['province']
])->execute();
And the result error is :
PHP Warning – yii\base\ErrorException : Missing argument 3 for yii\db\Command::batchInsert(), called in C:\wamp\www\basic_yii2\controllers\TestController.php on line 60 and defined
You are not calling batchInsert() properly.
See it in documentation.
public $this batchInsert ( $table, $columns, $rows )
$table string The table that new rows will be inserted into.
$columns array The column names
$rows array The rows to be batch inserted into the table
Example:
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();

Coupon Magento API Soap

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();
}

Vtiger Webform issue

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

I'm getting 'The request must contain the parameter Signature' although I'm actually supplying it

I'm trying the AWS Product Advertisement API in PhP.
Here is the PhP code that I've copied from net.
function callSOAPFunction($function, $array){
$timeStamp = gmdate("Y-m-d\TH:i:s\Z");
//service is always the same, $function is operation
$string = 'AWSECommerceService'.$function.$timeStamp;
$signature = base64_encode(hash_hmac("sha256", $string, 'MySecretKey', True));
$params = array('Service' => 'AWSECommerceService',
'AssociateTag' => 'Wassup?',
**'Signature' => $signature,**
'AWSAccessKeyId' => 'MyKey'
'Request' => array($array),
'Timestamp' => $timeStamp
);
$client = new
SoapClient("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
array('exceptions' => 0));
return $client->__soapCall($function, array($params));
}
$array = array('Operation' => 'ItemSearchRequest',
'ItemPage' => 3,
'SearchIndex' => 'DVD',
'ResponseGroup' => 'Large',
'Keywords' => 'Karate');
$result = callSOAPFunction("ItemSearch", $array);
Although I'm including the signature parameter, I'm still getting the error.