### Install Go SDK Source: https://pusher.com/docs/beams/reference/server-sdk-go Use the go get command to add the Pusher Beams SDK to your project. ```bash go get github.com/pusher/push-notifications-go ``` -------------------------------- ### Install Pods Source: https://pusher.com/docs/beams/getting-started/ios/sdk-integration Install the dependencies specified in your Podfile and open the generated workspace. ```bash pod install ``` -------------------------------- ### Installation Source: https://pusher.com/docs/beams/reference/server-sdk-python Instructions on how to install the Beams Python server SDK using pip. ```APIDOC ## Installation The Beams Python server SDK is available on PyPi. You can install this SDK by using pip: ``` pip install pusher_push_notifications ``` ``` -------------------------------- ### Installation Source: https://pusher.com/docs/beams/reference/server-sdk-node Instructions on how to install the Beams Node.js server SDK using NPM or Yarn. ```APIDOC ## Installation You can install this SDK by using NPM or Yarn: ``` npm install @pusher/push-notifications-server --save ``` ``` yarn add @pusher/push-notifications-server ``` ``` -------------------------------- ### Publish an event using Python Source: https://pusher.com/docs/channels/server_api/overview This Python example shows how to publish an event. Install the 'pusher' library using pip. ```python # First, run 'pip install pusher' import pusher pusher_client = pusher.Pusher( app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER' ) pusher_client.trigger(u'my-channel', u'my-event', {u'message': u'hello world'}) ``` -------------------------------- ### Installation using Composer Source: https://pusher.com/docs/beams/reference/server-sdk-php Instructions on how to install the Beams PHP Server SDK using Composer. ```APIDOC ## Installation The Beams PHP Server SDK is available on Packagist. We recommend using Composer to install this SDK. ### Using Composer You can add this SDK to your project using composer, or by directly adding it to your `composer.json`: ```bash composer require pusher/pusher-push-notifications ``` Alternatively, add the following to your `composer.json`: ```json { "require": { "pusher/pusher-push-notifications": "^1.0" } } ``` ``` -------------------------------- ### Install Carthage Source: https://pusher.com/docs/beams/getting-started/ios/sdk-integration Install Carthage dependency manager using Homebrew. ```bash brew update && brew install carthage ``` -------------------------------- ### Publish an event using Node.js Source: https://pusher.com/docs/channels/server_api/overview This example shows how to publish an event using the Pusher Node.js library. Install the library using npm. ```javascript // First, run 'npm install pusher' const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", useTLS: true, }); pusher.trigger("my-channel", "my-event", { message: "hello world", }); ``` -------------------------------- ### Installation Source: https://pusher.com/docs/beams/reference/server-sdk-ruby Instructions on how to install the Pusher Beams Ruby Server SDK using RubyGems. ```APIDOC ## Installation The Pusher Beams Ruby server SDK is available on RubyGems. Add this line to your application’s Gemfile: ```ruby gem 'pusher-push-notifications' ``` ``` -------------------------------- ### Channels credentials example Source: https://pusher.com/docs/channels/library_auth_reference/auth-signatures Example credentials used for demonstration purposes. ```text key = '278d425bdf160c739803' secret = '7ad3773142a6692b25b8' ``` -------------------------------- ### Installation Source: https://pusher.com/docs/beams/reference/web Instructions for installing the Beams Web SDK using npm or Yarn, and how to include it via a script tag. ```APIDOC ## Installation ### npm/Yarn You can install this SDK by using npm/Yarn: ``` npm install @pusher/push-notifications-web ``` ``` yarn add @pusher/push-notifications-web ``` And import it into your application: ```javascript import * as PusherPushNotifications from "@pusher/push-notifications-web"; const beamsClient = new PusherPushNotifications.Client({ instanceId: "", }); beamsClient.start().then(() => { // Build something beatiful 🌈 }); ``` ### Script tag Or you can include the SDK directly via a script tag: ```html ``` And it will be available in the global scope as `PusherPushNotifications` ```html ``` ``` -------------------------------- ### Push Notification Started Webhook Example Source: https://pusher.com/docs/beams/reference/webhooks Represents the initial payload sent when a push notification publishing process begins. ```json { "publishId": "pubid-9e5f186a-93d9-4b79-af37-2a946d73e2b5", "status": "STARTED", "requestBody": { "interests": ["my_interest"], "webhookUrl": "http://mysite.com/push-webhook", "fcm": { "notification": { "title": "New Message", "body": "Alex Smith just sent you a new message" } }, "apns": { "aps": { "alert": { "title": "New Message", "body": "Alex Smith just sent you a new message" } } } } } ``` -------------------------------- ### Client.start() Source: https://pusher.com/docs/beams/reference/web Starts the SDK and ensures the device is registered with Beams. Returns a Promise. ```APIDOC ### .start Starts the SDK. Must be called at least once to ensure that the device is registered with Beams. #### Arguments None #### Returns A Promise that resolves to your PusherPushNotifications instance (allows for promise-chaining) #### Example ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: '', }) beamsClient.start() .then(() => { // Beams integration code here }); ``` ``` -------------------------------- ### Member Added Example JSON Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol A concrete example of a member added event. ```json { "event": "pusher_internal:member_added", "channel": "presence-example-channel", "data": "{ \"user_id\": \"11814b369700141b222a3f3791cec2d9\", \"user_info\": { \"name\": \"Phil Leggetter\", \"twitter\": \"@leggetter\", \"blogUrl\": \"http://blog.pusher.com\" } }" } ``` -------------------------------- ### Subscription Succeeded Example JSON Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol A concrete example of a successful presence channel subscription event. ```json { "event": "pusher_internal:subscription_succeeded", "channel": "presence-example-channel", "data": "{ \"presence\": { \"ids\": [\"11814b369700141b222a3f3791cec2d9\",\"71dd6a29da2a4833336d2a964becf820\"], \"hash\": { \"11814b369700141b222a3f3791cec2d9\": { \"name\":\"Phil Leggetter\", \"twitter\": \"@leggetter\" }, \"71dd6a29da2a4833336d2a964becf820\": { \"name\":\"Max Williams\", \"twitter\": \"@maxthelion\" } }, \"count\": 2 }" } ``` -------------------------------- ### Install Pusher Beams Python SDK Source: https://pusher.com/docs/beams/reference/server-sdk-python Install the Beams Python server SDK using pip. This command fetches and installs the latest version from PyPi. ```bash pip install pusher_push_notifications ``` -------------------------------- ### Initialize Pusher Client Source: https://pusher.com/docs/channels/using_channels/client-api-overview Examples of how to instantiate the Pusher client across different supported languages. ```javascript var pusher = new Pusher("YOUR_APP_KEY", options); ``` ```swift let pusher = Pusher(key: "YOUR_APP_KEY") ``` ```objective-c self.pusher = [[Pusher alloc] initWithKey:@"YOUR_APP_KEY"]; ``` ```java Pusher pusher = new Pusher("YOUR_APP_KEY"); ``` ```javascript window.Echo = new Echo({ broadcaster: "pusher", key: "YOUR_APP_KEY" }); ``` ```javascript var pusher = new Pusher("YOUR_APP_KEY"); ``` -------------------------------- ### Start Beams SDK Source: https://pusher.com/docs/beams/reference/web Initialize the SDK to register the device with Beams. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: '', }) beamsClient.start() => .then(() => { // Beams integration code here }); ``` -------------------------------- ### Channel Existence Example Source: https://pusher.com/docs/channels/server_api/webhooks Example of how to handle channel occupied and vacated webhooks. ```APIDOC # Channel Existence Example This example demonstrates how to process `channel_occupied` and `channel_vacated` events using the Pusher webhook library. ## Webhook Handler ### Method POST ### Endpoint `/your-webhook-endpoint` ### Request Body Example (This is a conceptual example, actual webhook payload will be sent by Pusher) ```json { "events": [ { "channel": "presence-your_channel_name", "name": "channel_occupied" }, { "channel": "presence-another_channel", "name": "channel_vacated" } ] } ``` ### Request Example (Ruby) ```ruby class PusherController < ApplicationController def webhook webhook = Pusher::WebHook.new(request) if webhook.valid? webhook.events.each do |event| case event["name"] when 'channel_occupied' puts "Channel occupied: #{event["channel"]}" when 'channel_vacated' puts "Channel vacated: #{event["channel"]}" end end render text: 'ok' else render text: 'invalid', status: 401 end end end ``` ### Response #### Success Response (200) - **text** (string) - 'ok' #### Error Response (401) - **text** (string) - 'invalid' ``` -------------------------------- ### Configure Cluster on Client-Side Source: https://pusher.com/docs/channels/miscellaneous/clusters Examples for initializing the Pusher client with a specific cluster on various platforms. ```javascript var pusher = new Pusher("APP_KEY", { cluster: "APP_CLUSTER", }); ``` ```swift let options = PusherClientOptions( host: .cluster("eu") ) let pusher = Pusher(key: "YOUR_APP_KEY", options: options) pusher.connect() ``` ```objective-c OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@"https://your.authendpoint/pusher/auth"]; OCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@"eu"]; PusherClientOptions *options = [[PusherClientOptions alloc] initWithOcAuthMethod:authMethod attemptToReturnJSONObject:YES autoReconnect:YES ocHost:host port:nil encrypted:YES]; self.pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY" options:options]; [self.pusher connect]; ``` ```java import com.pusher.client.Pusher; PusherOptions options = new PusherOptions(); options.setCluster("APP_CLUSTER"); Pusher pusher = new Pusher("APP_KEY", options); pusher.connect(); ``` ```javascript window.Echo = new Echo({ broadcaster: "pusher", key: "APP_KEY", cluster: "APP_CLUSTER", }); ``` ```csharp using PusherClient; public class Program { private static Pusher pusher; public static void Main(string[] args) { pusher = new Pusher("APP_KEY", new PusherOptions() { Cluster = "APP_CLUSTER", Encrypted = true }); } } ``` -------------------------------- ### Install Pusher Beams Node.js Server SDK using NPM Source: https://pusher.com/docs/beams/reference/server-sdk-node Install the SDK using NPM. This command adds the SDK as a dependency to your project. ```bash npm install @pusher/push-notifications-server --save ``` -------------------------------- ### Authorize Presence Channel in Node.js with Express Source: https://pusher.com/docs/channels/server_api/authorizing-users Set up an Express.js server to handle Pusher authorization for presence channels. This example includes basic setup for Express, CORS, and Pusher client initialization. Note: Authenticating every user is not recommended for production. ```javascript // npm install pusher // npm install express // npm install cors const express = require("express"); const cors = require("cors"); const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", useTLS: true, }); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cors()); app.post("/pusher/auth", function (req, res) { const socketId = req.body.socket_id; const channel = req.body.channel_name; const presenceData = { user_id: "unique_user_id", user_info: { name: "Mr Channels", twitter_id: "@pusher" }, }; // This authenticates every user. Don't do this in production! const authResponse = pusher.authorizeChannel(socketId, channel, presenceData); res.send(authResponse); }); const port = process.env.PORT || 5000; app.listen(port); ``` -------------------------------- ### Install CocoaPods Source: https://pusher.com/docs/beams/getting-started/ios/sdk-integration Install CocoaPods dependency manager using RubyGems. ```bash gem install cocoapods ``` -------------------------------- ### Installation Source: https://pusher.com/docs/beams/reference/server-sdk-swift Instructions on how to add the PushNotifications SDK to your Swift Package Manager dependencies. ```APIDOC ## Installation To include PushNotifications in your package, add the following to your `Package.swift` file. ```swift // swift-tools-version:4.0 import PackageDescription let package = Package( name: "YourProjectName", dependencies: [ ... .package(url: "git@github.com:pusher/push-notifications-server-swift.git", from: "1.0.0"), ], targets: [ .target(name: "YourProjectName", dependencies: ["PushNotifications", ... ]) ] ) ``` ``` -------------------------------- ### Configure Cluster on Server-Side Source: https://pusher.com/docs/channels/miscellaneous/clusters Examples for initializing the Pusher server SDK with a specific cluster. ```ruby require 'pusher' pusher = Pusher::Client.new( app_id: 'APP_ID', key: 'APP_KEY', secret: 'APP_SECRET', cluster: 'APP_CLUSTER' ); ``` ```php require __DIR__ . '/vendor/autoload.php'; $pusher = new Pusher\Pusher(APP_KEY, APP_SECRET, APP_ID, array( 'cluster' => 'APP_CLUSTER' )); ``` ```php // In config/broadcasting.php 'options' => [ 'cluster' => 'APP_CLUSTER' ], ``` ```javascript const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", }); ``` ```csharp using PusherServer; using System.Web.Mvc; using System.Net; using Your.Config; public class HelloWorldController : Controller { [httpPost] public ActionResult HelloWorld() { var options = new PusherOptions(); options.Cluster = Config.AppCluster; var pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, options); } } ``` ```python import pusher pusher_client = pusher.Pusher( app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER' ) ``` ```go package main import "github.com/pusher/pusher-http-go/v5" func main(){ pusherClient := pusher.Client{ AppID: "APP_ID", Key: "APP_KEY", Secret: "APP_SECRET", Cluster: "APP_CLUSTER", } } ``` ```java Pusher pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET"); pusher.setCluster("APP_CLUSTER"); ``` -------------------------------- ### Install Pusher Beams Node.js Server SDK using Yarn Source: https://pusher.com/docs/beams/reference/server-sdk-node Install the SDK using Yarn. This command adds the SDK as a dependency to your project. ```bash yarn add @pusher/push-notifications-server ``` -------------------------------- ### Install Beams Web SDK Source: https://pusher.com/docs/beams/reference/web Commands to add the SDK dependency to your project. ```bash npm install @pusher/push-notifications-web ``` ```bash yarn add @pusher/push-notifications-web ``` -------------------------------- ### Configure TokenProvider and Start Beams Client Source: https://pusher.com/docs/beams/reference/web Constructs a TokenProvider for authenticating with your Beams auth endpoint and starts the Beams client. This is required before setting a user ID. ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://example.com/pusher/beams-auth', queryParams: { userId: 'alice' }, headers: { 'Example-Header': 'value' }, credentials: 'include', }) const beamsClient = new PusherPushNotifications.Client({ instanceId: '', }) beamsClient.start() .then(() => beamsClient.setUserId('', tokenProvider)) .then(() => console.log('User ID has been set')) .catch(e => console.error('Could not authenticate with Beams:', e); ``` -------------------------------- ### Install Pusher PHP SDK with Composer Source: https://pusher.com/docs/beams/reference/server-sdk-php Use Composer to add the Pusher Push Notifications SDK to your project. This is the recommended installation method. ```bash composer require pusher/pusher-push-notifications ``` ```json "require": { "pusher/pusher-push-notifications": "^1.0" } ``` -------------------------------- ### Publish Event Examples Source: https://pusher.com/docs/channels/server_api/http-api Examples of publishing an event using the Pusher API in various programming languages. ```APIDOC ### Ruby Example ```ruby require 'pusher' pusher_client = Pusher::Client.new( app_id: 'APP_ID', key: 'APP_KEY', secret: 'APP_SECRET', cluster: 'APP_CLUSTER' ) pusher_client.trigger('my-channel', 'my-event', {:message => 'hello world'}) ``` ### PHP Example ```php require __DIR__ . '/vendor/autoload.php'; $pusher = new Pusher\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER')); $response = $pusher->trigger('my-channel', 'my-event', array( 'message' => 'hello world')); ``` ### Laravel Example (BroadcastOn) ```php // In the class implementing ShouldBroadcast public function broadcastOn() { return ['my-channel']; } ``` ### C# Example ```csharp using PusherServer; var options = new PusherOptions(); options.Cluster = "APP_CLUSTER"; var pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET", options); ITriggerResult result = await pusher.TriggerAsync( "my-channel", "my-event", new { message = "hello world" }); ``` ### Node.js Example ```javascript const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", }); pusher.trigger("my-channel", "my-event", { message: "hello world", }); ``` ### Python Example ```python import pusher pusher_client = pusher.Pusher(app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER') pusher_client.trigger(u'my-channel', u'my-event', {u'some': u'data'}) ``` ### Go Example ```go import "github.com/pusher/pusher-http-go/v5" pusherClient := pusher.Client{ AppID: "APP_ID", Key: "APP_KEY", Secret: "APP_SECRET", Cluster: "APP_CLUSTER", } data := map[string]string{"message": "hello world"} pusherClient.Trigger("my-channel", "my-event", data) ``` ``` -------------------------------- ### Example WebSocket Connection URL Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol An example of a complete WebSocket connection URL including query parameters for client identification, version, and protocol version. ```url ws://ws-ap1.pusher.com:80/app/APP_KEY?client=js&version=7.0.3&protocol=5 ``` -------------------------------- ### Example of Binding to All Events Globally Source: https://pusher.com/docs/channels/using_channels/events An example demonstrating how to bind a callback to all events on the Pusher connection. The callback receives the event name and its data payload. ```javascript var pusher = new Pusher("APP_KEY"); var callback = (eventName, data) => { console.log( `bind global: The event ${eventName} was triggered with data ${JSON.stringify( data )}` ); }; // bind to all events on the connection pusher.bind_global(callback); ``` -------------------------------- ### Query Application State via GET Source: https://pusher.com/docs/channels/server_api/http-api Use the generic GET method to query application state by providing a resource path and optional parameters. ```javascript pusher.get(resource, params) ``` ```php response = $pusher->get($resource, $params) ``` ```csharp IGetResult result = await pusher.GetAsync(string resource, object parameters); ``` ```javascript const res = await pusher.get({ path, params }); ``` -------------------------------- ### Install Beams Web SDK via Yarn Source: https://pusher.com/docs/beams/getting-started/web/sdk-integration Install the Beams Web SDK using Yarn. This package manager handles your Javascript dependencies. ```bash yarn add @pusher/push-notifications-web ``` -------------------------------- ### Example: Triggering a Client Event After Subscription (JavaScript) Source: https://pusher.com/docs/channels/using_channels/events This example shows how to trigger a client event ('client-someEventName') only after the subscription to the private channel is successfully established, using the 'pusher:subscription_succeeded' event. ```javascript var pusher = new Pusher("YOUR_APP_KEY"); var channel = pusher.subscribe("private-channel"); channel.bind("pusher:subscription_succeeded", () => { var triggered = channel.trigger("client-someEventName", { your: "data", }); }); ``` -------------------------------- ### Install Pusher Java Client via Maven Source: https://pusher.com/docs/channels/getting_started/android Add the dependency to your pom.xml file. ```xml com.pusher pusher-java-client 2.2.1 ``` -------------------------------- ### Example: Whispering an Event with Echo (JavaScript) Source: https://pusher.com/docs/channels/using_channels/events This example demonstrates using 'whisper' to send an event ('someeventname') with data after a subscription to a private channel is successful, within an Echo setup. ```javascript window.Echo = new Echo({ broadcaster: "pusher", key: "YOUR_APP_KEY", cluster: "eu", forceTLS: true, }); var channel = Echo.channel("private-channel"); var callback = (data) => {}; channel.bind("pusher:subscription_succeeded", () => { var triggered = channel.whisper("someeventname", { your: "data", }); }); ``` -------------------------------- ### Basic Auth Authorization Header Example Source: https://pusher.com/docs/beams/concepts/webhooks Shows the format of the Authorization header using Basic authentication. ```http Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= ``` -------------------------------- ### Install Pusher Beams SDK Source: https://pusher.com/docs/beams/reference/server-sdk-java-kotlin Add the SDK dependency to your project using Maven or Gradle. ```xml com.pusher push-notifications-server-java 1.1.1 ``` ```groovy dependencies { compile 'com.pusher:push-notifications-server-java:1.1.1' } ``` -------------------------------- ### Get Beams SDK Registration State Source: https://pusher.com/docs/beams/reference/web Use this to check the current registration state of the Beams SDK. The state determines if notifications can be received and guides the user interaction flow. ```javascript beamsClient .getRegistrationState() .then((state) => { let states = PusherPushNotifications.RegistrationState; switch (state) { case states.PERMISSION_DENIED: { // Notifications are blocked // Show message saying user should unblock notifications in their browser break; } case states.PERMISSION_GRANTED_REGISTERED_WITH_BEAMS: { // Ready to receive notifications // Show "Disable notifications" button, onclick calls '.stop' break; } case states.PERMISSION_GRANTED_NOT_REGISTERED_WITH_BEAMS: case states.PERMISSION_PROMPT_REQUIRED: { // Need to call start before we're ready to receive notifications // Show "Enable notifications" button, onclick calls '.start' break; } } }) .catch((e) => console.error("Could not get registration state", e)); ``` -------------------------------- ### User authentication request parameters Source: https://pusher.com/docs/channels/library_auth_reference/auth-signatures Example parameters received in a POST request for user authentication. ```text (socket_id = 1234.1234) ``` -------------------------------- ### Create a new Flutter project Source: https://pusher.com/docs/beams/getting-started/flutter/sdk-integration Initialize a new Flutter application using the CLI. ```bash flutter create example ``` -------------------------------- ### List Pusher Apps via CLI Source: https://pusher.com/docs/channels/pusher_cli/documentation After logging in, use this command to verify your setup by listing your Pusher applications. ```bash pusher channels apps list ``` -------------------------------- ### Publish Event (Go) Source: https://pusher.com/docs/channels/server_api/http-api This Go example shows how to trigger an event on a channel using the Pusher Go HTTP library. Initialize the client with your app credentials and provide the event data as a map. ```go import "github.com/pusher/pusher-http-go/v5" pusherClient := pusher.Client{ AppID: "APP_ID", Key: "APP_KEY", Secret: "APP_SECRET", Cluster: "APP_CLUSTER", } data := map[string]string{"message": "hello world"} pusherClient.Trigger("my-channel", "my-event", data) ``` -------------------------------- ### Initialize Podfile Source: https://pusher.com/docs/beams/getting-started/ios/sdk-integration Create an empty Podfile for your Xcode project. ```bash pod init ``` -------------------------------- ### Initialize Beams SDK Source: https://pusher.com/docs/beams/getting-started/web/sdk-integration Initialize the Beams SDK with your instance ID and start the client. This registers the device and logs the device ID. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: "YOUR_INSTANCE_ID", }); beamsClient .start() .then((beamsClient) => beamsClient.getDeviceId()) .then((deviceId) => console.log("Successfully registered with Beams. Device ID:", deviceId) ) .catch(console.error); ``` -------------------------------- ### Install Pusher CLI on MacOS Source: https://pusher.com/docs/channels/pusher_cli/installation Use Homebrew to install the Pusher CLI on MacOS systems. ```bash brew install pusher/brew/pusher ``` -------------------------------- ### Create a Pusher Connection Source: https://pusher.com/docs/channels/getting_started/ios Initialize the client with your app credentials and cluster information. ```swift let options = PusherClientOptions( host: .cluster("YOUR_CLUSTER") ) let pusher = Pusher(key: "YOUR_APP_KEY", options: options) pusher.connect() ``` ```objective-c OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@"https://your.authendpoint/pusher/auth"]; OCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@"YOUR_CLUSTER"]; PusherClientOptions *options = [[PusherClientOptions alloc] initWithOcAuthMethod:authMethod attemptToReturnJSONObject:YES autoReconnect:YES ocHost:host port:nil encrypted:YES]; self.pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY" options:options]; [self.pusher connect]; ``` -------------------------------- ### GET /resource Source: https://pusher.com/docs/channels/server_api/http-api Queries the application state by performing a GET request to a specified resource path. ```APIDOC ## GET /resource ### Description Queries the state of the application, such as active subscribers or users on a presence channel. ### Parameters #### Path Parameters - **resource** (string) - Required - The resource endpoint to be queried. #### Query Parameters - **params** (object) - Optional - Key/value pairs to be sent as query string parameters. ### Response #### Success Response (200) - **result** (object) - The state information returned by the queried resource. ``` -------------------------------- ### Valid Channel Name Example Source: https://pusher.com/docs/channels/using_channels/channels Example of a valid channel name string adhering to naming conventions. ```text foo-bar_1234@=,.; ``` -------------------------------- ### Open a Connection to Channels Source: https://pusher.com/docs/channels/getting_started/javascript Initialize the Pusher client using your application key and cluster. ```javascript var pusher = new Pusher("APP_KEY", { cluster: "APP_CLUSTER", }); ``` -------------------------------- ### Successful event response example Source: https://pusher.com/docs/channels/library_auth_reference/rest-api Example JSON response body when the info parameter is included in the request. ```json { "channels": { "presence-foobar": { "user_count": 42, "subscription_count": 51 }, "presence-another": { "user_count": 123, "subscription_count": 140 }, "another": { "subscription_count": 13 } } } ``` -------------------------------- ### GET Channel Stats Source: https://pusher.com/docs/channels/library_auth_reference/rest-api-deprecated Retrieves statistics for a specific channel. This method is deprecated and should be replaced with the new 'GET channel' endpoint. ```http GET /apps/[app_id]/channels/[channel_name]/stats ``` -------------------------------- ### Publish Started Hook (Deprecated) Source: https://pusher.com/docs/beams/reference/webhooks Indicates we have started publishing to the devices subscribed to the specified interests. This webhook format is deprecated. ```APIDOC ## Publish Started Hook (Deprecated) ### Description Indicates we have started publishing to the devices subscribed to the specified interests. This webhook format is deprecated and will be replaced by the newer webhook formats. ### Method POST ### Endpoint /webhooks ### Request Body - **publish_id** (string) - Required - Unique ID of the publish request that triggered this event. - **status** (string) - Required - String constant which indicates the webhook type. Equal to `STARTED`. - **request_body** (object) - Required - The body of the request sent to the Publish API when publishing this notification. ### Request Example ```json { "publish_id": "pubid-1df0b272-910b-43f7-9271-7345036aa739", "status": "STARTED", "request_body": { "message": { "apns": { "aps": { "alert": "Hello!" } } }, "topic": "your-topic" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the webhook reception. #### Response Example ```json { "status": "received" } ``` ``` -------------------------------- ### Initialize Pusher Beams Client Source: https://pusher.com/docs/beams/reference/server-sdk-node Construct a new Pusher Beams Client instance. You only need to do this once. Ensure you replace 'YOUR_INSTANCE_ID_HERE' and 'YOUR_SECRET_KEY_HERE' with your actual credentials. ```javascript const PushNotifications = require("${SDK_NAME}"); let beamsClient = new PushNotifications({ instanceId: "YOUR_INSTANCE_ID_HERE", secretKey: "YOUR_SECRET_KEY_HERE", }); ``` -------------------------------- ### Install Beams Web SDK via NPM Source: https://pusher.com/docs/beams/getting-started/web/sdk-integration Install the Beams Web SDK using NPM. This package manages your Javascript dependencies. ```bash npm install @pusher/push-notifications-web ``` -------------------------------- ### Initialize Beams Client via Module Source: https://pusher.com/docs/beams/reference/web Import and initialize the client in a module-based environment. ```javascript import * as PusherPushNotifications from "@pusher/push-notifications-web"; const beamsClient = new PusherPushNotifications.Client({ instanceId: "", }); beamsClient.start().then(() => { // Build something beatiful 🌈 }); ``` -------------------------------- ### Example Pusher Sign-in Event Payload Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol An example of the JSON payload for a `pusher:signin` event, including authentication signature and user data. ```json { "event": "pusher:signin", "data": { "auth": "::user::", "user_data": "{ \"id\": \"\", \"name\": \"Phil Leggetter\", \"twitter\": \"@leggetter\", \"blogUrl\":\"http://blog.pusher.com\" }" } } ``` -------------------------------- ### Initialize Beams Client Source: https://pusher.com/docs/beams/reference/server-sdk-python Construct a new Beams client instance using your instance ID and secret key. Obtain these credentials from the Pusher dashboard. ```python beams_client = PushNotifications( instance_id='YOUR_INSTANCE_ID_HERE', secret_key='YOUR_SECRET_KEY_HERE', ) ``` -------------------------------- ### Initialize Pusher Client Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol Instantiates a new Pusher client with your application key. This typically establishes the connection. ```javascript var pusher = new Pusher("APP_KEY"); ``` -------------------------------- ### Set Up Beams Token Provider (Java) Source: https://pusher.com/docs/beams/reference/android Configure the BeamsTokenProvider with your authentication URL and implement AuthDataGetter to provide necessary headers and query parameters for token requests. Use this when a user logs into your application. ```java BeamsTokenProvider tokenProvider = new BeamsTokenProvider( "", new AuthDataGetter() { @Override public AuthData getAuthData() { // Headers and URL query params your auth endpoint needs to // request a Beams Token for a given user HashMap headers = new HashMap<>(); // for example: // headers.put("Authorization", sessionToken); HashMap queryParams = new HashMap<>(); return new AuthData( headers, queryParams ); } } ); PushNotifications.setUserId("", tokenProvider, new BeamsCallback(){ @Override public void onSuccess(Void... values) { Log.i("PusherBeams", "Successfully authenticated with Pusher Beams"); } @Override public void onFailure(PusherCallbackError error) { Log.i("PusherBeams", "Pusher Beams authentication failed: " + error.getMessage()); } }); ``` -------------------------------- ### Publish to Interests with Java Source: https://pusher.com/docs/beams/getting-started/web/sdk-integration This Java example demonstrates publishing a notification to the 'hello' interest using the Beams SDK. Ensure correct initialization with instance and secret keys. ```java String instanceId = "YOUR_INSTANCE_ID_HERE"; String secretKey = "YOUR_SECRET_KEY_HERE"; PushNotifications beamsClient = new PushNotifications(instanceId, secretKey); List interests = Arrays.asList("hello"); Map publishRequest = new HashMap(); Map webNotification = new HashMap(); webNotification.put("title", "hello"); webNotification.put("body", "Hello world"); webNotification.put("deep_link", "https://www.pusher.com"); Map web = new HashMap(); web.put("notification", webNotification); publishRequest.put("web", web); beamsClient.publishToInterests(interests, publishRequest); ``` -------------------------------- ### Configure Pusher Beams Instance Source: https://pusher.com/docs/beams/reference/server-sdk-ruby Initialize the SDK with your instance ID and secret key obtained from the Pusher dashboard. ```ruby Pusher::PushNotifications.configure do |config| config.instance_id = 'YOUR_INSTANCE_ID_HERE' config.secret_key = 'YOUR_SECRET_KEY_HERE' end ``` -------------------------------- ### GET /apps/[app_id]/channels/[channel_name]/stats Source: https://pusher.com/docs/channels/library_auth_reference/rest-api-deprecated Retrieves statistics for a specific channel. Note: This method is deprecated; use GET channel instead. ```APIDOC ## GET /apps/[app_id]/channels/[channel_name]/stats ### Description Returns statistics for the given channel. This method is deprecated as of 2012-09. ### Method GET ### Endpoint /apps/[app_id]/channels/[channel_name]/stats ### Parameters #### Path Parameters - **app_id** (string) - Required - The ID of the application - **channel_name** (string) - Required - The name of the channel ### Response #### Success Response (200) - **occupied** (Boolean) - Whether or not there are currently any subscribers to this channel - **user_count** (Integer) - Number of distinct users currently subscribed to this channel (Presence channels only) - **connection_count** (Integer) - Number of connections currently subscribed to this channel (Beta feature) ``` -------------------------------- ### Initialize Beams Client Source: https://pusher.com/docs/beams/reference/server-sdk-go Construct a new Beams client instance using your instance ID and secret key obtained from the dashboard. ```go const ( instanceId = "YOUR_INSTANCE_ID_HERE" secretKey = "YOUR_SECRET_KEY_HERE" ) beamsClient, err := pushnotifications.New(instanceId, secretKey) if err != nil { fmt.Println("Could not create Beams Client:", err.Error()) } ``` -------------------------------- ### Get Presence Channel Member Count (JavaScript) Source: https://pusher.com/docs/channels/using_channels/presence-channels Access the 'count' property of the members object to get the number of users currently subscribed to the presence channel. ```javascript var count = presenceChannel.members.count; ``` -------------------------------- ### Publish an event using Java Source: https://pusher.com/docs/channels/server_api/overview This Java example shows how to publish an event. Add the pusher-http-java Maven dependency. ```java /* First, add this Maven dependency: com.pusher pusher-http-java 1.0.0 */ Pusher pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET"); pusher.setCluster("APP_CLUSTER"); pusher.trigger("my-channel", "my-event", Collections.singletonMap("message", "Hello World")); ``` -------------------------------- ### PHP JSONP Authentication Response (Example 2) Source: https://pusher.com/docs/channels/server_api/authorizing-users Another PHP example for JSONP authentication, similar to the previous one, ensuring the correct JavaScript content type and callback invocation. ```php if ( is_user_logged_in() ) { $pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID); $auth = $pusher->authorizeChannel($_GET['channel_name'], $_GET['socket_id']); $callback = str_replace('\\', '', $_GET['callback']); header('Content-Type: application/javascript'); echo($callback . '(' . $auth . ');'); } else { header('', true, 403); echo "Forbidden"; } ``` -------------------------------- ### Get a Specific Presence Channel Member (JavaScript) Source: https://pusher.com/docs/channels/using_channels/presence-channels Use the 'get' method with a user ID to retrieve a specific member object from the presence channel. The member object includes 'id' and 'info'. ```javascript var user = presenceChannel.members.get("some_user_id"); ``` -------------------------------- ### Publish Event with Pusher Go Source: https://pusher.com/docs/channels/server_api/http-api Initialize the Pusher client with your App ID, Key, Secret, and Cluster. Use the Trigger method to publish events. ```go import "github.com/pusher/pusher-http-go/v5" pusherClient := pusher.Client{ AppID: "APP_ID", Key: "APP_KEY", Secret: "APP_SECRET", Cluster: "APP_CLUSTER", } pusherClient.Trigger(channels, event, data) ``` -------------------------------- ### Example: Triggering an Event with Optional Data (Swift) Source: https://pusher.com/docs/channels/using_channels/events This Swift example triggers an event named 'myevent' with associated data on a private chat channel. The library automatically prefixes 'client-' if the event name is not already prefixed. ```swift let myPrivateChannel = pusher.subscribe("private-chat") myPrivateChannel.trigger(eventName: "myevent", data: ["foo": "bar"]) ``` -------------------------------- ### Connect to Pusher Channels Source: https://pusher.com/docs/channels/getting_started/android Initialize the Pusher client with your credentials and establish a connection. ```java import com.pusher.client.Pusher; ... PusherOptions options = new PusherOptions(); options.setCluster("APP_CLUSTER"); Pusher pusher = new Pusher("APP_KEY", options); pusher.connect(); ``` -------------------------------- ### Trigger Realtime Events with Python Source: https://pusher.com/docs/channels/getting_started/javascript-realtime-chart This Python snippet uses the Pusher SDK to trigger 'new-price' events every second. Install the SDK using 'pip install pusher'. Replace placeholder credentials with your actual app details. ```python # First, run 'pip install pusher' import pusher import random import time pusher_client = pusher.Pusher( app_id='APP_ID', # Replace with 'app_id' from dashboard key='APP_KEY', # Replace with 'key' from dashboard secret='APP_SECRET', # Replace with 'secret' from dashboard cluster='APP_CLUSTER', # Replace with 'cluster' from dashboard ssl=True ) # Trigger a new random event every second.In your application, # you should trigger the event based on real-world changes! while True: pusher_client.trigger('price-btcusd', 'new-price', { 'value': random.randint(0, 5000) }) time.sleep(1) ``` -------------------------------- ### Configuration Source: https://pusher.com/docs/beams/reference/server-sdk-ruby How to configure the Pusher Beams SDK with your instance ID and secret key. ```APIDOC ## Configuration ### `Class: PushNotifications` #### Arguments - **instance_id** (String) - Required - The unique identifier for your Push notifications instance. This can be found in the dashboard under “Credentials”. - **secret_key** (String) - Required - The secret key your server will use to access your Beams instance. This can be found in the dashboard under “Credentials”. #### Example ```ruby Pusher::PushNotifications.configure do |config| config.instance_id = 'YOUR_INSTANCE_ID_HERE' config.secret_key = 'YOUR_SECRET_KEY_HERE' end ``` ``` -------------------------------- ### Trigger Realtime Events with Node.js Source: https://pusher.com/docs/channels/getting_started/javascript-realtime-chart This Node.js snippet uses the Pusher SDK to trigger 'new-price' events every second. Install the SDK using 'npm install pusher'. Replace placeholder credentials with your actual app details. ```javascript // First, run 'npm install pusher' const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", // Replace with 'app_id' from dashboard key: "APP_KEY", // Replace with 'key' from dashboard secret: "APP_SECRET", // Replace with 'secret' from dashboard cluster: "APP_CLUSTER", // Replace with 'cluster' from dashboard useTLS: true, }); // Trigger a new random event every second. In your application, // you should trigger the event based on real-world changes! setInterval(() => { pusher.trigger("price-btcusd", "new-price", { value: Math.random() * 5000, }); }, 1000); ``` -------------------------------- ### Authorize Presence Channel in Go Source: https://pusher.com/docs/channels/server_api/authorizing-users Implement the authorization endpoint for a presence channel using Go. This example demonstrates reading the request body, authenticating the channel, and writing the response. Note: Authenticating every user is not recommended for production. ```go params, _ := ioutil.ReadAll(req.Body) presenceData := pusher.MemberData{ UserID: "1", UserInfo: map[string]string{ "twitter": "pusher", }, } // This authenticates every user. Don't do this in production! response, err := pusherClient.AuthorizePresenceChannel(params, presenceData) if err != nil { panic(err) } fmt.Fprintf(res, string(response)) ``` -------------------------------- ### Install PusherSwift via CocoaPods Source: https://pusher.com/docs/channels/getting_started/ios Add the library dependency to your Podfile. ```ruby pod 'PusherSwift' ``` -------------------------------- ### GET /devices/fcm/{device_id} Source: https://pusher.com/docs/beams/reference/device-api Retrieves details for a specific FCM device. ```APIDOC ## GET /device_api/v1/instances//devices/fcm/ ### Description Retrieves information about a registered FCM device. ### Method GET ### Endpoint https://.pushnotifications.pusher.com/device_api/v1/instances//devices/fcm/ ### Parameters #### Path Parameters - **DEVICE_ID** (string) - Required - The unique identifier for the device. ``` -------------------------------- ### Create Webpage with Realtime Chart Source: https://pusher.com/docs/channels/getting_started/javascript-realtime-chart This HTML and JavaScript code sets up a Google Chart and connects to Pusher to receive and display realtime data points. Ensure you replace 'APP_KEY' and 'APP_CLUSTER' with your actual Pusher credentials. ```html
```