问题
I am implementing web push notifications using Onesigal API.
$fields = array(
'app_id' => "07aae1f0-xxxx-xxxx-aa7a-21c79c5b6733",
'include_player_ids'=>['57dd3f80-xxxx-xxxx-adb0-294bfa69621a'],
'contents' => array( "en"=> "message" )
);
$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: Basic YTdmYTYxYzYtN...tNjVlNzJkNDFlZmMz'));
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_CAINFO, dirname(__FILE__) . '/cacert.pem' );
$response = curl_exec($ch);
curl_close($ch);
Above code sends a push notification to the user if you know his player_id
. But suppose if some user visits my site and subscribes to push notifications and leaves.Later again he visits (he is already subscribed) and favs.(adds to favorite) a currently out of stock product.So how can I get player_id
of this user which I can store in "subs_fav"
table ?
id player_id product_id
1 57dd3f80...a69621a p097
When that product becomes available pushFav()
function will run which would notify the user that the product is now available and they can buy it but for that we should know the player_id of the user who favd. this product. I want to know how to find this player_id so that I can send it addToFav()
ajax call to store in "sub_fav"
table
回答1:
Found it! all you need is OneSignal.getUserId()
passed in a callback, which gives the user's player_id
upon querying. Before calling make sure user has actually subscribed.
OneSignal.isPushNotificationsEnabled(function(isEnabled) {
if (isEnabled) {
// user has subscribed
OneSignal.getUserId( function(userId) {
console.log('player_id of the subscribed user is : ' + userId);
// Make a POST call to your server with the user ID
});
}
});
回答2:
You can do it via Javascript: Just add this to your header.php or footer.php. Create your path in the controller to save it via database, etc.
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
autoRegister: false,
notifyButton: {
enable: true,
},
});
OneSignal.registerForPushNotifications();
});
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
var user_id = <?php echo (Sentry::getUser()->id) ?? 0; ?>;
var token = "{{ csrf_token() }}";
$.post("/user/storeUserPath", {
'user_id': user_id,
'_token': token,
'userId': userId,
});
});
});
</script>
来源:https://stackoverflow.com/questions/42919613/get-player-id-from-onesignal-on-page-load