index.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. let lang = window.navigator.language;
  2. console.log(lang);
  3. function apiAuth() {
  4. if (!window.h5sdk) {
  5. console.log('invalid h5sdk')
  6. alert('please open in feishu')
  7. return
  8. }
  9. // 通过服务端的Route: get_appid获取app_id
  10. // 服务端Route: get_appid的具体内容请参阅服务端模块server.py的get_appid()函数
  11. // 为了安全,app_id不应对外泄露,尤其不应在前端明文书写,因此此处从服务端获取
  12. fetch(`/get_appid`).then(response1 => response1.json().then(res1 => {
  13. console.log("get appid succeed: ", res1.appid);
  14. // 通过error接口处理API验证失败后的回调
  15. window.h5sdk.error(err => {
  16. throw('h5sdk error:', JSON.stringify(err));
  17. });
  18. // 通过ready接口确认环境准备就绪后才能调用API
  19. window.h5sdk.ready(() => {
  20. console.log("window.h5sdk.ready");
  21. console.log("url:", window.location.href);
  22. // 调用JSAPI tt.requestAuthCode 获取 authorization code
  23. tt.requestAuthCode({
  24. appId: res1.appid,
  25. // 获取成功后的回调
  26. success(res) {
  27. console.log("getAuthCode succeed");
  28. //authorization code 存储在 res.code
  29. // 此处通过fetch把code传递给接入方服务端Route: callback,并获得user_info
  30. // 服务端Route: callback的具体内容请参阅服务端模块server.py的callback()函数
  31. fetch(`/callback?code=${res.code}`).then(response2 => response2.json().then(res2 => {
  32. console.log("getUserInfo succeed");
  33. // 示例Demo中单独定义的函数showUser,用于将用户信息展示在前端页面上
  34. showUser(res2);}
  35. )
  36. ).catch(function (e) {console.error(e)})
  37. },
  38. // 获取失败后的回调
  39. fail(err) {
  40. console.log(`getAuthCode failed, err:`, JSON.stringify(err));
  41. }
  42. })
  43. }
  44. )
  45. })).catch(function (e) { // 从服务端获取app_id失败后的处理
  46. console.error(e)
  47. })
  48. }
  49. function showUser(res) {
  50. // 展示用户信息
  51. // 头像
  52. $('#img_div').html(`<img src="${res.avatar_url}" width="100%" height=""100%/>`);
  53. // 名称
  54. $('#hello_text_name').text(lang === "zh_CN" || lang === "zh-CN" ? `${res.name}` : `${res.en_name}`);
  55. // 欢迎语
  56. $('#hello_text_welcome').text(lang === "zh_CN" || lang === "zh-CN" ? "欢迎使用飞书" : "welcome to Feishu");
  57. }