使用PHP后端的Web推送通知示例

6

我正在寻找一个使用JS代码和PHP后端的Web推送通知示例。 有人可以分享示例代码或教程吗?


如果你想使用服务,请查看 Pushpad PHP library。从 入门开始 开始,然后你可以看到一些示例关于收集订阅,最终你可以通过 PHP 库从你的 PHP 后端发送通知。 - collimarco
谢谢,我会尝试这个。如果您有GCM和APN的示例,请告诉我。 - kapilkarda
你的意思是从头开始吗?因为Pushpad在底层使用GCM、APNs和Mozilla autopush。 - collimarco
实际上,我计划启动一个类似于Pushpad的服务,这就是为什么我正在寻找相同的服务。 - kapilkarda
2个回答

0
  • 你应该生成VAPID密钥。
  • 然后你应该创建 "service-worker.js"。
  • 之后,你应该获取指定用户的密钥('endpoint'、'p256dh'、'auth')。
  • 最后,你可以使用PHP向用户发送推送通知。

这里 你可以找到 "service-worker.js" 和 PHP 脚本的示例。


0
这是一个使用 web-push-php 的基本示例:https://github.com/Minishlink/web-push-php-example 主要的 PHP 代码如下:
<?php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;

$auth = array(
    'VAPID' => array(
        'subject' => 'https://github.com/Minishlink/web-push-php-example/',
        'publicKey' => 'BCmti7ScwxxVAlB7WAyxoOXtV7J8vVCXwEDIFXjKvD-ma-yJx_eHJLdADyyzzTKRGb395bSAtxlh4wuDycO3Ih4',
        'privateKey' => 'HJweeF64L35gw5YLECa-K7hwp3LLfcKtpdRNK8C_fPQ', // in the real world, this would be in a secret file
    ),
);

$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
    $subscription['endpoint'],
    "Hello!", // payload
    $subscription['key'],
    $subscription['token'],
    true // flush
);
// handle eventual errors here, and remove the subscription from your server if it is expired

希望这能有所帮助 :)

1
欢迎提供解决方案的链接,但请确保您的答案即使没有链接也是有用的:在链接周围添加上下文,以便其他用户了解它的内容和原因,然后引用您链接的页面中最相关的部分,以防目标页面不可用。仅仅是一个链接的答案可能会被删除 - thewaywewere
4
这个例子不能立即运行,需要更多的说明。 - halfpastfour.am
@halfpastfour.am 这太多了,不适合在 SA 回答,所以放在了 GitHub 存储库中。 - t1gor
@t1gor,你误解了我的意思。更多的指令并不意味着整个代码库。 - halfpastfour.am
正如其他人所说,需要更多的上下文信息。我认为这不是完整的答案。 - The Vojtisek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接