Giter VIP home page Giter VIP logo

Comments (6)

doreechi avatar doreechi commented on June 30, 2024

Hi SaqibOctave, can you make sure that all pre-requisite steps were followed? See https://github.com/amazon-connect/amazon-connect-chat-ui-examples/tree/master/customChatWidget#prerequisites.

from amazon-connect-chat-ui-examples.

SaqibOctave avatar SaqibOctave commented on June 30, 2024

hi @doreechi, Yes, I have enabled the chat, contact flow to handle chat, and a lambda function to start the chat here is my lambda function,

 import AWS from "aws-sdk";
AWS.config.update({region: process.env.REGION});
var connect = new AWS.Connect();

export const lambdaHandler = async(event, context, callback) => {
    console.log("Received event: " + JSON.stringify(event));
    var body = JSON.parse(event["body"]);

    startChatContact(body).then((startChatResult) => {
        callback(null, buildSuccessfulResponse(startChatResult));
    }).catch((err) => {
        console.log("caught error " + err);
        callback(null, buildResponseFailed(err));
    });
};

function startChatContact(body) {
    var contactFlowId = "";
    if(body.hasOwnProperty('ContactFlowId')){
        contactFlowId = body["ContactFlowId"];
    }
    console.log("CF ID: " + contactFlowId);
    
    var instanceId = "";
    if(body.hasOwnProperty('InstanceId')){
        instanceId = body["InstanceId"];
    }
    console.log("chat contact body: ", JSON.stringify(body))
    return new Promise(function (resolve, reject) {
        var startChat = {
            "InstanceId": instanceId == "" ? process.env.INSTANCE_ID : instanceId,
            "ContactFlowId": contactFlowId == "" ? process.env.CONTACT_FLOW_ID : contactFlowId,
            "Attributes": {
                "customerName": body["ParticipantDetails"]["DisplayName"]
            },
            "ParticipantDetails": {
                "DisplayName": body["ParticipantDetails"]["DisplayName"]
            },
            // Enable rich messaging: https://docs.aws.amazon.com/connect/latest/adminguide/enable-text-formatting-chat.html
            ...(!!body["SupportedMessagingContentTypes"] && { "SupportedMessagingContentTypes": body["SupportedMessagingContentTypes"] }),
            // Set optional chat duration: https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html#connect-StartChatContact-request-ChatDurationInMinutes
            ...(!!body["ChatDurationInMinutes"] && { "ChatDurationInMinutes": body["ChatDurationInMinutes"] })
        };
        const persistentChatEnabled = body.PersistentChat && body.PersistentChat.RehydrationType && body.PersistentChat.SourceContactId;
        if(persistentChatEnabled) {
            startChat['PersistentChat'] = {
                "RehydrationType": body["PersistentChat"]["RehydrationType"],
                "SourceContactId": body["PersistentChat"]["SourceContactId"]
            }
        }

        connect.startChatContact(startChat, function(err, data) {
            if (err) {
                console.log("Error starting the chat.", err);
                reject(err);
            } else {
                console.log("Start chat succeeded with the response: " + JSON.stringify(data));
                resolve(data);
            }
        });

    });
}

function buildSuccessfulResponse(result) {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': 'application/json',
            'Access-Control-Allow-Credentials' : true,
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
        },
        body: JSON.stringify({
            data: { startChatResult: result }
        })
    };
    console.log("RESPONSE" + JSON.stringify(response));
    return response;
}

function buildResponseFailed(err) {
    const response = {
        statusCode: err.statusCode,
        headers: {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': 'application/json',
            'Access-Control-Allow-Credentials' : true,
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
        },
        body: JSON.stringify({
            data: {
                "Error": err
            }
        })
    };
    return response;
}

from amazon-connect-chat-ui-examples.

SaqibOctave avatar SaqibOctave commented on June 30, 2024

@doreechi I also tried with this lambda

import { ConnectClient, StartChatContactCommand } from "@aws-sdk/client-connect"; 
const CREDENTIALS = {
    accessKeyId: "1221312312344",
    secretAccessKey: "123123128930981201244123",
  };
  const REGION = "us-east-1";
  

var connect = new ConnectClient({ region: REGION, credentials: CREDENTIALS });

export const lambdaHandler = async(event, context, callback) => {
    console.log("Received event: " + JSON.stringify(event));
    var body = JSON.parse(event["body"]);
    console.log("Body :: ", body);
const input = { 
  InstanceId: body["InstanceId"], 
  ContactFlowId: body["ContactFlowId"],
  Attributes: { 
    "chennal": "web",
  },
  ParticipantDetails: { // ParticipantDetails
    DisplayName: "STRING_VALUE", // required
  },
  InitialMessage: { // ChatMessage
    ContentType: "text/plain", // required
    Content: "STRING_VALUE", // required
  },
  ClientToken: "1237981789-2139812893-1231",
  ChatDurationInMinutes: Number(1500),
  SupportedMessagingContentTypes: [ // SupportedMessagingContentTypes
        "text/plain"
  ],
};
console.log("Input :: ", input)
const command = new StartChatContactCommand(input);
console.log("command :: ", command);
const response = await connect.send(command);
console.log("response :: ", response);
buildSuccessfulResponse(response);


function buildSuccessfulResponse(result) {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': 'application/json',
            'Access-Control-Allow-Credentials' : true,
            'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
        },
        body: JSON.stringify({
            data: { startChatResult: result }
        })
    };
    console.log("RESPONSE" + JSON.stringify(response));
    return response;
}

response of this lambda in cloud watch is:

response ::  {
  '$metadata': {
    httpStatusCode: 200,
    requestId: '2f55e13e-9427-436a-a0ad-9eebdb183e59',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  ContactId: 'aa36341b-ec21-419c-bafa-a9304f496098',
  ParticipantId: '18789fdd-d1d8-43f9-9160-5b23c5f8bff7',
  ParticipantToken: 'QVFJREFIZzI0N0RNMnY2aVBPWXdGaHBzL1Bib0tZSWVZN2VhWEJyUTcwOG5rdnY5c2dGNW45ZEVJZzJUcVJ3cGFuVzJtTVI3QUFBQWJqQnNCZ2txaGtpRzl3MEJCd2FnWHpCZEFnRUFNRmdHQ1NxR1NJYjNEUUVIQVRBZUJnbGdoa2dCWlFNRUFTNHdFUVFNNE5EVWFzYkw3LzNwcE10NUFnRVFnQ3RYMmRLcTZqMFhmR3IzRms3cEgxSHJOY0dJYWwyNjFrSVlNaGs0bnBxOVBTbTRVemFueklyWEZVTTM6OllNRElVYzJVUEhaa0J4OTQ4aG9xbWJlZmxTTmptaVM4YUt6L1Y0dXVTQmNsY08xWHk3aGg0Qmt6QitOMkNZZkhuSUc4by9lb1p1UVRXdWtDaTQ2Rkp2SXF0ams0YWVuSXhOKzlVVEJCQnljMGlFRDRNZUJzdnB3azY4d2FQeWtnWHYvaGdGZkMvQ2piUW5JZmFiSGYzVk45T0VSdGFoM01xa05vc2RMTkhYUTI0ZGQ2d3NyZFhYdlMwYzdheTArS1JJMzB6K2s1Zjh5ajlnSEk1RmxNRXJmcjNBVTlKUXFUaHZKTmJnPT0='
}

but chat is not been initiated should.. Will you please help me to start the chat after pre chat is submittted

from amazon-connect-chat-ui-examples.

doreechi avatar doreechi commented on June 30, 2024

Hi,

For first code, can you verify that region env variables have been updated: process.env.REGION - this should be the updated to the region that the instance and stack are in.
And depending on how the body is inputted, may also need to check process.env.INSTANCE_ID and process.env.CONTACT_FLOW_ID. I'd be interested to see the body of the start chat request and make sure all those values look correct.

For the second code, can you make sure that CREDENTIALS and REGION are updated to be accurate? Also for that successful response, how was the lambda invoked? Did you do that via console or were you able to invoke the lambda from you chat UI?

from amazon-connect-chat-ui-examples.

SaqibOctave avatar SaqibOctave commented on June 30, 2024

hi doreechi,
for second lambda i have checked the lambda with POSTMAN and then pass the API gateway URL to index.html file in CHAT UI, Lambda is invoked with chat UI and then chat UI internally call the createParticipantConnection API but i got the Access denied Error when Chat UI calls the create Participant connection API

from amazon-connect-chat-ui-examples.

doreechi avatar doreechi commented on June 30, 2024

Hi, see other open issue thread #133.

from amazon-connect-chat-ui-examples.

Related Issues (20)

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.