Saturday, June 2, 2018

Alexa Skill Account Linking- Python

For setting up account linking in Alexa Skill, follow the steps here.
Once setup is done, and intent handler needs to be implemented in the Python code: 

# --------------- Helpers that build all of the responses ----------------------

def build_user_authentication_response():
    return {
        "version": "1.0",
        "response": {
            "outputSpeech": {
                "type": "PlainText",
                "text": " Please use the companion app to authenticate on Amazon to start using this skill"
            },
            "card": {
                "type": "LinkAccount"
            },
            "shouldEndSession": false
        },
        "sessionAttributes": {}
    }

# --------------- Method that gets called when there is an intent request ----------------------

def on_intent(intent_request, session, context):
    """ Called when the user specifies an intent for this skill """

    print("on_intent requestId=" + intent_request['requestId'] +
          ", sessionId=" + session['sessionId'])

    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']
    if intent_name == "SayHello":
        return build_user_authentication_response()


# --------------- Main handler ------------------

def lambda_handler(event, context):
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print("event.session.application.applicationId=" + 
          event['session']['application']['applicationId'])

    """
    Uncomment this if statement and populate with your skill's application ID to
    prevent someone else from configuring a skill that sends requests to this
    function.
    """
    # if (event['session']['application']['applicationId'] !=
    #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
    #     raise ValueError("Invalid Application ID")

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'], event['context'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])

This will open a Login with Amazon screen where customers can sign in using their Amazon Account Credentials. Once logged-in successfully, the account is linked and next time onwards the user token comes as part of the session request.

Sample Request after Account Linking:

{
    "version": "1.0",
    "session": {
        "new": true,
        "sessionId": "session-id",
        "application": {
            "applicationId": "application-id"
        },
        "user": {
            "userId": "user-id",
            "accessToken": "access-token",
            "permissions": {
                "consentToken": "consent-token"
            }
        }
    },
    "context": {
        "AudioPlayer": {
            "playerActivity": "IDLE"
        },
        "Display": {},
        "System": {
            "application": {
                "applicationId": "application-id"
            },
            "user": {
                "userId": "user-id",
                "accessToken": "access-token",
                "permissions": {
                    "consentToken": "consent-token"
                }
            },
            "device": {
                "deviceId": "device-id",
                "supportedInterfaces": {
                    "AudioPlayer": {},
                    "Display": {
                        "templateVersion": "1.0",
                        "markupVersion": "1.0"
                    }
                }
            },
            "apiEndpoint": "https://api.eu.amazonalexa.com",
            "apiAccessToken": "api-access-token"
        }
    },
    "request": {
        "type": "LaunchRequest",
        "requestId": "request-id",
        "timestamp": "2018-06-03T05:22:36Z",
        "locale": "en-US",
        "shouldLinkResultBeReturned": false
    }
}

No comments:

Post a Comment