sugarcrm retrieve accounts list in a web page using webservice - sugarcrm

I would like to retrieve all accounts datas and contact datas in Sugarcrm database using webservice .
I would like it to show it in a webpage .
How can i go about it?

Modify the below code to your requirements. It uses the SOAP API of SugarCRM.
$user_name = 'admin';
$user_password = 'admin';
$sugarcrm_url = 'http://example.com/'
$options = array(
"uri" => $sugarcrm_url,
"trace" => true
);
$offset = 0;
$limit = 100;
try {
$client = new SoapClient($sugarcrm_url.'service/v4_1/soap.php?wsdl', $options);
$response = $client->__soapCall('login',array(
'user_auth'=>array(
'user_name'=>$user_name,
'password'=>md5($user_password),
'version'=>'.01'
),
'application_name'=>'SoapTest'
));
$session_id = $response->id;
$response = $client->__soapCall('get_entry_list',array(
'session'=>$session_id,
'module_name'=>'Contacts',
'query'=>'',
'order_by'=>'contacts.last_name asc',
'offset'=>$offset,
'select_fields'=>array(),
'max_results'=>$limit)
);
print_r($response);
$response = $client->__soapCall('get_entry_list',array(
'session'=>$session_id,
'module_name'=>'Accounts',
'query'=>'',
'order_by'=>'accounts.name asc',
'offset'=>$offset,
'select_fields'=>array('id', 'name', 'email1'),
'max_results'=>$limit)
);
print_r($response);
$response = $client->__soapCall('logout',array('session'=>$session_id));
} catch (Exception $ex) {
echo $ex->getMessage();
}

Related

How to consume 3rd Party wsdl in magento2

I need to fetch Customer Information from a third party http://91.209.142.215:2803/SXYMAGENTO/?wsdl. I can connect it using SOAPUI and get desired response, but I am not able to connect it via Magento2. So far I tried
$requestData = [
'pageSize' => 1,
'pageNumber' => 1
];
$webservice_url = 'http://xx.xxx.xxx.xx:xxxx/MAGENTO/?wsdl';
$token = 'm31oix12hh6dfthmfmgk7j5k5dpg8mel';
$opts = array(
'http'=>array(
'header' => 'Authorization: Bearer '.$token)
);
$context = stream_context_create($opts);
$soapClient = new \SoapClient($webservice_url, ['version' => SOAP_1_2, 'context' => $context]);
$collection = $soapClient->RetrieveCollection($requestData);
print_r($collection);
die();
but this outputs Product data(maybe this is set as default), not customer data. Can anyone please point me in the right direction?
Finally, I figure this out and posting the answer so that it may help anyone craving a solution or fighting with a deadline.
Extend SoapClient and you can change Action, Request, and location
namespace Namespace\SoapModule\Api;
class CustomSoap extends \SoapClient
{
public function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$action = 'Your/Action/Obtainedfrom/SOAPAction';
$this->__last_request = $request; //Optional. You should do this if you dont want to get confused when print $request somewhere else in the module
return parent::__doRequest($request, $location, $action, $version, $one_way);
}
}
construct an object of above class wherever required
public function getCustomersDetails($page_size, $page_number)
{
$requestData = [
'pageSize' => $page_size,
'pageNumber' => $page_number
];
$data = $this->client->__soapCall('RetrieveCollection', [$requestData]);
return $this->client->__getLastResponse();
}
public function statementBalance()
{
$responsexml = $this->getCustomersDetails(1, 1);
$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $responsexml);
#$xml = simplexml_load_string($xml);
$json = json_encode($xml);
$responseArray = json_decode($json, true);
echo '<pre>';
print_r($responseArray);
}
Happy coding!

IPP CustomerAgg 401 on getAccountTransactions

The user flow I'm building for my application is that users can click on myAccounts and I'll display the getCustomerAccounts Results. That works perfectly. Then for each account I have a hyperlink called get transactions. That takes the user to a new page that should list out the transactions for that account. For some reason I'm always getting a 401 Code:ApplicationAuthenticationFailed when I call getAccountTransactions even though the previous call of getCustomerAccounts worked fine.
I'm confused as I imagine the authentication that is failing for the 401 is the exact same that works for the earlier call. Here is my code:
function get_transactions($accountID)
{
IntuitAggCatHelpers::GetOAuthTokens( $oauth_token, $oauth_token_secret);
$signatures = array( 'consumer_key' => OAUTH_CONSUMER_KEY,
'shared_secret' => OAUTH_SHARED_SECRET,
'oauth_token' => $oauth_token,
'oauth_secret' => $oauth_token_secret);
$txnStartDate = '2014-06-01'; // YYYY-MM-DD
$url = FINANCIAL_FEED_URL ."v1/accounts/$accountID/transactions?txnStartDate=$txnStartDate";
$action = 'GET';
$oauthObject = new OAuthSimple();
$oauthObject->setAction( $action );
$oauthObject->reset();
$result = $oauthObject->sign(
array
(
'path' => $url,
'parameters'=>
array
(
'oauth_signature_method' => 'HMAC-SHA1',
'Host' => FINANCIAL_FEED_HOST
),
'signatures'=> $signatures
)
);
$options = array();
$curlError = fopen('php://temp', 'rw+');
$options[CURLOPT_STDERR] = $curlError;
$options[CURLOPT_CUSTOMREQUEST] = $action;
$options[CURLOPT_URL] = $result['signed_url'];
$options[CURLOPT_HEADER] = 1;
$options[CURLOPT_VERBOSE] = 1;
$options[CURLOPT_RETURNTRANSFER] = 1;
$options[CURLOPT_SSL_VERIFYPEER] = true;
$options[CURLOPT_HTTPHEADER] = array
(
'Accept:application/json',
'Content-Type:application/json',
//'Content-Length:' . strlen( $postData ),
'Host:'. FINANCIAL_FEED_HOST,
//'Authorization:' . $result['header']
);
$curlError = fopen('php://temp', 'rw+');
$options[CURLOPT_STDERR] = $curlError;
$ch = curl_init();
curl_setopt_array( $ch, $options );
$responseText = urldecode( curl_exec( $ch ) );
echo $responseText;
//display curl http conversation
rewind( $curlError );
stream_get_contents( $curlError );
fclose( $curlError );
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
return $responseText;
}
Using same certificate(.p12) please try the above getAccountTransaction call from APIExplorer tool.
https://developer.intuit.com/apiexplorer?apiname=CustomerAccountData
Usage Ref - https://developer.intuit.com/docs/0020_customeraccountdata/007_firstrequest
If that works well, then compare the request header and URL with the same from your above code. 401 suggests authentication error which comes when your OAuth header is not properly formed/incorrect. Above comparison should sort this out.
PN - While uploading .p12 file(SAML) in ApiExplorer, sometiems, I get the following error msg.
"Your certificate is invalid. Please use base64 encoded CER format and make sure that the file is not empty". If you get the same then this can't be tested in ApiExplorer.
Thanks
This worked for me:
$result = $oauthObject->sign(array(
'path' => FINANCIAL_FEED_URL . 'v1/accounts/400037865348',
'parameters'=> array('oauth_signature_method' => 'HMAC-SHA1',
'Host'=> FINANCIAL_FEED_HOST,
'txnStartDate' => '2014-01-01',
'txnEndDate' => '2014-08-29'),
'signatures'=> $signatures));
Found at https://intuitpartnerplatform.lc.intuit.com/questions/797819-how-to-get-txnstartdate-into-my-url-without-breaking-oauth-authentication.

Facebook Php API: RSVP users to public event

I'm trying to use the facebook php api to rsvp users to a public event.
So far I can only get it to work for users who have already been invited.
I've tried:
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
Which does nothing.
My code as it stands is:
function rsvpEvent($event_id)
{
$fb_config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
);
$this->load->library('facebook', $fb_config);
$me = $this->facebook->api('/me/');
$user_id = $me['id'];
$path = $event_id.'/invited/'.$user_id;
$status = $this->facebook->api($path, 'GET');
$status = $status['data'][0]['rsvp_status'];
if($status === 'not_replied')
{
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
}
}
Has anyone got any ideas how I can get this to work?
$path = $event_id.'/attending?access_token='.$SOME_ACCESS_TOKEN;
You're not using the access token in your code, so I am uncertain of whether you skipped it when you copied it, If it's not in the code, then it may be that.
I retrieved the information here

Facebook Events by Cron Job Struggle

I finally have a working script to submit Facebook Events remotely, and have finished tackling the problem of converting my site's events RSS feed to the FB Events data. Utilizing RSS2HTML, I have added in a template-based call to send each event over two days before the event. Here's the code:
// Post Today's Game
if (strstr($template, "~~~TwitterToday~~~"))
{
//Build Arrays for games (when there are more than one per day...
$name = array( 'name' );
$desc = array( 'description' );
$venue = array( 'location' );
$s_time = array( 'start_time' );
$e_time = array( 'end_time' );
$pic = array( 'picture' );
$priv = array( 'privacy' );
//Build Main Facebook Array for All games to draw from
$fbook = array(
$name,
$desc,
$venue,
$s_time,
$e_time,
$pic,
$priv,
);
$template = str_replace("~~~TwitterToday~~~", "", $template);
$mycount = 1;
for ($y = 1; $y < count($rss_parser->Items)+1; $y++) //come back through events
{
//find each event's information to look for today's
$gamedate = date('n/j/Y', $rss_parser->Items[$y]->pubDate_t);
$todaysdate = date('n/j/Y');
$tomorrowsdate = date('n/j/Y',mktime(0,0,0,date('m'), date('d')+1, date('Y')));
$gametime = date('Y-m-d H:i:s',$rss_parser->Items[$y]->pubDate_t);
$title = $rss_parser->Items[$y]->title;
$description = $rss_parser->Items[$y]->description;
if ($gamedate == $tomorrowsdate) //found it
{
$mycount++;
//Fill the arrays
$name[] = $title;
$desc[] = $description;
$venue[] = "Home";
$s_time[] = $gametime;
$e_time[] = "";
$pic[] = "";
$priv[] = "OPEN";
}
} // end $y loop
//Populate Main Facebook Array
$fbook[0] = $name;
$fbook[1] = $desc;
$fbook[2] = $venue;
$fbook[3] = $s_time;
$fbook[4] = $e_time;
$fbook[5] = $pic;
$fbook[6] = $priv;
// Let's run with it
if (strpos($title,"Special Event") === false)
{
$page_id = "xxxxxxxxxxxxxx"; //First Page Id
}
else
{
$page_id = "xxxxxxxxxxxxxxxxxxx"; //Special Event Page Id
}
$app_id = "xxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://mydomain.com/feeds/rss2html.php"; // URL to THIS script
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
$code = $_REQUEST["code"];
if (empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'] . "&scope=create_event&scope=manage_pages";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if ($_REQUEST['state'] == $_SESSION['state'])
{
$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
$access_token = #file_get_contents($token_url);
$params = null;
parse_str($access_token, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
}
else
{
echo("The state does not match. You may be a victim of CSRF.");
}
//Now, getting the PAGE Access token, using the user access token
$page_token_url = "https://graph.facebook.com/" . $page_id . "?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);
// Parse the return value and get the Page access token
$resp_obj = json_decode($response,true);
$page_access_token = $resp_obj['access_token'];
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
This script works wonders when I call it from my browser, but when calling it from the cron job, I get an "Unable to open template" error in the rss2html script. In the past, I have always been able to solve this by making a separate script for the cron job, essentially using cURL to call the feed, and it works wonders.
Unfortunately, this technique won't work with a FaceBook Auth script, because it then returns the "The state does not match. You may be a victim of CSRF."
So, I'm between a rock and a hard place. Can't run the rss2html script without the cURL call, and the cURL call impedes the Facebook login. Here's a text version of the rss2html script as it stands, in case anyone wants to see it.
Can anyone think of a good workaround one way or t'other?
Thanks to DCMS, solution went thusly:
Using Facebook's Authentication Docs at https://developers.facebook.com/docs/authentication/ and adding '&scope=offline_access" to my call, I was able to grab some offline access tokens, and altered my above code thusly:
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
Thanks for the help, and I hope this helps anyone to come along with the same issue in the future!
Your solution might be to store the access token. Request offline_access and grab that token and hold onto it. Then use that token for your Graph API calls.

(iphone) inAppPurchase verifyReceipt using MKStoreKit

I am testing in app purchase with MKStoreKit.
I'm getting response's status 21002 and wonder why.
Do I need to set up a certificate or something to talk to apple server?
Below is the php code that MKStoreKit uses
<?php
$devmode = TRUE; // change this to FALSE after testing in sandbox
$receiptdata = $_POST['receiptdata'];
$udid = $_POST['udid'];
if($devmode)
{
$appleURL = "https://sandbox.itunes.apple.com/verifyReceipt";
}
else
{
$appleURL = "https://buy.itunes.apple.com/verifyReceipt";
}
$receipt = json_encode(array("receipt-data" => $receiptdata));
$response_json = do_post_request($appleURL, $receipt);
$response = json_decode($response_json);
file_put_contents('php://stderr', print_r($response->{'status'}, true));
file_put_contents('php://stderr', print_r($udid, true));
if($response->{'status'} == 0)
{
file_put_contents('php://stderr', print_r("yes", true));
error_log('udid: %s', $udid);
error_log('quantity: %d', $response->{'receipt'}->quantity);
echo ('YES');
}
else
{
echo ('NO');
}
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
?>
Please check Verify Purchase
MKStore Kit has a bug with sending receiptdata to server
You should base64 encode receiptData not asciiStringEncoding.
Used the following link's code to base64 and I get status 0.
Verify receipt for in App purchase