def handle()

in src/aws-lambda/alexa-skill-lambda/alexa-skill-lambda.py [0:0]


    def handle(self, handler_input):
        """
        Handle this intent. Results are provided using response_builder.
        Args:
            handler_input (HandlerInput): The handler_input dict used to call the intent handler.
        Returns:
            Response
        """
        logger.info(
            f"Calling CheckoutIntentHandler {json.dumps(handler_input.request_envelope.to_dict(), default=str, indent=2)}")

        basket_total = get_cart_total(handler_input)
        user_details = get_cognito_user_details(handler_input)
        user_email = user_details['email']

        if len(AMAZON_PAY_MERCHANT_ID) == 0:

            speak_output = f"Your total is ${basket_total}. "
            # This happens if AMAZON_PAY_MERCHANT_ID not set up in .env file
            speak_output += "This demo has no merchant set up so we'll just finish up now."

            if user_details['cognito_loaded']:
                name = user_details.get('custom:profile_first_name', '')
                speak_output += f" Hope to see you again soon {name}. "
            else:
                speak_output += " Thanks for playing! "

            return (
                handler_input.response_builder
                    .speak(speak_output)
                    .set_should_end_session(True)
                    .response
            )

        else:

            """
            Below is an example of further attributes you could specify, to override the default.

            user_details = get_cognito_user_details(handler_input)
            basket_id = get_basket_id(handler_input)

            seller_billing_agreement_attributes=SellerBillingAgreementAttributes(
                version="2",
                seller_billing_agreement_id=user_details['username'] + '-' + basket_id,
                store_name="C store demo",
                custom_information="A demonstration of Alexa Pay integration"
            )

            billing_agreement_type = BillingAgreementType("CustomerInitiatedTransaction") # BillingAgreementType("MerchantInitiatedTransaction") #

            billing_agreement_attributes = BillingAgreementAttributes(
                version="2",
                billing_agreement_type=billing_agreement_type, # EU/UK only
                seller_note="C store demo payment sandbox only",
                seller_billing_agreement_attributes=seller_billing_agreement_attributes
            )
            """

            # Let us save our session as a token for Pay, because by handing over to Pay, the Alexa session has ended.
            # Alternatively, you could save these in a backend DB.
            correlation_token = json.dumps(handler_input.attributes_manager.session_attributes)

            pay_request = SetupAmazonPayRequest(
                version="2",
                seller_id=AMAZON_PAY_MERCHANT_ID,
                country_of_establishment="US",
                ledger_currency="USD",
                checkout_language="en-US",
                sandbox_mode=True,
                # Note that we also send an email ourselves according to that saved against the Cognito user.
                # Here, for testing purposes, we allow you to specify the email of your testing account
                # in the environment variables (see the README.md).
                sandbox_customer_email_id=user_email,
                # extra params could be added here: billing_agreement_attributes=billing_agreement_attributes,
                need_amazon_shipping_address=False)

            pay_setup_directive = SendRequestDirective(
                name='Setup',
                token=correlation_token,
                payload=pay_request
            )

            logger.info(f"SendRequestDirective: {pay_setup_directive}")

            response_builder = handler_input.response_builder
            # We may need to ask the user for permissions to use Amazon Pay to make payments
            # Alexa should do this automatically.
            autopay = 'payments:autopay_consent'
            permissions = handler_input.request_envelope.context.system.user.permissions
            scopes = None if permissions is None else permissions.scopes

            logger.info(f"Permissions: scopes: {scopes}")
            if scopes is not None:
                logger.info(f"Scopes autopay status: {scopes[autopay].status}")
                logger.info(f"Status: name: {scopes[autopay].status.name} value: {scopes[autopay].status.value}")

            if user_details['cognito_loaded']:
                speak = ''
            else:
                speak = ('Not authenticated as a retail demo store user with a simulated profile chosen -'
                         ' using configured default as Amazon Pay account. ')

            permissions_not_granted = (scopes is None or
                                       autopay not in scopes or
                                       scopes[autopay].status.value!="GRANTED")

            # Amazon Pay Setup will ask for permissions from the user, so this is not necessary.
            # However, we can present the permissions card.
            # See https://developer.amazon.com/en-US/docs/alexa/amazon-pay-alexa/integrate-skill-with-amazon-pay-v2.html#amazon-pay-permissions-and-voice-purchase-settings
            if FORCE_ASK_PAY_PERMISSIONS_ALWAYS or (permissions_not_granted and ASK_PAY_PERMISSIONS_IF_NOT_GRANTED):
                speak += "Please give permission to use Amazon Pay to check out. "
                response_builder = response_builder.set_card(
                    AskForPermissionsConsentCard(permissions=[autopay]))

            response_builder = response_builder.speak(speak)
            response_builder = response_builder.add_directive(pay_setup_directive)

            return response_builder.response