LIFF APP 串接发送认证码 API

今天要结合前两天的成果,完成 LIFF APP 串接 发送认证码 API 的功能

目标

要完成的功能有两个:

  1. 发送 POST Request 到 Google App Script 专案 Send Mail
  2. 根据回应显示验证码送出的结果

发送 POST Request

这边我们选用 axios 处理 Request,当然如果你习惯用 jQuery AJAX / fetch 也是可以的。

安装 axios

npm i axios --save-dev

别忘了在 vite.config.js 加上设定:

export default defineConfig({
  plugins: [vue()],
  base: '/{YOUR_PROJECT_NAME}/dist/',
  optimizeDeps: {
    include: ["axios"]
  }
})

use axios send post request

在 src 资料夹底下建立一个 service 资料夹,里面新增一个 api.js 如下:

import axios from 'axios';

export const sendValidationCodePost = (name, mail, token) => {
    const targetUrl = "YOUR_GAS_API_URL";
    let data = JSON.stringify({name, mail, token});
    return axios.post(targetUrl, data, {
        headers: { 'content-type': 'application/x-www-form-urlencoded' }
    }).then(response => {
        if (response) {
            return response;
        } else {
            return Promise.reject();
        }
    }).catch(error => {
        console.log('error', error);
    });
};

呈现结果

修改 Vue Component

因为我们需要两个 Component

  1. 实作表单
  2. 呈现结果

所以我们将原本 BindMail.vue 拆成以下三个 Component:

  1. BindMail.vue: 负责初始化 LIFF。BindMail功能的父元素。
  2. BindMailForm.vue: 负责处理表单的呈现与送出。BindMail功能的子元素。
  3. BindMailResult.vue: 负责呈现结果页面。BindMail功能的子元素。

修改 BindMail.vue 如下

<script setup>
import {onMounted, ref, provide} from 'vue'
import BindMailForm from "./BindMailForm.vue";
import BindMailResult from "./BindMailResult.vue";

const errorMsg = ref("");
// 判断要显示表单元件还是结果元件
const bindStep = ref('form');
// API 回应结果
const resMessage = ref('');
provide('resMessage', resMessage);

// 切换至结果元件显示
const next = (event) => {
  resMessage.value = event
  bindStep.value = 'result'
}

// 判断是否登入以及是否使用 Line 开启 LIFF
const initializeApp = () => {
  if (!liff.isLoggedIn() || !liff.isInClient()) {
    errorMsg.value = "please use line liff open";
  }
};

// 初始化 LIFF APP
onMounted(() => {
  liff.init({
    liffId: 'YOUR_LIFF_ID'
  }).then(() => {
    initializeApp();
  }).catch((err) => {
    errorMsg.value = "initialize LIFF fail";
  });
});
</script>

<template>
  <h1>验证码小帮手 - 身份认证</h1>
  <component v-if="!errorMsg" :is="(bindStep === 'form') ? BindMailForm : BindMailResult"  @nextStep="next"></component>
  <p v-else class="error">{{ errorMsg }}</p>
</template>

新增 BindMailForm.vue 如下

<script setup>
import {onMounted, ref, defineEmits} from 'vue'
import {sendValidationCodePost} from '/src/service/api'

const userName = ref("");
const userToken = ref("");
const userEmail = ref("");
const inputEmail = ref("");

const emit = defineEmits(['nextStep'])

const submit = (mail) => {
  sendValidationCodePost(userName.value, mail, userToken.value)
      .then((res) => {
        const result = res.data.message;
        emit('nextStep', result);
      })
      .catch((err) => {
        console.log("err: ", err);
      });
}

onMounted(() => {
  liff.ready.then(() => {
    const user = liff.getDecodedIDToken();
    userName.value = user && user.name;
    userToken.value = user && user.sub;
    userEmail.value = user && user.email;
  })
})
</script>

<template>
  <template v-if="userEmail">
    <p>将发送身份认证码到 {{ userEmail }}</p>
    <button type="button" class="btn" @click="submit(userEmail)">确定</button>
  </template>

  <template v-else>
    <p>发送身份认证码到 <input type="email" v-model="inputEmail" placeholder="请输入 Email"></p>
    <button type="button" class="btn" @click="submit(inputEmail)">确定</button>
  </template>
</template>

新增 BindMailResult.vue 如下

<template>
  <p>{{(result === 'success') ? '已将验证码发送至信箱' : '发送失败,请稍後再试'}}</p>
  <button type="button" class="btn" @click="closeLiff">关闭</button>
</template>

<script setup>
import {inject} from "vue";

const result = inject('resMessage');
const closeLiff = () => {
  liff.closeWindow();
}
</script>

接着就可以执行 npm run build,然後将打包好的静态档案部署到 Github Pages 测试结果罗~


<<:  【程序】技术债 转生成恶役菜鸟工程师避免 Bad End 的 30 件事 - 11

>>:  23. React key 的用途

[Day 30] 使用 Heroku 部署机器学习 API

使用 Heroku 部署机器学习 API 今日学习目标 动手部署自己的机器学习 API 使用 Her...

Hook 概观( Day15 )

如果想快速使用 Hook ,其实就参考 Hook 概观分的五个面向,包含一定会用也最常用的 Stat...

Web服务器扫描工具-Nikto

前几天有练习了小蜘蛛和跳过鱼 今天还是持续练习Web的工具 透过这些工具可以辅助我们更顺利进行手动测...

[ 卡卡 DAY 12 ] - React Native UI 元件(component) 介绍(下)

再来多介绍一个常会用到的 list 元件 以及到目前的踩雷分享 :P 列表元件 Virtualiz...

人生还有更重要的事! 善选CISSP应考策略!

Express: 三个月内短冲型. 适合有一定的工作经验, 能专注在一个目标, 每天下班後可稳定且...