lang/node

Getting Startd : Messenger Platform - facebook for developers

C/H 2016. 7. 14. 08:30

Getting Started

This is a walkthrough to see the basics of the platform in action. Read the Complete Guide to learn about the platform in more detail.
실행되는 플랫폼을 볼 수있는 기초 연습입니다. 자세히 플랫폼에 대해 알아 보려면 완전한 가이드를 참조하십시오.

Sample App

Download the sample app from Github to follow along with this tutorial. You can run the sample app to see it in action.
이 튜토리얼을 따라할 수 있는 Github 샘플 응용 프로그램을 다운로드합니다. 샘플을 보고 응용 프로그램을 실행할 수 있습니다.

Get Sample App

Steps

  1. Create a Facebook App and Page
    페이스 북 앱과 페이지 만들기

    Create a new Facebook App and Page or use existing ones. Go to the App Dashboard and under Product Settings click "Add Product" and select "Messenger."
    새로운 페이스 북 앱 및 페이지를 만들거나 기존 사용합니다. 앱 대시 보드 및 제품 설정에서 이동하는 "제품 추가"를 선택 클릭 "메신저를."

  2. Setup Webhook
    webhook 설정

    In the Webhooks section, click "Setup Webhooks."
    Webhooks 섹션에서 "Setup Webhooks" 을 클릭합니다.

    Enter a URL for a webhook, enter a Verify Token and select message_deliveries, messages, messaging_optins, and messaging_postbacks under Subscription Fields.
    토큰을 확인하고 서브 스크립 션 필드에서 message_deliveries, messages, messaging_optins 및 messaging_postbacks을 선택 입력한 후, webhook의 URL을 입력합니다.

    At your webhook URL, add code for verification. Your code should look for the Verify Token and respond with the challenge sent in the verification request. Click Verify and Save in the New Page Subscription to call your webhook with a GET request.
    당신은 webhook URL에서 확인을 위해 코드를 추가합니다. 당신의 코드는 확인 토큰을 찾아서 확인 요청에서 전송 된 도전에 응답해야합니다. 확인 및 GET 요청과 함께 당신은 webhook를 호출하는 새 페이지 가입에 저장을 클릭합니다.

    In the sample app, this method is defined in app.js:
    샘플 앱에 app.js에 메소드가 정의되어있다 :

       app.get('/webhook', function(req, res) {
    	if (req.query['hub.mode'] === 'subscribe' &&
    		req.query['hub.verify_token'] === VALIDATION_TOKEN) {
    		console.log("Validating webhook");
    		res.status(200).send(req.query['hub.challenge']);
    	} else {
    		console.error("Failed validation. Make sure the validation tokens match.");
    		res.sendStatus(403);
    	}
     });
     

  3. Get a Page Access Token
    페이지 액세스 토큰을 가져 오기

    In the Token Generation section, select your Page. A Page Access Token will be generated for you. Copy this Page Access Token. Note: The generated token will NOT be saved in this UI. Each time you select that Page a new token will be generated. However, any previous tokens created will continue to function.
    토큰 생성 섹션에서 페이지를 선택합니다. 페이지 액세스 토큰은 당신을 위해 생성됩니다. 이 페이지에 액세스 토큰을 복사합니다. 참고 : 생성 된 토큰이 UI에 저장되지 않습니다. 매번 페이지를 선택 할때마다 새 토큰이 생성됩니다. 그러나, 생성 이전 토큰은 계속 작동합니다.

  4. Subscribe the App to the Page
    페이지에 앱을 구독

    In the Webhooks section, you can subscribe the webhook for a specific page.
    Webhooks 섹션에서 특정 페이지에 대한으로 webhook를 구독 할 수 있습니다.

  5. Receive Messages
    메시지 수신

    Now that the subscription is completed, we need to listen for POST calls at our webhook. All callbacks will be made to this webhook.
    이제 가입이 완료되고, webhook에서 POST 호출을 수신 할 필요가있다. 모든 콜백이은 webhook로 이루어집니다.

    In our sample app, we handle the all of them. For receiving messages, we look for the messagingEvent.message field and call the receivedMessage function.
    샘플 앱에서 모두 처리됩니다. 메시지 수신을 위해, 메시징 Event.message 필드에 대해 보고하고, 수신 된 메시지 함수를 호출합니다.

    app.post('/webhook', function (req, res){
    	var data = req.body;
    	// Make sure this is a page subscription
    	if (data.object == 'page') {
    		// Iterate over each entry
    		// There may be multiple if batched
    		data.entry.forEach(function(pageEntry) {
    			var pageID = pageEntry.id;
    			var timeOfEvent = pageEntry.time;
    			// Iterate over each messaging event
    			pageEntry.messaging.forEach(function(messagingEvent) {
    				if (messagingEvent.optin) {
    					receivedAuthentication(messagingEvent);
    				} else if (messagingEvent.message) {
    					receivedMessage(messagingEvent);
    				} else if (messagingEvent.delivery) {
    					receivedDeliveryConfirmation(messagingEvent);
    				} else if (messagingEvent.postback) {
    					receivedPostback(messagingEvent);
    				}else{
    					console.log("Webhook received unknown messagingEvent: ", messagingEvent);
    				}
    			});
    		});
    		// Assume all went well.
    		// 모든 것이 잘 전달되었다고 가정합니다.
    		//
    		// You must send back a 200, within 20 seconds, to let us know you've
    		// successfully received the callback. Otherwise, the request will time out.
    		// 성공적으로 콜백을 받았다면 우리가 알 수 있도록 20 초 이내에, 200을 다시 전송해야 합니다.
    		// 그렇지 않으면, 요청은 시간 초과됩니다.
    		res.sendStatus(200);
    	}
    });
    

  6. Send a Text Message

    텍스트 메세지 보내기

    In receivedMessage, we've made logic to send a message back to the user. The default behavior is to echo back the text that was received.
    수신 된 메시지에서, 우리는 다시 사용자에게 메시지를 전송하는 논리를 만들었다. 기본 동작은 수신 된 텍스트를 반향하는 것입니다.

    function receivedMessage(event) {
    	var senderID = event.sender.id;
    	var recipientID = event.recipient.id;
    	var timeOfMessage = event.timestamp;
    	var message = event.message;
    	
    	console.log("Received message for user %d and page %d at %d with message:",
    	senderID, recipientID, timeOfMessage);
    	console.log(JSON.stringify(message));
    	
    	var messageId = message.mid;// You may get a text or attachment but not both
    	var messageText = message.text;
    	var messageAttachments = message.attachments;
    	
    	if (messageText) {
    		// If we receive a text message, check to see if it matches any special
    		// keywords and send back the corresponding example. Otherwise, just echo
    		// the text we received.
    		// 우리는 문자 메시지를 수신하는 경우, 그것은 특별한 키워드와 일치하는지 확인하고 해당 예제를 다시 보내 확인합니다. 그렇지 않으면, 그냥 우리가받은 텍스트를 그대로 다시 보냅니다.
    		switch (messageText) {
    			case 'image':
    				sendImageMessage(senderID);
    				break;
    			case 'button':
    				sendButtonMessage(senderID);
    				break;
    			case 'generic':
    				sendGenericMessage(senderID);
    				break;
    			case 'receipt':
    				sendReceiptMessage(senderID);
    				break;
    			default:
    				sendTextMessage(senderID, messageText);
    			}
    	 } else if (messageAttachments) {
    		sendTextMessage(senderID, "Message with attachment received");
    	 }
    }
    

    sendTextMessage formats the data in the request:
    문자 메시지를 전송하는 요 데이터를 포맷

    function sendTextMessage(recipientId, messageText) {
    	var messageData = {
    		recipient: {
    			id: recipientId
    		},
    		message: {
    			text: messageText
    		}
    	};
    	callSendAPI(messageData);
    }
    

    callSendAPI calls the Send API:
    callSendAPI 보내기 API를 호출

    function callSendAPI(messageData) {
    	request({
    		uri: 'https://graph.facebook.com/v2.6/me/messages',
    		qs: { access_token: PAGE_ACCESS_TOKEN },
    		method: 'POST',
    		json: messageData
    	}, function (error, response, body) {
    		if (!error && response.statusCode == 200) {
    			var recipientId = body.recipient_id;
    			var messageId = body.message_id;
    			console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
    		} else {
    			console.error("Unable to send message.");
    			console.error(response);
    			console.error(error);
    		}
    	});
    }
    

    Go to your Facebook Page and send a message to it. You should see the message echoed back to you along with output to the logs.
    페이스 북 페이지로 이동하고 메시지를 보낼 수 있습니다. 당신은 로그 출력과 함께 다시 당신에게 에코 메시지를 볼 수 있습니다.

  7. Send a Structured Message.
    구조화 된 메시지를 보냅니다.

    receivedMessage also sends back other kinds of messages for certain keywords. If you send the message 'generic', it will call sendGenericMessage which sends back a Structured Message with a generic template.
    receivedMessage는 특정 키워드에 대한 메시지의 다른 종류를 다시 보냅니다. 메시지를 보낼 경우 '일반', 그것은 일반적인 템플릿으로 구조화 된 메시지를 다시 전송 sendGenericMessage를 호출합니다.

    function sendGenericMessage(recipientId) {
    	var messageData = {
    		recipient: {
    			id: recipientId
    		},
    		message: {
    			attachment: {
    				type: "template",
    				payload: {
    					template_type: "generic",
    					elements: [{
    						title: "rift",
    						subtitle: "Next-generation virtual reality",
    						item_url: "https://www.oculus.com/en-us/rift/",
    						image_url: "http://messengerdemo.parseapp.com/img/rift.png",
    						buttons: [{
    							type: "web_url",
    							url: "https://www.oculus.com/en-us/rift/",
    							title: "Open Web URL"
    						}, {
    							type: "postback",
    							title: "Call Postback",
    								payload: "Payload for first bubble",
    						}],
    					}, {
    						title: "touch",
    						subtitle: "Your Hands, Now in VR",
    						item_url: "https://www.oculus.com/en-us/touch/",
    						image_url: "http://messengerdemo.parseapp.com/img/touch.png",
    						buttons: [{
    							type: "web_url",
    							url: "https://www.oculus.com/en-us/touch/",
    							title: "Open Web URL"
    						}, {
    							type: "postback",
    							title: "Call Postback",
    							payload: "Payload for second bubble",
    						}]
    					}]
    				}
    			}
    		}
     	};
     	callSendAPI(messageData);
    }
    

  8. Handle Postbacks
    포스트 백을 처리

    In the last step, the Structured Message that is sent has postbacks. Postbacks are back end calls to your webhook when buttons are tapped. These calls contain the payload that is set for the button. Buttons on Structured Messages support opening URLs and postbacks.
    마지막 단계에서 전송되는 구조화 된 메시지는 포스트 백을 보유하고 있습니다. 버튼을 탭하면 포스트 백은 다시으로 webhook에 최종 호출입니다. 이러한 호출 버튼 설정되어 페이로드를 포함한다. 구조화 된 메시지의 버튼은 URL 및 포스트 백을 열고 지원합니다.

    In our webhook handler, we handle the postback by calling receivedPostback:
    우리의 webhook 처리기에서, 우리는 receivedPostback를 호출하여 다시 게시를 처리 :

    ...
    	 } else if (messagingEvent.postback) {
    		 receivedPostback(messagingEvent);
    ...

    Which sends a message back saying that hte the postback was called:
    어느 다시 게시가 호출되었다는 메시지를 보냅니다

    function receivedPostback(event) {
    	var senderID = event.sender.id;
    	var recipientID = event.recipient.id;
    	var timeOfPostback = event.timestamp;
    	// The 'payload' param is a developer-defined field which is set in a postback
    	// button for Structured Messages.
    	var payload = event.postback.payload;
    	console.log("Received postback for user %d and page %d with payload '%s' " +
    	"at %d", senderID, recipientID, payload, timeOfPostback);

    // When a postback is called, we'll send a message back to the sender to // let them know it was successful sendTextMessage(senderID, "Postback called"); }

Next Steps
다음 단계

Great! You've complete the walkthrough. The sample app contains more functionality that you can explore, including the other Structured Message templates and example of how to use the web plugins.
훌륭합니다! 당신은 예제를 완료했습니다. 샘플 응용 프로그램은 다른 구조화 된 메시지 템플릿 및 웹 플러그인을 사용하는 방법의 예를 포함하여 탐색 할 수 있고, 더 많은 기능을 포함하고 있습니다.

The Complete Guide goes into all the features in much more detail.
완전한 가이드 훨씬 더 자세하게 모든 기능에 간다.

반응형

'lang > node' 카테고리의 다른 글

pm2 1.1.3 to 2.1.5 upgrade  (0) 2016.11.24
socket.io namespace 사용 시 sids, io.to  (0) 2016.09.09
Messenger Platform - facebook for developers  (0) 2016.07.13
n 을 이용한 nodejs 설치 및 관리  (0) 2016.05.13
node v6.0.0  (0) 2016.05.11