Nativescript - Onesignal rest Api - nativescript

I have push notifications on my app with onesignal sdk, but i´m having dificulty understanding how could i send with a large icon, i mean the one that stays on the left when the user receives the push(instead of showing a bell)...i know the icon must be transparent and have 256px x 256px. I´m sending the push using the rest api, but i don´t know where the problem is because nothing seems to work, here is my code:
public function sendMessage($messagePush){
$subtitle=["en" => $messagePush['message']];
$content = array(
"en" => $messagePush['contentJson']['tipoImovel'],
"large_icon" => public_path('img/icon.png')
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "id1",
"text" => "Ver"
));
$fields = array(
'app_id' => "myappid",
'included_segments' => array(
'All'
),
'data' => array(
"imovel" => $messagePush['contentJson']
),
'headings'=> $subtitle,
'contents' => $content,
'buttons' => $hashes_array
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: my autorization'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
I can receive the push, but the icon never appears, and there´s also another problem...the push always appear on the top tray instead of the popup "kind", for that manner below is also my code that is on my app.js:
if (application.android) {
application.on(application.launchEvent, (args) => {
try {
TnsOneSignal.startInit(application.android.context).setNotificationOpenedHandler(new TnsOneSignal.NotificationOpenedHandler({
// notificationOpened: function (result: com.onesignal.OSNotificationOpenResult) {
notificationOpened: function (result) {
const imovelAndroid = JSON.parse(result.stringify()).notification.payload.additionalData;
handleOpenURL(imovelAndroid);
}
})).init();
TnsOneSignal.setInFocusDisplaying(TnsOneSignal.OSInFocusDisplayOption.Notification);
TnsOneSignal.startInit(application.android.context).init();
}
catch (error) {
console.error('error', error);
}
});
}
If i remove the TnsOneSignal.setInFocusDisplaying(TnsOneSignal.OSInFocusDisplayOption.Notification); the popup style appears, but the buttons don´t navegate to my handleOpenURL function...but if i let it stay, it does navigate but the push is always on the tray.
Any tips? thanks for your time.
Regards

You will have to remove TnsOneSignal.setInFocusDisplaying(TnsOneSignal.OSInFocusDisplayOption.Notification); as that would force the notification to be the tray one. Default one is InAppAlert already.
You were resetting setNotificationOpenedHandler on second call to startInit. So if you remove the second startInit statement too you should be good.

Related

504 timeout error when sending many notifications using laravel +firebase messaging

I m sending notifications to many users at the same time and this is my code:
public function sendNotifications($title,$body,$image){
$SERVER_API_KEY ="my_api_key";
$tokens=DB::select("select * from fcm_token");
$token_array=[];
for( $i =0;$i<count($tokens);$i++){
array_push($token_array,$tokens[$i]->token);
}
$data = [
"registration_ids" =>
$token_array
,
"notification" => [
"title" => $title,
"body" => $body,
"image" => $image,
"sound"=> "default" // required for sound on ios
],
];
$dataString = json_encode($data);
$headers = [
'Authorization: key=' . $SERVER_API_KEY,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
curl_close($ch);
}
this function is executed after a form is filled by the admin who should give the title body and image to the back-end. after that, he must wait for the task to be complete (to make sure that everyone got the notification ). it was working like a charm before but right now after a long loading time, the server responds with 504 timeout. I know that I could have queued but would that solve the problem? wouldn't the Queue be stopped also by the same error? I m hosting the app in shared hosting (lws) and my max execution time is 60 seconds and can't increase it without paying more but I want to be sure where the problem resides.
I tried to test it with just 100 users, and it is working like a charm, but I need to send it to more than that since my users are more than 4000.
Google clound messaging supports sending to 1000 tokens at once.
$tokens=array_chunk($all_tokens,1000);
foreach($tokens as $thousand_tokens){
send_notification($thousand_tokens, $request->title.' Video added', 'New Video added in '.$cat->category->name, $cat->image_url, $data);
}
Above one is sample code. You can use that to modify your code.
function send_notification($tokens, $message, $description, $image, $data)
{
try{
$token_ids = array($tokens);
$apiKey = env('FCM_KEY');
$url = 'https://fcm.googleapis.com/fcm/send';
$msg =
array(
"registration_ids"=> $tokens,
"collapseKey"=> "com.notification",
"data"=> $data,
"notification"=> array(
"android"=> array(
"channelId"=> "Notifications-Channel",
"imageUrl"=> $image,
"sound"=> "sample.mp3"
),
"sound"=> "sample.mp3",
"channelId"=> "Notifications-Channel",
"android_channel_id"=> "Notifications-Channel",
"body"=> $description,
"title"=> $message
)
);
define("GOOGLE_API_KEY", $apiKey);
$headers = array(
'Authorization: key='.$apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}catch(Exception $e){
return 'at exception '.$e->getLine();
die('Error: '.$e->getMessage());
}
}

cURL error 60: SSL certificate problem: certificate has expired (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

I am using https://github.com/darthsoup/laravel-whmcs package for integration of WHMCS APIs I set up my WHMCS_API_URL, WHMCS_API_IDENTIFIER, WHMCS_API_SECRET and WHMCS_API_ACCESSKEY in .env file my Laravel Application I put code for fetching my clients by following code in my controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DarthSoup\Whmcs\WhmcsManager;
class WhmcsController extends Controller
{
//
private WhmcsManager $whmcsManager;
public function __construct(WhmcsManager $whmcsManager)
{
$this->whmcsManager = $whmcsManager;
}
public function index()
{
$result = $this->whmcsManager->client()->getClients();
dd($result);
}
}
I dump die the results but I am getting the above title error, I don't know to tackle it and even I also used cURL to fetch data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://billing.pakchamp.com/includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
http_build_query(
array(
'action' => 'DomainWhois',
// See https://developers.whmcs.com/api/authentication
'username' => 'WHMCS_API_IDENTIFIER',
'password' => 'WHMCS_API_SECRET',
'id' => '1',
'domain' => 'exampkhkjhkjhkjlehhkuhuhuih.com',
'responsetype' => 'json',
)
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
dd($response);
now using CURL I am getting false, please help me to solve this issue.

How can I send sms using codeigniter 4?

I'm trying to send SMS using CodeIgniter 4 but something went wrong any help or another way to send?
This is my code:
public function message()
{
/*Check submit button */
if ($this->request->getPost()) {
$email = $this->input->post('email');
$data=$this->users_model->getUserByEmail($email);
$phone=$data['phone'];
$authKey = "3456655757gEr5a019b18";
/*Multiple mobiles numbers separated by comma*/
$mobileNumber = $phone;
/*Sender ID,While using route4 sender id should be 6 characters long.*/
$senderId = "ABCDEF";
/*Your message to send, Add URL encoding here.*/
$message = "From Codeigniter 4";
/*Define route */
$route = "route=4";
/*Prepare you post parameters*/
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
/*API URL*/
$url="https://control.msg91.com/api/sendhttp.php";
/* init the resource */
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
/*,CURLOPT_FOLLOWLOCATION => true*/
));
/*Ignore SSL certificate verification*/
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
/*get response*/
$output = curl_exec($ch);
/*Print error if any*/
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo "Message Sent Successfully !";
}
}
After run the code above my web page return "Message Sent Successfully!", but nothing received in my phone. What is the problem?
What does the cURL call responds in the $output variable?
You already put the output in it and i think it will guide you to the reason why the SMS is not sending out to your phone.

Codeigniter reCaptcha v3 with cUrl

I have a form integrated with invisible reCaptcha.
Verification is performed on a function within the Controller.
The call to google is made using file_get_content and if no response is obtained, the call is made using curl.
This is the function
public function verify_captcha()
{
$recaptcha_response = $_POST['recaptchaResponse'];
log_message('info', $recaptcha_response);
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'My KEY';
$recaptcha_response = $_POST['recaptchaResponse'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha,true);
if(!$recaptcha)
{
// call curl to POST request
log_message('info', 'Call CURL');
$data = array( 'secret' => $recaptcha_secret, 'response' => $recaptcha_response);
//$curlConfig = array( CURLOPT_URL => $recaptcha_url, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $recaptcha_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$recaptcha = json_decode($response, true);
ob_start();
var_dump($recaptcha);
$result = ob_get_contents(); //or ob_get_clean()
log_message('info', $result);
if (array_key_exists('error-codes', $recaptcha))
{
log_message('error', 'Error reCaptcha '.$recaptcha['error-codes'][0]);
}
if ($recaptcha["success"] == '1')
{
if ($recaptcha["score"] >= 0.5)
{
}
}
else
{
log_message('error', 'Error reCaptcha no Success');
}
else
{
log_message('info', 'Call file_get_content');
}
}
These are the messages of the log file
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=6LfP26QUAAAAAHilJfguEgIcgOBkTg2soD7oCQIh&response=03AERD8XpOL7956DMd7dhiqasH4fK2iNjtBFBJdw3OynXGeAFBMmSqqtjsqXFW97rv-kD_H-y6aLrL1VLMkwg222Y7BoNnaB_zQ7y2NzXVtlIsWYwIw9BSbUdFdSylq4dNjO5j5Jo1xvjPotvMFuddnC5YVRC1wnk7HESqv8hvRU40x9pNpoQ-sIaXcAN8BdBgleXFufmmNoMzuh3PCvgT3RkIj1TsTs-ltM9LyVbLtFnFPbTkHZqpQjppMkHCcw87u3xqbr23EJkusR_U2vFwJTAJU9p-Z27sDuiKmEMsjJ2O1i3Wnxm9yq4HiEI2vnh420VDnPZEYRbXuLLSGhGuPciGQ3mtp07tjn265oyYbcFp2s9GentdUpPWRCxWfySTa6du7dzzSHkqPMKcPf6LmfVtICkTJf4y-w): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
INFO - 2020-03-18 09:54:31 --> Call CURL
INFO - 2020-03-18 09:54:31 --> NULL
The call to file_get_content shows error and returns nothing with curl.
What may be happening?
Thanks
If you totally, absolutely need to use file_get_contents, I'll share with you a helper function I have, which you can adapt to your own needs
function validate_recaptcha_response($recaptcha_response)
{
$api_url = 'https://www.google.com/recaptcha/api/siteverify';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$remoteip = '';
$data = array('secret' => $api_secret, 'response' => $recaptcha_response);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($api_url, false, $context);
$captcha_response = json_decode($result, true);
$r = array(
'success' => $captcha_response['success'],
'timestamp' => $captcha_response['challenge_ts'],
'hostname' => $captcha_response['hostname'],
'error_codes' => (isset($captcha_response['error-codes'])) ? $captcha_response['error-codes'] : null,
);
return $r;
}
I call this from any controller that gets the recaptcha response (the helper is autoloaded) using something like
$recaptcha_check = validate_recaptcha_response($var_where_you_store_the_recaptcha_response);
Please note that I'm adding the $options array to build a POST, defining a header, the method and use http_build_query() and stream_context_create() before file_get_contents() in order to query the data.
Please Follow the bellow Steps to integrate Recaptcha v3 in Codeigniter versions bellow 4 (3.1.9) or others.
Step #1: Create Recaptcha v3 for your domain and keep the site_key & secret_key.
[https://cloud.google.com/recaptcha-enterprise/docs/create-key][1]
Step #2: Add the bellow Javascirpt codes with replacement of your site_key & secret_key inside Head section of your Form page.
<script type="text/javascript">
var review_recaptcha_widget;
var onloadCallback = function() {
if($('#review_recaptcha').length) {
review_recaptcha_widget = grecaptcha.render('review_recaptcha', {
'sitekey' : 'recaptcha_site_key_v3',
'secretkey' : 'recaptcha_secret_key_v3'
});
}
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Step #3:Browse the page, you will see the new recaptcha in right bottom corner of page, Done, thats it.

Create product using Oauth & curl

Im trying to create product using RESTful Api. Achieved this functionality using RESTCLIENT firefox addon but failed using script. I can able to list products But im not able to create product using script. Getting access denied error. Can anyone help me?
Here is my script.
$url = 'http://magento.com/api/rest/products';
$method = 'POST';
# headers and data (this is API dependent, some uses XML)
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'oauth_signature_method : HMAC-SHA1',
'oauth_nonce : ilJuravy9KVYm6R',
'oauth_timestamp : 1363848967',
'oauth_consumer_key : xxx',
'oauth_consumer_secret : yyy',
'oauth_token : zzz',
'oauth_token_secret : xyz',
'oauth_signature : 4admodOkAj2pKwhO5Tk6TEjc7Rg%3D',
'oauth_verifier: mrr1350pp0j8hiyv31kzxhko97hyyuwx',
'oauth_version : 1.0',
);
$data = json_encode(
array(
'type_id' => 'simple',
'attribute_set_id' => 4,
'sku' => 'simple' . uniqid(),
'weight' => 1,
'status' => 1,
'visibility' => 4,
'name' => 'Simple Product',
'description' => 'Simple Description',
'short_description' => 'Simple Short Description',
'price' => 99.95,
'tax_class_id' => 0,
)
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
switch($method) {
case 'GET':
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
echo $response = curl_exec($handle);
echo $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
you have to generate 3 things mention below and other things are static like oauth_consumer_key,oauth_token etc.
1.timestmap
2.signature
3.nonce
i have generated all things see below code.
$nonce = substr(md5(uniqid('nonce_', true)),0,16);
$temprealm="http://magentohost/api/rest/products";
$realm=urlencode($temprealm);
$oauth_version="1.0";
$oauth_signature_method="HMAC-SHA1";
$oauth_consumer_key="lro2hnoh3c8luvhcr49j6qgygmyvw7e3";
$oauth_access_token="xbqe4wnu3zv357gimpdnuejvcbtk51ni";
$oauth_method="GET";
$oauth_timestamp=time();
$algo="sha1";
$key="sb88hfdihyg25ipt1by559yzbj2m3861&s7uhaheu8nrx961oxg6uc3os4zgyc2tm"; //consumer secret & token secret //Both are used in generate signature
$data="oauth_consumer_key=".$oauth_consumer_key."&oauth_nonce=".$nonce."&oauth_signature_method=".$oauth_signature_method."&oauth_timestamp=".$oauth_timestamp."&oauth_token=".$oauth_access_token."&oauth_version=".$oauth_version;
$send_data=$oauth_method."&".$realm."&".urlencode($data);
$sign=hash_hmac($algo,$send_data,$key,1); // consumer key and token secrat used here
$fin_sign=base64_encode($sign);
$curl = curl_init();
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization : OAuth realm='.$realm.', oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_nonce="'.$nonce.'", oauth_timestamp="'.$oauth_timestamp.'", oauth_consumer_key='.$oauth_consumer_key.', oauth_token='.$oauth_access_token.', oauth_signature="'.$fin_sign.'"'));
curl_setopt ($curl, CURLOPT_URL,$temprealm);
$xml=curl_exec($curl);

Resources