在上一篇中我們提到,replyToken可以用作我們回覆使用者訊息的驗證.
Line文件中有說到
https://api.line.me/v2/bot/message/reply
成功回傳HttpStatus 200,body無內容
失敗則回傳對應狀態碼,並會在body內帶入message顯示錯誤訊息
可以使用 RestTemplate 或是 Line提供的套件方法,以下我們兩個都會示範
@Data
@AllArgsConstructor
public class Message {
private String type;
private String id;
private String text;
}
@Data
public class ReplyMsg {
private String userId;
private String replyToken;
private Message[] messages;
}
@Service
@Slf4j
public class LineMsgService {
@Value("${line.bot.channelToken}")
private String channel_token;
@Autowired
private RestTemplate restTemplate;
private final String replyUrl = "https://api.line.me/v2/bot/message/reply";
public void replyMsg(ReplyMsg replyMsgs) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setBearerAuth(channel_token);
HttpEntity<ReplyMsg> httpEntity = new HttpEntity<>(replyMsgs,httpHeaders);
ResponseEntity<JsonObject> response = restTemplate.exchange(replyUrl, HttpMethod.POST, httpEntity,JsonObject.class);
if(HttpStatus.OK.equals(response.getStatusCode())) {
log.info("response status:{}, response msg:{}",response.getStatusCode(),response.getBody().getMessage());
}
}
接下來是 Controller端
@PostMapping(value="reply",consumes="application/json")
public void replyUser(@RequestBody ReplyMsg replyMsg) {
lineMsgService.replyMsg(replyMsg);
}
那當然也可以呼叫Line 提供的套件,文件裡面也有提供呼叫的範例
public void sendByLine(LineMsgBack message) throws InterruptedException, ExecutionException {
LineMessagingClient client = LineMessagingClient
.builder(channel_token)
.build();
TextMessage text = new TextMessage("hello");
ReplyMessage replyMessag = new ReplyMessage(message.getEvents()[0].getReplyToken(),
text);
BotApiResponse botApiResponse = client.replyMessage(replyMessag).get();
log.info("reply message result:"+botApiResponse.getMessage());
}
貼心提示:
1.請注意 replyToken只能使用一次,時間有效期為一分鐘
2.另外當時我在做測試的時候有遇到,怎麼打都是回傳 { status:400 message:Invalid Reply Token} 的問題
,最後發現問題是出在 channel access token上,去設定頁面,按Issue重新申請一個就可以了
那我們這個系列就告一段落囉
以下是其他篇供大家參考
Line Message API + MongoDB 串接實作(一)安裝環境
Line Message API + MongoDB 串接實作(二)接收訊息
Line Message API + MongoDB 串接實作(三)查詢使用者訊息資料