getPrivateKey.js 2.57 KB
import config from '../../config'
import udid from './utils/udid.js'
const ClientInitConfigMethod = "resources.simple.pice"

const getPrivateKey = () => {
  return new Promise((resolve, reject) => {
    let app = getApp();
    let globalData;
    // 获取 App 中的全局变量
    if (app && app.globalData) {
      // 原生小程序的 globalData 获取方式
      globalData = app && app.globalData;
    } else {
      // Taro 下 globalData 获取方式
      globalData = app && app.props && app.props.globalData;
    }
    // 获取 p2SecretKey
    let p2SecretKey = globalData && globalData.p2SecretKey;
    // 如果未取到 p2SecretKey
    if (!p2SecretKey) {
      // 本地获取
      p2SecretKey = getYHStorageSync('p2SecretKey', 'request');
    }

    if (!p2SecretKey) {
      p2SecretKey = getYHStorageSync('verifyKey', 'request');
    }

    if (p2SecretKey) {
      // 存在,直接返回
      resolve(p2SecretKey);
    } else {
      // 不存在,请求数据
      const data = {
        "udid": udid.get(),
        "method": ClientInitConfigMethod
      };
      const method = "GET";
      const header = {
        'Content-Type': 'application/x-www-form-urlencoded'
      };
      wx.request({
        url: config.domains.yohoApi,
        data,
        method,
        header,
        success: (res) => {
          let data = res && res.data
          if (data && data.data && data.data.sk) {
            // 存在,获取,存储并返回
            p2SecretKey = data.data.sk;
            if (globalData) {
              globalData.p2SecretKey = p2SecretKey;
            }
            wx.setStorageSync("p2SecretKey", p2SecretKey);
            wx.setStorageSync("verifyKey", p2SecretKey);
            resolve(p2SecretKey);
          } else {
            let err = new Error();
            let code = err.code ? err.code : 800;
            let message = err.message ? err.message : '';
            let isPrivatekeyError = true
            reject({ code, message, isPrivatekeyError });
          }
        },
        fail: (err) => {
          let code = err.code ? err.code : 800;
          let message = err.message ? err.message : '';
          let isPrivatekeyError = true
          reject({ code, message, isPrivatekeyError });
        }
      })
    }
  });
}

const getYHStorageSync = (key, fromPage) => {
  try {
    let res = wx.getStorageSync(key);
    return res;
  } catch (e) {
    wx.reportAnalytics('ufo_get_storage_error', {
      key: key,
      error: e.message,
      error_code: e.code,
      from_page: fromPage,
    });
    return null;
  }
}

export default getPrivateKey;