How to send push to specific member using SNS topic? - amazon-web-services

I am using AWS SNS to send a push notification, right now i am using publish method of aws-php-sdk to send push specific device. My requirement is sent push to thousands of members within 30 seconds. When i used publish method it takes 5min to send 1000 users.
I have read about topic it sends multiple members at once, but my scenario is i want to send push to specific users, not all topic users.
For example, i register 10,000 members in one topic, but from this 10,000 some time i am sending 9000, sometimes 1000 members.
So anyone has an idea how to send push using topic but specific members only.
I also think another case, every time i create new topic and register member to this topic and then send a message to him and then delete topic, but here every time when register member it is also taking time. So if you have an idea to register multiple members at once then it will also be helpful for me.
Below is my current code to send push.
$arn = "user arn";
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
$appArn = "application arn";
$sns->publish(array('Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));

I would recommend to use publishAsync() method.
$userArnCollection = array(
'arn:XXX',
'arn:YYY',
'arn:ZZZ',
);
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
foreach ($userArnCollection as $userArn) {
$sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $userArn
));
}
EDIT
Example with promise handling
$userArnCollection = array(
'arn:XXX',
'arn:YYY',
'arn:ZZZ',
);
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
$promises = array();
foreach ($userArnCollection as $userArn) {
$promises[] = $sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $userArn
));
}
$results = \GuzzleHttp\Promise\unwrap($promises);

After trying many solutions i am able to send thousands of notification within one minute, here i am showing code how i do it, I have done with php multicurl functionality, so i execute multiple parallel processes and all process send notification simultaneously.
Define multi curl and prepare URL to send notification
Suppose i have 5,000 members and i have array of it's token and other member details $device_type_ids_arr
I part of all member to 500 bunch, so each time curl execute it sends notification to 500 members
$_datas = array_chunk($device_type_ids_arr, 500);
/*initialise multi curl*/
$mh = curl_multi_init();
$handles = array();
/* Perform loop for each 500 members batch */
foreach ($_datas as $batchPart) {
$ch = curl_init();
$postData['devices'] = $batchPart;
$postData['push_content'] = $push_content;
$data_string = json_encode($postData);
curl_setopt($ch, CURLOPT_URL, base_url() . "EmailPipe/sendNotification/"); //your URL to call amazon service (Explain below)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: curl/7.39.0');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length:' . strlen($data_string))
);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// execute requests and poll periodically until all have completed
$isRunning = null;
do {
curl_multi_exec($mh, $isRunning);
} while ($isRunning > 0);
/* Once all execution are complete remove curl handler */
foreach ($handles as $ch) {
curl_multi_remove_handle($mh, $ch);
}
/* Close multi curl */
curl_multi_close($mh);
Function which is received curl request and send notification
function sendCurlSignal() {
require_once APPPATH . 'libraries/aws-sdk/aws-autoloader.php';
$pipeArr = json_decode(file_get_contents('php://input'), true);
$push_content = $pipeArr["push_content"];
$device_id_arr = $pipeArr["devices"];
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => "Amazon key",
'secret' => "Amazon secret",
'region' => "region like eu-west-1",
'profile' => "Amazon account user",
'debug' => false,
'http' => array('verify' => false)
));
$appArn = "SNS application arn";
$promises = $results = $retArr = array();
foreach ($device_id_arr as $key => $device_detail) {
$arn = $device_detail['arn']; /* SNS ARN of each device */
$token = $device_detail['token_id']; /* Registered token */
$userid = $device_detail['member_id'];
/* If you don't have arn then add arn for specific token in amazon */
if (empty($arn)) {
try {
$updatedArn = $sns->createPlatformEndpoint(array('PlatformApplicationArn' => $appArn, 'Token' => $token));
$arn = $newArn = isset($updatedArn['EndpointArn']) ? $updatedArn['EndpointArn'] : "";
//update member detail with new arn
if ($newArn != "" && $userid != "" && $token != "") {
/* You can update arn into database for this member */
}
} catch (Exception $e) {
/* Get error if any */
$errorMsg = $e->getMessage();
$newFile = fopen("error_arn_fail.txt", "a+");
fwrite($newFile, "Member Id:" . $userid . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
if (!empty($arn)) {
try {
$promises[$userid] = $sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \"' . $push_content . '\" } }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));
$promises[$userid]->arn = $arn;
$promises[$userid]->token = $token;
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_async_fail_signal.txt", "a+");
fwrite($newFile, $errorMsg . "\r\n");
fclose($newFile);
}
}
}
/* Broadcast push notification */
$results = \GuzzleHttp\Promise\settle($promises)->wait(TRUE);
/* if you want to get result of broadcast and sent message id then do following */
foreach ($results as $key => $value) {
if (isset($value['reason'])) {
/* Reason come in case of fail */
$message = $value['reason']->getMessage();
$token = (isset($promises[$key]->token)) ? $promises[$key]->token : "";
$arn = (isset($promises[$key]->arn)) ? $promises[$key]->arn : "";
if (empty($arn) || empty($token) || empty($key)) {
$newFile = fopen("error_empty_detail_result.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nArn:" . $arn . "\r\nToken:" . $token . "\r\n");
fclose($newFile);
}
/* Handle error */
if (strpos($message, "Endpoint is disabled") !== false && $token != "" && $arn != "") {
try {
$res = $sns->setEndpointAttributes(array(
'Attributes' => array("Token" => $token, "Enabled" => "true"),
'EndpointArn' => $arn
));
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_endpoint_disable.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nArn:" . $arn . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
if (strpos($message, "No endpoint found for the target arn specified") !== false && $token != "") {
try {
$updatedArn = $sns->createPlatformEndpoint(array('PlatformApplicationArn' => $appArn, 'Token' => $token));
$arn = $newArn = isset($updatedArn['EndpointArn']) ? $updatedArn['EndpointArn'] : "";
//update member detail with new arn
if ($newArn != "" && !empty($key) && $token != "") {
/* You can update arn into database for this member */
}
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_arn_fail.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
/* After handle error resed notification to this users */
if (!empty($arn)) {
try {
$publishRes = $sns->publish(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \"' . $push_content . '\" } }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));
$retArr[$key] = $publishRes->get("MessageId");
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_push_not_sent.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nARN:" . $arn . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
} else {
$retArr[$key] = $results[$key]['value']->get("MessageId");
}
}
/* All member data get into one array to perform database operation */
if (isset($retArr) && !empty($retArr)) {
/* in $retArr you get each member amazon message id */
}
}

Related

Unexpected Signature while obtaining user session token

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."&timestamp=".$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 . "&timestamp=" . $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);

Fetch product from amazon mws using product api

I have successfully posted product in amazon using amazon MWS Feeds API. Now i want to list those products using the Products API, But im facing some errors.
I run GetMatchingProductSample.php.
Caught Exception: Required parameter ASINList not found Response Status Code: 400 Error Code: MissingParameter Error Type: Sender Request ID: 8bb9c8d1-f48c-495c-be86-89492976b4a9 XML: SenderMissingParameterRequired parameter ASINList not found8bb9c8d1-f48c-495c-be86-89492976b4a9 ResponseHeaderMetadata: RequestId: 8bb9c8d1-f48c-495c-be86-89492976b4a9
Code:
<?php
require_once('.config.inc.php');
$serviceUrl = "https://mws-eu.amazonservices.com/Products/2011-10-01";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceProducts_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
APPLICATION_NAME,
APPLICATION_VERSION,
$config);
$request = new MarketplaceWebServiceProducts_Model_GetMatchingProductRequest();
$request->setSellerId(MERCHANT_ID);
// object or array of parameters
invokeGetMatchingProduct($service, $request);
function invokeGetMatchingProduct(MarketplaceWebServiceProducts_Interface $service, $request)
{
try {
$response = $service->GetMatchingProduct($request);
echo ("Service Response\n");
echo ("=============================================================================\n");
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebServiceProducts_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
As it says ASINList not found
You need to add these line of code after below line
$request->setSellerId(MERCHANT_ID);
Code needs to add:
$request->setMarketplaceId($marketplace_id);
$asin_list = new MarketplaceWebServiceProducts_Model_ASINListType();
$asins = array("ASIN1","ASIN2","ASIN3");
$asin_list->setASIN($asins);
$request->setASINList($asin_list);

Activation form does not fully work

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.

Add Netsuite Sales order items

I am getting this type of error:
=> i am getting error in the integration of the netsuite.
In sales order add the items in the netsuite so there are some error is define in above section my code is below please see the code add how to solve this problem.
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERRORi am gatting this type of error please help me
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERROR
my code is
include('NetSuiteService.php');
$service = new NetSuiteService();
if($order_items->netsuitid > 0){
$internal_Id = $order_items->netsuitid;
$emailCustomer = $order_items->user_email;
}
else{
$customer_Info = $order->get_customer_info($order->user_id);
$customer_information = array();
foreach($customer_Info as $customer_key => $customer_value){
if($customer_value->meta_key == 'first_name'){
$customer_information['first_name'] = $customer_value->meta_value;
}
if($customer_value->meta_key == 'last_name'){
$customer_information['last_name'] = $customer_value->meta_value;
}
}
$customer_information['email'] = $customer_Info->user_email;
//Add customer into net suit integration
$service = new NetSuiteService();
$customer = new Customer();
$customer->lastName = $customer_information['last_name'];
$customer->firstName = $customer_information['first_name'];
$customer->companyName = 'Company Name';
$customer->phone = '2222222222';
$customer->email = $customer_information['email'];
$emailCustomer = $customer_information['email'];
$request = new AddRequest();
$request->record = $customer;
$addResponse = $service->add($request);
if (!$addResponse->writeResponse->status->isSuccess) {
echo "You are already Registered with Netsuit.";
}
else {
$internal_Id = $addResponse->writeResponse->baseRef->internalId;
$order->insert_Customer($internal_Id,$order->user_id);
}
//End customer into net suit integration
}
//Add Product Information
/*$items = array();
foreach ( $order_items as $item_id => $item ) {
$itemRef = new nsRecordRef(array('internalId'=>$internal_Id));
$qty = $item['qty'];
if($item['type'] == 'line_item'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
if($item['type'] == 'fee'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
$SalesOrderItem->setFields($salesOrderItemFieldArray);
$items[] = $SalesOrderItem;
}
$salesOrderItemList = new nsComplexObject("SalesOrderItemList");
$salesOrderItemList->setFields(array(
"item" => $items
));
$salesOrderFields = array(
"orderStatus" => $order->status,
"entity" => '',
"getAuth" => true,
"shippingCost" => $order->order_shipping,
"shipMethod" => $order->payment_method,
"toBeEmailed" => true,
"email" => $emailCustomer,
"itemList" => $salesOrderItemList
);*/
$so = new SalesOrder();
//created Date
//$so->createdDate = $order->order_date;
//entity
$so->entity = new RecordRef();
$so->entity->internalId = $internal_Id;
$so->entity->name = $order->order_custom_fields['_billing_company'][0];
//Transaction Id
//$so->tranId = $order->order_custom_fields['Transaction ID'][0];
//Transaction Paid Date
//$so->tranDate = $order->order_custom_fields['_paid_date'][0];
//Source
$so->source = 'littlecrate';
//Created From
$so->createdFrom = 'littlecrate.com';
//Currency Name
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->currency = $order->order_custom_fields['_order_currency'];
$so->currencyName = $geoplugin->countryName;
$so->currency = $order->order_custom_fields['_order_currency'][0];
//Discount
$so->discountRate = $order->order_custom_fields['_order_discount'][0];
//Tax
$so->taxRate = $order->order_custom_fields['_order_tax'][0];
//email
$so->email = $order->billing_email;
//Status
//$so->orderStatus = $order->status;
//Billing Address
$so->billAddressList = array(
'billFirstname' => $order->order_custom_fields['_billing_first_name'][0],
'lastname' => $order->order_custom_fields['_billing_last_name'][0],
'billAddressee' => $order->order_custom_fields['_billing_address_1'][0],
'billAddr1' => $order->order_custom_fields['_billing_address_2'][0],
'billCountry' => $order->order_custom_fields['_billing_country'][0],
'billState' => $order->order_custom_fields['_billing_state'][0],
'billZip' => $order->order_custom_fields['_billing_postcode'][0],
'billPhone' => $order->order_custom_fields['_billing_phone'][0],
'billEmail' => $order->order_custom_fields['_billing_email'][0]);
//Shipping Address
$so->shipAddressList = array(
'shipFirstname' => $order->order_custom_fields['_shipping_first_name'][0],
'shipLastname' => $order->order_custom_fields['_shipping_last_name'][0],
'shipAddressee' => $order->order_custom_fields['_shipping_address_1'][0],
'shipAddr1' => $order->order_custom_fields['_shipping_address_2'][0],
'shipCity' => $order->order_custom_fields['_shipping_city'][0],
'shipState' => $order->order_custom_fields['_shipping_state'][0],
'shipZip' => $order->order_custom_fields['_shipping_postcode'][0],
'shiplPhone' => $order->order_custom_fields['_billing_phone'][0],
'shipEmail' => $order->order_custom_fields['_billing_email'][0]);
//Ship Date
//$so->shipDate = $order->order_custom_fields['Transaction ID'][0];
//Shipping Method
$so->shipMethod = $order->shipping_method;
//Shipping Charges
$so->shippingCost = $order->order_shipping;
//Shipping Tax Rate
$so->shippingTax1Rate = $order->order_shipping_tax;
//Payment Method
$so->paymentMethod = $order->payment_method;
//Sub Total
//$so->subTotal = $order->order_total;
//Discount Total(Cart Total)
//$so->discountTotal = $order->cart_discount;
//Tax Total
//$so->taxTotal = $order->order_tax;
//Total
//$so->total = $order->order_total;
//Product Listing
$arrItemsList = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
if($valueProduct['type'] == 'line_item'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
if($valueProduct['type'] == 'fee'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
$i++;
}
//print_r($arrItemsList);
$so->itemList->item = $arrItemsList;
/*$so->itemList = new SalesOrderItemList();
$soi = new SalesOrderItem();
$soi->item = new RecordRef();
$soi->item->internalId = 15;
$soi->quantity = 3;
$soi->price = new RecordRef();
$soi->price->internalId = $id;
$soi->amount = 55.3;
$so->itemList->item = array($soi);*/
$request = new AddRequest();
$request->record = $so;
//print_r($request);
$addResponse = $service->add($request);
print_r($addResponse);
exit;
if (!$addResponse->writeResponse->status->isSuccess) {
echo "ADD ERROR";
} else {
echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
}
+
I Complited Using The Help Of Saqib,
http://stackoverflow.com/users/810555/saqib
He is The Great Developer And Regarding Netsuite Information Please Contact To Saqib Thanks Man U Just Do It.
<?php
$order_date = date('Y-m-d H:i:s');
// create array of fields
$itemArr = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
//if you not have internal id of item in netsuuite then please add the item in the netsuite and try.
$netsuiteItemId = 'Your Item Internal id Which is in the Netsuite Item';
$itemArr[$i]['item']['internalId'] = $netsuiteItemId;
$itemArr[$i]['quantity'] = $valueProduct['qty'];
$i++;
}
if (!define('LF', "\n")) {
define('LF', "\n");
}
/* for use in formatting custom addresses since NetSuite converts to <br> */
//Billing Address Information
/* this example has the customer address info in a db record, just pulled into $row */
$billAddress = stripslashes($order->order_custom_fields['_billing_first_name'][0]) . ' ' . $order->order_custom_fields['_billing_last_name'][0] . LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_1'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_2'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_country'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_state'][0]) . ' - ' . $order->order_custom_fields['_billing_postcode'][0] . ', ' . LF;
$billAddress .= $order->order_custom_fields['_billing_phone'][0] . ', ' . $order->order_custom_fields['_billing_email'][0];
//Shipping Address Information
$shipAddress = stripslashes($order->order_custom_fields['_shipping_first_name'][0]) . ' ' . $order->order_custom_fields['_shipping_last_name'][0] . LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_1'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_2'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_city'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_state'][0]) . ', ' . $order->order_custom_fields['_shipping_postcode'][0] . ', ' . LF;
$shipAddress .= $order->order_custom_fields['_billing_phone'][0] .', '. $order->order_custom_fields['_billing_email'][0];
$purchaseOrderFields = array (
'entity' => array ('internalId' => $internal_Id, 'type' => 'customer'),
'shippingCost' => $order->order_shipping,
'shipMethod' => $order->payment_method,
'toBeEmailed' => true,
//'tranId' => $order->order_custom_fields['Transaction ID'][0],
//'tranDate' => date('Y-m-d H:i:s'),
'source' => 'littlecrate',
'createdFrom' => 'littlecrate.com',
'discountRate' => $order->order_custom_fields['_order_discount'][0],
'taxRate' => $order->order_custom_fields['_order_tax'][0],
'email' => $order->billing_email,
//'shipDate' => date('Y-m-d H:i:s'),
'shipMethod' => $order->shipping_method,
'shippingCost' => $order->order_shipping,
'shippingTax1Rate' => $order->order_shipping_tax,
'paymentMethod' => $order->payment_method,
//'taxTotal' => $order->order_tax,
//'total' => $order->order_total,
'billAddress' => $billAddress,
'shipAddress' => $shipAddress,
'itemList' => array (
'item' => $itemArr
)
);
$salesOrder = new nsComplexObject('SalesOrder');
$salesOrder ->setFields($purchaseOrderFields);
$addResponse = $myNSclient->add($salesOrder );
if (!$addResponse->isSuccess) {
echo "Order Information is Not Inserted Into The Netsuite. Please Contact to Administration.";
exit;
}
?>
You item List object doesn't seem in correct format. Your code should look like this
$itemArr = array();
foreach($order_items_product as $keyProduct =>$valueProduct){
$item = new SalesOrderItem();
$item->item = $valueProduct['product_id'];
$item->quantity = $valueProduct['qty'];
$itemArr[] = $item;
}
$itemList = new SalesOrderItemList();
$itemList->item = $itemArr;
$so->itemList->item = $itemList;

Could you explain me how i get news tickers from facebook into my app?

In my app. i get user's feed and user's news ticker. With first i have no questions, but with the second i have some troubles. How a can access to the ticker using php?
From my experience the ticker is just a shortened version of a users news feed using "story"
Here is a sample batch request "with only 1 request" i use to display ticker info from a users news feed.
user / home https://developers.facebook.com/docs/reference/api/user/#home
filtering results based on user lists https://developers.facebook.com/docs/reference/fql/stream_filter/
API Request:
<?php
$Ticker = $facebook->api('/me/home?fields=id,story%26'.$access_token.'');
echo '<pre>';
print_r($Ticker);
echo '</pre>';
?>
Batch API Request:
<?php
$Ticker = '/me/home?fields=id,story%26'.$access_token.'';
$queries = array(
array('method' => 'GET', 'relative_url' => ''.$Ticker.'')
);
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
$MEticker = json_decode($batchResponse[0]['body'], true);
echo '<pre>';
print_r($MEticker);
echo '</pre>';
?>
Thank you very much! I almost understood! :)
Another way to get ticker:
<?php
$res = $app->facebook->get_friends_news('me',$access_token);
print_r($res);
print "Ticker:"."\r\n";
foreach ($res['data'] as $value){
if (isset($value['story'])){
echo $value['story']."\r\n";
}
}
?>
where
<?php
function get_friends_news($user_id ='me',$token)<br/>
{
$url = $this->url_base_graph.$user_id.'/home?access_token='.$token;
$res = json_decode($this->httpQuery($url),true);
return $res;
}
?>
And:
<?php
function httpQuery($url, $method = 'GET', $post_data = array(), $CONNECTTIMEOUT = 30) {
// type of query
if ($method == 'POST')
$method = 1;
elseif ($method == 'GET')
$method = 0;
if ($this->access_token != false)
$url = $url . 'access_token=' . $this->access_token;
//echo $url;
//traverse array and prepare data for posting (key1=value1)
if (count($post_data)) {
foreach ($post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode('&', $post_items);
} else {
$post_string = '';
}
// echo $url;
//create cURL connection
$curl_connection = curl_init($url);
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, $CONNECTTIMEOUT);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_connection, CURLOPT_URL, $url);
curl_setopt($curl_connection, CURLOPT_POST, $method);
//set data to be posted
if ($post_string != '') {
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
}
//perform our request
$result = curl_exec($curl_connection);
//close the connection
curl_close($curl_connection);
return $result;
}?>