UniLoginClient.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const axios = require('axios')
  2. const https = require('https')
  3. const config = require('../config.json')
  4. const VALID_SOCIAL_TYPES = ['qq', 'wx']
  5. function normalizeSocialType(type) {
  6. const socialType = type || 'qq'
  7. return VALID_SOCIAL_TYPES.includes(socialType) ? socialType : null
  8. }
  9. async function fetchUniLoginProfile(type, code) {
  10. const socialType = normalizeSocialType(type)
  11. if (!socialType)
  12. throw new Error('不支持的第三方登录类型')
  13. const uniConfig = config.unilogin
  14. const url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${socialType}&code=${code}`
  15. const r = await axios.get(url, {
  16. httpsAgent: new https.Agent({
  17. rejectUnauthorized: false
  18. }),
  19. proxy: false
  20. })
  21. if (!r || r.data?.code !== 0)
  22. throw new Error(r.data?.msg || 'api接口错误')
  23. return {
  24. ...r.data,
  25. social_type: socialType
  26. }
  27. }
  28. module.exports = {
  29. VALID_SOCIAL_TYPES,
  30. normalizeSocialType,
  31. fetchUniLoginProfile
  32. }