Giter Club home page Giter Club logo

novu-php's Introduction

PHP SDK

Latest Stable Version License Total Downloads

The PHP Novu SDK and package provides a fluent and expressive interface for interacting with Novu's API and managing notifications.

Installation

PHP 7.2+ and Composer are required.

To get the latest version of Novu PHP SDK, simply require it:

composer require unicodeveloper/novu

Contents

Usage

To interact with the Novu SDK, you can instantiate it with either just an API key or with a configuration array that includes the API key and a custom base URI.

Using just the API key:

use Novu\SDK\Novu;

$novu = new Novu('YOUR_API_KEY_HERE');

// Sign up on https://web.novu.co and grab your API key from https://web.novu.co/settings

Using a configuration array:

If you need to specify a custom base URI (e.g., if you are pointing to a staging environment or a local development setup), you can pass an array with the apiKey and baseUri:

use Novu\SDK\Novu;

$config = [
    'apiKey' => 'YOUR_API_KEY_HERE',
    'baseUri' => 'https://custom-api-url.com/v1/'
];

$novu = new Novu($config);

// Get started with self-hosted Novu here https://docs.novu.co/overview/docker-deploy

Once the Novu instance is created, you can use it to perform all the actions that Novu's API provides.

EVENTS

Trigger an event - send notification to subscribers:

$response = $novu->triggerEvent([
    'name' => '<REPLACE_WITH_TEMPLATE_NAME_FROM_ADMIN_PANEL>',
    'payload' => ['customVariables' => 'Hello'],
    'to' => [
        'subscriberId' => '<SUBSCRIBER_IDENTIFIER_FROM_ADMIN_PANEL>',
        'phone' => '07983882186'
    ]
])->toArray();

Bulk Trigger events:

$response = $novu->bulkTriggerEvent([
    [
        'name' => '<REPLACE_WITH_TEMPLATE_NAME_FROM_ADMIN_PANEL>', 
        'to' => '<SUBSCRIBER_IDENTIFIER_FROM_ADMIN_PANEL>', 
        'payload' => ['customVariables' => 'Hello']
    ],
    [
        'name' => '<REPLACE_WITH_TEMPLATE_NAME_FROM_ADMIN_PANEL>', 
        'to' => '<SUBSCRIBER_IDENTIFIER_FROM_ADMIN_PANEL>', 
        'payload' => ['customVariables' => 'World']
    ],
    [
        'name' => '<REPLACE_WITH_TEMPLATE_NAME_FROM_ADMIN_PANEL>', 
        'to' => '<SUBSCRIBER_IDENTIFIER_FROM_ADMIN_PANEL>', 
        'payload' => ['customVariables' => 'Again']
    ]
])->toArray();

Trigger an event - send notification to topics

$response = $novu->triggerEvent([
    'name' => '<event_name>',
    'payload' => ['customVariables' => 'Hello'],
    'to' => [
        [
            'type' => 'Topic',
            'topicKey' => $topicKey
        ],
        [
            'type' => 'Topic',
            'topicKey' => $topicSecondKey
        ]
    ]
])->toArray();

Broadcast event to all existing subscribers:

$response = $novu->broadcastEvent([
    'name' => '<REPLACE_WITH_EVENT_NAME_FROM_ADMIN_PANEL>',
    'payload' => ['customVariables' => 'Hello'],
    'transactionId' => '<REPLACE_WITH_TRANSACTION_ID>'
])->toArray();

Cancel triggered event. Using a previously generated transactionId during the event trigger, this action will cancel any active or pending workflows:

$response = $novu->cancelEvent($transactionId);

SUBSCRIBERS

// Get list of subscribers
$subscribers  = $novu->getSubscriberList();

// Create subscriber & get the details of the recently created subscriber returned.
$subscriber = $novu->createSubscriber([
    'subscriberId' => 'YOUR_SYSTEM_USER_ID>',
    'email' => '<insert-email>', // optional
    'firstName' => '<insert-firstname>', // optional
    'lastName' => '<insert-lastname>', // optional
    'phone' => '<insert-phone>', //optional
    'avatar' => '<insert-avatar>', // optional
])->toArray();

// Bulk create subscribers
$response = $novu->bulkCreateSubscribers([
    [
        'subscriberId' => 'SUBSCRIBER_IDENTIFIER>',
        'email' => '<insert-email>', // optional
        'firstName' => '<insert-firstname>', // optional
        'lastName' => '<insert-lastname>', // optional
        'avatar' => '<insert-avatar>', // optional
    ],
    [
        'subscriberId' => 'SUBSCRIBER_IDENTIFIER>',
        'email' => '<insert-email>', // optional
        'firstName' => '<insert-firstname>', // optional
        'lastName' => '<insert-lastname>', // optional
        'avatar' => '<insert-avatar>', // optional
    ],
]);

// Get subscriber
$subscriber = $novu->getSubscriber($subscriberId)->toArray();

// Update subscriber
$subscriber = $novu->updateSubscriber($subscriberId, [
    'email' => '<insert-email>', // optional
    'firstName' => '<insert-firstname>', // optional
    'lastName' => '<insert-lastname>', // optional
    'phone' => '<insert-phone>', //optional
    'avatar' => '<insert-avatar>', // optional
])->toArray();

// Delete subscriber
$novu->deleteSubscriber($subscriberId);

// Update subscriber credentials
$response = $novu->updateSubscriberCredentials($subscriberId, [
    'providerId'  => '<insert-providerId>',
    'credentials' => '<insert-credentials>'
])->toArray();

// Update subscriber online status
$isOnlineStatus = true; // or false
$response = $novu->updateSubscriberOnlineStatus($subscriberId, $isOnlineStatus)->toArray();

// Get subscriber preferences
$preferences = $novu->getSubscriberPreferences($subscriberId)->toArray();

// Update subscriber preference
$novu->updateSubscriberPreference($subscriberId, $templateId, [
    'channel' => 'insert-channel',
    'enabled' => 'insert-boolean-value' // optional
]);

// Get a notification feed for a particular subscriber
$feed = $novu->getNotificationFeedForSubscriber($subscriberId);

// Get the unseen notification count for subscribers feed
$count = $novu->getUnseenNotificationCountForSubscriber($subscriberId);

// Mark a subscriber feed message as seen
$novu->markSubscriberFeedMessageAsSeen($subscriberId, $messageId, []);

// Mark message action as seen
$novu->markSubscriberMessageActionAsSeen($subscriberId, $messageId, $type, []);

TOPICS

// Create a Topic
$novu->createTopic([
  'key'  => 'frontend-users',
  'name' => 'All frontend users'
]);

// Fetch all topics
$novu->getTopics();

// Get a topic
$novu->topic($topicKey);

// Add subscribers to a topic
$subscribers = [
    '63e271488c028c44fd3a64e7',
    '3445'
];
$novu->topic($topicKey)->addSubscribers($subscribers);

// Remove subscribers from a topic
$subscribers = [
    '63e271488c028c44fd3a64e7',
    '3445'
];
$novu->topic($topicKey)->removeSubscribers($subscribers);

// Rename a topic
$novu->topic($topicKey)->rename($topicName);

ACTIVITY

// Get activity feed
$feed = $novu->getActivityFeed();

// Get activity statistics
$stats = $novu->getActivityStatistics()->toArray();

// Get activity graph statistics
$graphStats = $novu->getActivityGraphStatistics()->toArray();

INTEGRATIONS

// Get integrations
$novu->getIntegrations()->toArray();

// Create integration
$novu->createIntegration([
    'providerId' => '<insert->provider->id>',
    'channel' => '<insert->channel>',
    'credentials' => [
        // insert all the fields
    ],
    'active' => true,
    'check' => true
])->toArray();

// Get active integrations
$novu->getActiveIntegrations()->toArray();

// Get webhook support status for provider
$novu->getWebhookSupportStatusForProvider($providerId)->toArray();

// Update integration
$novu->updateIntegration($integrationId, [
    'active' => true,
    'credentials' => [
        // insert all the fields
    ],
    'check' => true
])->toArray();

// Delete integration
$novu->deleteIntegration($integrationId);

LAYOUTS

// filter layouts
$novu->filterLayouts(['pageSize' => 1])->toArray();

// Create layout
$novu->createLayout([
    'name' => '<insert-name-of-layout>',
    'identifier' => '<insert-identifier>',
    'content' => '<insert-html-content>',
])->toArray();

// Get a layout
$novu->getLayout('<insert-layout-id>')->toArray();

// Set Layout as default
$novu->setLayoutAsDefault('<insert-layout-id>');

// Update layout
$novu->updateLayout('<insert-layout-id>', [
    'name' => '<insert-name-of-layout>',
    'identifier' => '<insert-identifier>',
    'content' => '<insert-html-content>',
])->toArray();

// Delete layout
$novu->deleteLayout('<insert-layout-id>');

NOTIFICATIONS

// Get all notifications
$novu->getNotifications()->toArray();

// Get all notifications with query parameters
$queryParams = [
    'page' => 3
];
$novu->getNotifications($queryParams)->toArray();

// Get one notification 
$novu->getNotification($notificationId)->toArray();

// Get notification stats
$novu->getNotificationStats()->toArray();

// Get Notification graph stats
$novu->getNotificationGraphStats()->toArray();

// Get Notification graph stats with query parameters
$queryParams = [
    'days' => 5
];
$novu->getNotificationGraphStats($queryParams)->toArray();

NOTIFICATION TEMPLATES

// Get notification templates
$novu->getNotificationTemplates()->toArray();

// Create notification template
$novu->createNotificationTemplate([
  "name" => "name",
  "notificationGroupId" => "notificationGroupId",
  "tags" => ["tags"],
  "description" => "description",
  "steps" => ["steps"],
  "active" => true,
  "draft" => true,
  "critical" => true,
  "preferenceSettings" => preferenceSettings
])->toArray();

// Update notification template
$novu->updateNotificationTemplate($templateId, [
  "name" => "name",
  "tags" => ["tags"],
  "description" => "description",
  "identifier" => "identifier",
  "steps" => ["steps"],
  "notificationGroupId" => "notificationGroupId",
  "active" => true,
  "critical" => true,
  "preferenceSettings" => preferenceSettings
])->toArray();

// Delete notification template
$novu->deleteNotificationTemplate($templateId);

// Get notification template
$novu->getANotificationTemplate($templateId);

// Update notification template status
$novu->updateNotificationTemplateStatus($templateId, [
    'active' => true
])

NOTIFICATION GROUPS

// Create Notification group
$novu->createNotificationGroup([
    'name' => '<insert-name>'
]);

// Get Notification groups
$novu->getNotificationGroups()->toArray();

CHANGES

// Get changes
$novu->getChanges();

// Get changes count
$novu->getChangesCount()->toArray();

// Apply changes
$novu->applyBulkChanges([
    'changeIds' = [
        '<insert-all-the-change-ids>'
    ]
])->toArray();

// Apply change
$novu->applyChange($changeId, []);

ENVIRONMENTS

// Get current environment
$novu->getCurrentEnvironment()->toArray();

// Create environment
$novu->createEnvironment([
    'name' => '<insert-name>',
    'parentId' => '<insert-parent-id>' // optional
])->toArray();

// Get environments
$novu->getEnvironments()->toArray();

// Update environment by id
$novu->updateEnvironment($envId, [
  "name" => "name",
  "identifier" => "identifier",
  "parentId" => "parentId"
]);

// Get API KEYS
$novu->getEnvironmentsAPIKeys()->toArray();

// Regenerate API KEYS
$key = $novu->regenerateEnvironmentsAPIKeys()->toArray();

// Update Widget Settings
$novu->updateWidgetSettings([
    'notificationCenterEncryption' => true
]);

FEEDS

// Create feed
$novu->createFeed([
    'name' => '<insert-name-for-feed>'
]);

// Get feeds
$novu->getFeeds()->toArray();

// Delete feed
$novu->deleteFeed();

MESSAGES

// Get messages
$novu->getMessages([
    'page' => 1,
    'channel' => ['<insert-channel>'],
]);

// Delete message
$novu->deleteMessage();

EXECUTION DETAILS

// Get execution details
$novu->getExecutionDetails([
    'notificationId' => '<insert-notification-id>',
    'subscriberId'   => '<insert-subscriber-id>'
])->toArray();

TENANTS

// Create tenant
$novu->createTenant([
    'identifier' => '<identifier>',
    'name' => '<name>',
]);

// Get tenants
$novu->getTenants()->toArray();

Validate the MX Record setup for Inbound Parse functionality

// Validate MX Record for Inbound Parse
$novu->validateMXRecordForInboundParse()->toArray();

For more information about these methods and their parameters, see the API documentation.

Contributing

Feature requests, bug reports and pull requests are welcome. Please create an issue.

Support and Feedback

Be sure to visit the Novu official documentation website for additional information about our SDK. If you need additional assistance, join our Discord server here.

License

Novu PHP SDK was created by Prosper Otemuyiwa under the MIT license.

novu-php's People

Contributors

2002bishwajeet avatar atharva1723 avatar eazybright avatar fadkeabhi avatar isaiahdahl avatar kraynel avatar lekso-surameli avatar ogunsakin01 avatar stacksharebot avatar sumitsaurabh927 avatar theabhishekin avatar unicodeveloper avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

novu-php's Issues

cancelEvent not working

the cancelEvent function in ManagesTriggers results in an error. In its body, delete returns a boolean, as the response body of the delete request is empty. When this boolean value $response is used to create a Trigger object, an error is thrown, since Trigger expects an array, not a boolean.

Novu Package Not Found

What is this issue about ?

After requiring this package in a project (a php project and in a php framework), instantiating the Novu class as mentioned in the README file throws an error saying that the Novu\SDK\Novu page isn't found.

How can it be reproduced

Step 1: require this package in a php project - composer require unicodeveloper/novu as stated in the README
Step 2: Import the name space in a php file use Novu\SDK\Novu;
Step 3: Instantiate the Novu class $novu = new Novu(<INSERT_API_KEY_HERE>);

Expected error message in a PHP project (without framework): Fatal error: Uncaught Error: Class "Novu\SDK\Novu" not found

Useful files/attachments

Screenshot 2023-01-09 at 19 19 15

Investigation/Possible Solution

Screenshot 2023-01-09 at 19 30 13

From the above screenshot (In the composer.json file) where the project src directory is been autoloaded i.e in the psr-4 autoload object, there seems to be a wrong-spelling of the alias names "Nova\\SDK\\" where the src directory is aliased, I would assume that it's supposed to be "Novu\\SDK\\" and not "Nova\SDK\" - key difference here seems to be Nova and Novu.

For me, I think this is just a mistake since the project classes and actions uses a different namespace as seen below:

Screenshot 2023-01-09 at 19 34 06
Screenshot 2023-01-09 at 19 34 21

The namespaces used are incorrect since the alias in the composer.json has a different spelling with the class namespaces as seen above.

Please let me know if I am wrong or if everything is done as expected and I will try to continue investigating what might have gone wrong with my installation.

Thanks for the good work!

Add Missing Methods for Environments

Some endpoints of the following section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Environments

Some of these methods may already exist. 
If so no need to change/update them, just point out that they already exist and we will close the issue.

This is just to bring every SDK we have on par with all the methods available.

Check all the endpoints here and add the missing ones.

Add Exponential Retry Mechanism with Idempotency Headers

In order to enhance the resilience and reliability of our SDK, we would like to introduce an Exponential Retry mechanism for retrying failed requests. Additionally, to ensure the idempotent processing of requests, it's vital to incorporate support for providing an Idempotency Key as per the draft specified in the HTTP Idempotency Key Header Field.

The key requirements for this implementation include:

  1. Exponential Retry Mechanism:

    • The SDK should retry failed requests following an exponential backoff strategy to minimize the contention and impact on the systems involved.
    • The SDK should ensure that the retry mechanism is configurable (e.g., max retries, initial delay, maximum delay).
  2. Idempotency Key Provisioning:

    • The SDK should allow for either automatic or manual provisioning of an Idempotency Key for each request.
    • The Idempotency Key should conform to either CUID, ULID, or UUID formats as specified in the draft.
    • The Idempotency Key should be included in the HTTP Header as Idempotency-Key and following the standards outlined in the draft.
  3. Configuration and Documentation:

    • The SDK should provide configuration options for enabling/disabling the Exponential Retry mechanism and Idempotency Key provisioning.
    • Comprehensive documentation should be provided explaining the configuration options, operational behavior, and the benefits of using the Exponential Retry mechanism along with Idempotency Keys.

Acceptance Criteria:

  • Implementation of the Exponential Retry mechanism with configurable parameters.
  • Provisioning of Idempotency Keys, either automatically or manually, conforming to specified formats (CUID, ULID, or UUID).
  • Adequate unit and integration testing to ensure the robustness and reliability of the implemented features.
  • Comprehensive documentation on the usage and configuration of the Exponential Retry mechanism and Idempotency Key provisioning.
  • Adherence to the specifications outlined in the HTTP Idempotency Key Header Field draft.

Update: You can reference the go-lang library to keep the method signature and configuration the same.
novuhq/go-novu#62

Please refer to the draft for further details on the HTTP Idempotency Key Header Field and ensure adherence to the specified standards while implementing this feature in the SDK.

Add Missing Methods for Changes

Some endpoints of the following section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Changes

Some of these methods may already exist. 
If so no need to change/update them, just point out that they already exist and we will close the issue.

This is just to bring every SDK we have on par with all the methods available.

Check all the endpoints here and add the missing ones.

Add Missing Methods for Execution details

Some endpoints of the following section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Execution details

Some of these methods may already exist. 
If so no need to change/update them, just point out that they already exist and we will close the issue.

This is just to bring every SDK we have on par with all the methods available.

Check all the endpoints here and add the missing ones.

Setup GitHub Workflow for Running Unit Tests

In order to ensure the stability and reliability of our codebase, it is essential to have automated unit tests running for each push and pull request. Currently, our repository lacks a GitHub Actions workflow to run unit tests, and this needs to be addressed to maintain code quality and catch issues early.

Suggested Solution:

  1. Create a new workflow file in .github/workflows/ directory.
    Filename: run-unit-tests.yml

  2. Configure the workflow to be triggered on every push and pull_request event to the main branch.

  3. Define job steps:
    Checkout the repository.
    Setup the environment/java runtime.
    Install dependencies.
    Run the unit tests.

[NV-PHP-3] API 🚀: Manage Layouts

There is no section to manage layouts from this SDK. Add the necessary action and methods to make it possible.

API references and methods/features required.

NV-PHP-8] API 🚀: Add Workflow Feature

The endpoints of the workflow section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Workflows feature.

Add Missing Methods for Inbound Parse

Some endpoints of the following section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Inbound Parse

Some of these methods may already exist. 
If so no need to change/update them, just point out that they already exist and we will close the issue.

This is just to bring every SDK we have on par with all the methods available.

Check all the endpoints here and add the missing ones.

Add Missing Methods for Feeds

Some endpoints of the following section can't be hit from this SDK.

We would like to ensure that all endpoints can be hit. For this issue, we would like to build out the Feeds

Some of these methods may already exist. 
If so no need to change/update them, just point out that they already exist and we will close the issue.

This is just to bring every SDK we have on par with all the methods available.

Check all the endpoints here and add the missing ones.

Add User Agent Header

Add the user-agent request header to every call in this sdk.

Example:

headers: {
Authorization: Bearer ${ApiKey},
"User-Agent": novu/${sdk}@${version},
},

Why? (Context)

Having request headers in the SDKs will help us in monitoring which SDK is mostly used by the community and customers. It will help us make the decisions in the future on which SDKs to officially support in the future.

Refactor Methods, Add Type Declarations, and Comments

This issue aims to enhance the codebase by refactoring methods to utilize a private getActivity function for fetching Activity data. Additionally, type declarations and comments will be added to improve code readability and maintainability.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.