Q&A

liff send userdata

我嘗試以https://liff.line.me/{我的網址} 讓使用者點選,傳送user資料至我設計的網頁, 但卻出現error:{INVALID_CONFIG},請問我該如何解決 my code github:https://github.com/Pei-Ting-Wang/linebot_liff.git js:

const app = require('express')();
let path = require('path');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const axios = require('axios').default;
const qs = require('query-string');
const myLink = liff.permanentLink.createUrl()
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccount.json");
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://linbrary-cd99a.firebaseio.com"
});

let user;
let pass;

const loginUrl = "https://uco-mcu.primo.exlibrisgroup.com/primaws/suprimaLogin";
const queryUrl = 'https://uco-mcu.primo.exlibrisgroup.com/primaws/rest/priv/myaccount/loans?bulk=10&lang=zh-tw&offset=1&type=active';
const port = process.env.PORT || 5000;

app.get('/send-id', (req, res) => {
    res.json({ id: process.env.LINE_LIFF_ID });
});

app.get('/', function (req, res) {
    console.log("Recieved GET request on [/] path.");
    res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/show', urlencodedParser, async (req, res) => {
    user = req.body.username;
    pass = req.body.password;
    const userData = {
        "authenticationProfile": "mcu_ldaps",
        "username": user,
        "password": pass,
        "institution": "886UCO_MCU",
        "view": "886MCU_INST"
    };
    try {
        const loginResponse = (await axios.post(loginUrl, qs.stringify(userData)));
        const token = loginResponse.data['jwtData']
        console.log(token)
        const [XPersist] = loginResponse.headers['set-cookie'].filter((cookie) => { return cookie.startsWith('X-Persist'); });
        console.log(XPersist)
        const queryResponse = await axios.get(queryUrl, { headers: { Authorization: `Bearer ${token}`, cookie: XPersist } })
        console.log(queryResponse.data['data']['loans']['loan']);
        userFirebase(userData);
        res.send("<h1 style='color:red'>" + "登入成功" + "</h1>");
    } catch (err) {
        console.log(err)
        console.log("err");
        res.send("<h1>" + "登入失敗" + "</h1>");

    }
    // console.log(borrowData);
    res.send();
});

app.listen(port, function () {
    console.log("Listening on " + port + " port.")
})

function userFirebase(userData) {
    let db = admin.firestore(); // 取得 Database 物件
    let db_ref = db.collection('libraryUser').doc(userData['username']);
    db_ref.set({
        "username": userData['username'],
        "passoword": userData['password'],
        "loginState": true
    });
}

html:

<body>
    <div class="wrap">
        <div class="container">
            <div class="items img">
                <img src="https://picsum.photos/300/200?random=3" />
            </div>
            <div class="items">
                <div>
                    <p class="title">圖書資訊系統</p>
                    <p class="title_2">驗證服務</p>
                </div>
                <form action="/show" method="POST">
                    <div class="item">
                        <input name="username" id="username" type="text" placeholder="帳號" required>
                    </div>
                    <div class="item">
                        <input name="password" id="password" type="password" placeholder="密碼">
                    </div>
                    <div class="item">
                        <button id="submit" type="submit" onclick="auth()">登入</button>
                    </div>
                    <div class="item">
                        <a
                            href="http://www1.mcu.edu.tw/Apps/SB/SB_Site.aspx?PageID=164&url=http://www1.mcu.edu.tw/forgetpassword.aspx&redirected=true">重設密碼</a>
                    </div>
                </form>
            </div>
        </div>

    </div>
    <script>
        function initializeLiff(myLiffId) {
            liff
                .init({
                    liffId: myLiffId,
                })
                .then(() => {
                    auth();
                })
                .catch(err => {
                    alert(`error: ${JSON.stringify(err)}`);
                });
        }
        function auth() {
            window.alert('clicked: sendMessages');
            liff
                .sendMessages([
                    {
                        type: 'text',
                        text: 'Hello, LIFF!',
                    },
                ])
                .then(() => {
                    alert('message sent');
                    liff.closeWindow();
                })
                .catch(err => {
                    window.alert('Error sending message: ' + err);
                });
        }
        document.addEventListener('DOMContentLoaded', () => {
            fetch('/send-id')
                .then(reqResponse => reqResponse.json())
                .then(jsonResponse => {
                    let myLiffId = jsonResponse.id;
                    initializeLiff(myLiffId);
                })
                .catch(err => {
                    alert(`error: ${JSON.stringify(err)}`);
                });
        });

    </script>
  • 0
  • 3
  • 269
  • twitter facebook

哈囉 請問你是在本地測試嗎? 如果是的話 要另外裝一個套件 npm i dotenv --save 然後在index.js 的最上面進行引入動作 require('dotenv').config()

做這個動作的目的是為了將.env的檔案做引入,你才會你設定的有環境變數!

PS:請不要把line的token, secret 放在git裡面,有心人士想利用,即可用你token存取任何使用者資訊,甚至透過你身分發送訊息! PS:也不要把node_modules用進git,很肥一包XD

  • 0

@罕罕 我已經按照你說的裝個套件,把檔案引入但還是出現error:{"code":"init_failed"}

  • 0

哈囉 我這邊測試正常哦! 可以點這個LIFF試試看~點我 這裡是成功的畫面 要看你詳細操作才知道哪裡有問題欸

還有問題的話可以直接加我

  • 0

関連する質問

    関連する質問はありません

本当によろしいですか? question.vm