Sending notifications from applications in your mobile devices is a common feature nowadays, but what if you can send notifications from your Alexa skills to Alexa-enabled devices? Now, with the release of the ProactiveEvents API, developers can send timely and relevant information to customers.
We have provided a pre-defined set of schemas that you can leverage to set up your skill service to use proactive events. Your skill can send proactive events information that conforms to a schema via the Skill Management API (SMAPI) as part of a skill manifest. Each schema has a predefined template that represents the text that Alexa reads back to the customer.
To make sure Alexa notifications provide relevant updates, customers have the ability to enable notifications on a per skill basis, which they can opt out of at any time using the Alexa app. When an Alexa notification is sent, customers see either a yellow light on devices without screens, or an on-screen banner for devices with screens that indicate that they have new notifications. Customers can ask Alexa to read their notifications when they want to hear them.
To add proactive events to your skill, follow the steps below:
To call the ProactiveEvents API, authenticate with Alexa as follows:
HTTP Header:
POST /auth/O2/token HTTP/1.1
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Request Body Syntax:
grant_type=client_credentials&client_id=(clientID)&client_secret=(clientSecret)&scope=alexa::proactive_events
1. function getTokenOptions(postLength){
2. // const TokenPostData = getTokenPostData();
3. return {
4. hostname: 'api.amazon.com',
5. port: 443,
6. path: '/auth/O2/token',
7. method: 'POST',
8. headers: {
9. 'Content-Type': 'application/x-www-form-urlencoded',
10. 'Content-Length': postLength // TokenPostData.length
11. }
12. }
13. }
14. function getTokenPostData() {
15. return 'grant_type=client_credentials&client_id=' + clientID + '&client_secret=' + clientSecret
16. + '&scope=alexa::proactive_events';
17. }
18. function getToken() {
19. return new Promise(resolve => {
20. const TokenPostData = getTokenPostData();
21. const req = https.request(getTokenOptions(TokenPostData.length), (res) => {
22. res.setEncoding('utf8');
23. let returnData = '';
24. res.on('data', (chunk) => { returnData += chunk; });
25. res.on('end', () => {
26. const tokenRequestId = res.headers['x-amzn-requestid'];
27. // console.log(`Token requestId: ${tokenRequestId}`);
28. resolve(JSON.parse(returnData).access_token);
29. });
30. });
31. req.write(TokenPostData);
32. req.end();
33. });
34. }
To locate ClientId and ClientSecret from the Alexa Developer Console, select the Build tab, scroll down to the Permissions section, and get these values from Alexa Skill Messaging at the bottom right.
Add the event schema to the skill for which you want to send notifications. Customers subscribed to receive notifications from the skill for these events will then receive an Alexa notification. These schemas are pre-defined by the Alexa Skills Kit.
You can use different schemas within your skill to represent different themes to your customers. Your skill cannot implement multiple instances of the same schema.
For example, if you have a weather skill, you can notify customers about weather alerts. Or if you have media skill, then consider adding proactive events to send notifications for when a new TV show becomes available.
The schema provided below is used to send weather alerts to all customers who enabled this skill and subscribed to its notification:
1. function getWeatherEvent() {
2.
3. let timestamp = new Date();
4. let expiryTime = new Date();
5. expiryTime.setMinutes(expiryTime.getHours() + 24);
6. let referenceId = "SampleReferenceId" + new Date().getTime(); // cross reference to records in your existing systems
7. const eventJson = {
8. "timestamp": timestamp.toISOString(),
9. "referenceId": referenceId,
10. "expiryTime": expiryTime.toISOString(),
11. "event":{
12. "name":"AMAZON.WeatherAlert.Activated",
13. "payload":{
14. "alert":{
15. "source": "localizedattribute:source",
16. "alertType": "HURRICANE"
17. }
18. }
19. },
20. "localizedattribute":[
21. {
22. "locale": "en-US",
23. "source": "Weather Channel"
24. },
25. {
26. "locale": "en-GB",
27. "source": "Britain Met Office"
28. },
29. {
30. "locale": "fr-FR",
31. "source": "Canal météo"
32. }
33. ],
34. "relevantAudience":{
35. "type":"Multicast",
36. "payload":{}
37. }
38. };
39. return eventJson;
40. }
In your skill manifest, you must define the event that your skill will provide to your customers. When specifying, you must include “alexa::devices:all:notifications:write” as a permission.
1. "permissions": [
2. {
3. "name": "alexa::devices:all:notifications:write"
4. }
5. ],
6. "events": {
7. "publications": [
8. {
9. "eventName": "AMAZON.WeatherAlert.Activated"
10. },
11. {
12. "eventName": "AMAZON.MessageAlert.Activated"
13. }
14. ],
15. "endpoint": {
16. "uri": "Your-ARN-Here"
17. },
18. "subscriptions": [
19. {
20. "eventName": "SKILL_PROACTIVE_SUBSCRIPTION_CHANGED"
21. }
22. ],
23. "regions": {
24. "NA": {
25. "endpoint": {
26. "uri": "Your-ARN-Here"
27. }
28. }
29. }
30. }
While your skill is in the development stage, you can test it by sending proactive events using the following development endpoint. Use the Notifications settings in the Alexa app to subscribe to your skill and receive test notifications.
To send events to your live customers, send proactive events to the live endpoint. Below endpoint is only available to you once your skill is certified. Be sure to select the appropriate endpoint for your region, as identified below:
1. function getProactiveOptions(token, postLength){
2. return {
3. hostname: 'api.amazonalexa.com', // api.eu.amazonalexa.com (Europe) api.fe.amazonalexa.com (Far East)
4. port: 443,
5. path: '/v1/proactiveEvents/' + (mode && mode === 'prod' ? '' : 'stages/development'), // mode: global var
6. method: 'POST',
7. headers: {
8. 'Content-Type': 'application/json',
9. 'Content-Length': postLength,
10. 'Authorization' : 'Bearer ' + token
11. }
12. };
13. }
14. function sendEvent(token) {
15. return new Promise(resolve => {
16. const ProactivePostData = JSON.stringify(getWeatherEvent());
17. const ProactiveOptions = getProactiveOptions(token, ProactivePostData.length);
18. const req = https.request(ProactiveOptions, (res) => {
19. res.setEncoding('utf8');
20. if ([200, 202].includes(res.statusCode)) {
21. console.log('successfully sent event');
22. } else {
23. console.log(`Error https response: ${res.statusCode}`);
24. console.log(`requestId: ${res.headers['x-amzn-requestid']}`);
25. if ([403].includes(res.statusCode)) {
26. resolve(`error ${res.statusCode}`);
27. }
28. }
29. let returnData;
30. res.on('data', (chunk) => { returnData += chunk; });
31. res.on('end', () => {
32. const requestId = res.headers['x-amzn-requestid'];
33. resolve("sent event");
34. });
35. });
36. req.write(ProactivePostData);
37. req.end();
38. });
39. }
With the Proactive Events API, developers can notify customers about upcoming shows or movies that are playing on their favorite channels. This could help improve engagement and retention of customers.
The ProactiveEvents API is available in all locales supported by Alexa. Review our technical documentation to get started and the following resources to learn more.