123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- import third from '@/sheep/api/third';
- import $store from '@/sheep/store';
- import AuthUtil from '@/sheep/api/member/auth';
- const socialType = 34; // 社交类型 - 微信小程序
- let sessionId = uni.getStorageSync('sessionId');
- let subscribeEventList = [];
- // 加载微信小程序
- function load() {
- checkUpdate();
- // const sessionStatus = await checkSession();
- // 小程序的接口改动太频繁了 强制每次进入都重新获取
- const sessionStatus = false;
- if (!sessionStatus) {
- getSessionId();
- }
- getSubscribeTemplate();
- }
- // 微信小程序静默授权登陆
- const login = async () => {
- return new Promise(async (resolve, reject) => {
- // 1. 获得微信 code
- const codeResult = await uni.login();
- if (codeResult.errMsg !== 'login:ok') {
- resolve(false);
- }
- // 2. 社交登录
- const loginResult = await loginByCode(codeResult.code);
- if (loginResult.code === 0) {
- setOpenid(loginResult.data.openid);
- resolve(true);
- } else {
- resolve(false);
- }
- return loginResult.code === 0 ? resolve(true) : resolve(false);
- });
- };
- function loginByCode(code) {
- return AuthUtil.socialLogin(socialType, code, 'default');
- // TODO 芋艿:shareLog
- }
- // 微信小程序手机号授权登陆
- const mobileLogin = async (e) => {
- return new Promise(async (resolve, reject) => {
- if (e.errMsg !== 'getPhoneNumber:ok') {
- resolve(false);
- return;
- }
- const { error } = await third.wechat.login({
- platform: 'miniProgram',
- shareInfo: uni.getStorageSync('shareLog') || {},
- payload: encodeURIComponent(
- JSON.stringify({
- sessionId: uni.getStorageSync('sessionId'),
- code: e.code,
- iv: e.iv,
- encryptedData: e.encryptedData,
- }),
- ),
- });
- if (error === 0) {
- resolve(true);
- }
- if (error === -1) {
- getSessionId(false);
- }
- resolve(false);
- });
- };
- // 微信小程序绑定
- const bind = () => {
- return new Promise(async (resolve, reject) => {
- const loginRes = await third.wechat.bind({
- platform: 'miniProgram',
- payload: encodeURIComponent(
- JSON.stringify({
- sessionId: uni.getStorageSync('sessionId'),
- }),
- ),
- });
- if (loginRes.error === -1) {
- getSessionId(false);
- } else if (loginRes.error === 0) {
- resolve(true);
- } else {
- reject(false);
- }
- });
- };
- // 微信小程序解除绑定
- const unbind = async () => {
- const { error } = await third.wechat.unbind({
- platform: 'miniProgram',
- });
- return !error;
- };
- // 获取最新sessionId
- const getSessionId = async (auto_login = null) => {
- // 获取code
- let codeStr = '';
- const loginResult = await uni.login();
- if (loginResult.errMsg === 'login:ok') {
- codeStr = loginResult.code;
- } else {
- getSessionId(auto_login);
- return false;
- }
- if(auto_login === null) {
- auto_login = !!($store('app').platform.auto_login && !$store('user').isLogin);
- }
- const { error, data } = await third.wechat.getSessionId({
- platform: 'miniProgram',
- payload: encodeURIComponent(
- JSON.stringify({
- code: codeStr,
- auto_login,
- }),
- ),
- });
- if (error === 0) {
- uni.setStorageSync('sessionId', data.session_id);
- return true;
- }
- return false;
- };
- // 检查sessionId是否可用
- const checkSession = () => {
- return new Promise((resolve, reject) => {
- if (!sessionId) {
- return resolve(false);
- }
- uni.checkSession({
- success() {
- return resolve(true);
- },
- fail() {
- uni.removeStorageSync('sessionId');
- return resolve(false);
- },
- });
- });
- };
- // 小程序更新
- const checkUpdate = async (silence = true) => {
- if (uni.canIUse('getUpdateManager')) {
- const updateManager = uni.getUpdateManager();
- updateManager.onCheckForUpdate(function (res) {
- // 请求完新版本信息的回调
- if (res.hasUpdate) {
- updateManager.onUpdateReady(function () {
- uni.showModal({
- title: '更新提示',
- content: '新版本已经准备好,是否重启应用?',
- success: function (res) {
- if (res.confirm) {
- // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
- updateManager.applyUpdate();
- }
- },
- });
- });
- updateManager.onUpdateFailed(function () {
- // 新的版本下载失败
- // uni.showModal({
- // title: '已经有新版本了哟~',
- // content: '新版本已经上线啦,请您删除当前小程序,重新搜索打开~',
- // });
- });
- } else {
- if (!silence) {
- uni.showModal({
- title: '当前为最新版本',
- showCancel: false,
- });
- }
- }
- });
- }
- };
- // 绑定用户手机号
- const bindUserPhoneNumber = (e) => {
- return new Promise(async (resolve, reject) => {
- const { error } = await third.wechat.bindUserPhoneNumber({
- platform: 'miniProgram',
- payload: encodeURIComponent(
- JSON.stringify({
- sessionId: uni.getStorageSync('sessionId'),
- iv: e.iv,
- encryptedData: e.encryptedData,
- code: e.code,
- }),
- ),
- });
- if (error === 0) {
- resolve(true);
- }
- resolve(false);
- });
- };
- // 获取订阅消息模板
- async function getSubscribeTemplate() {
- const { error, data } = await third.wechat.subscribeTemplate();
- if (error === 0) {
- subscribeEventList = data;
- }
- }
- // 订阅消息
- function subscribeMessage(event) {
- let tmplIds = [];
- if (typeof event === 'string') {
- tmplIds.push(subscribeEventList[event]);
- }
- if (typeof event === 'object') {
- event.forEach((item) => {
- if (typeof subscribeEventList[item] !== 'undefined') tmplIds.push(subscribeEventList[item]);
- });
- }
- if (tmplIds.length === 0) return;
- uni.requestSubscribeMessage({
- tmplIds,
- fail: (err) => {
- console.log(err);
- },
- });
- }
- // 设置 openid 到本地存储,目前只有 pay 支付时会使用
- function setOpenid(openid) {
- uni.setStorageSync('openid', openid);
- }
- export default {
- load,
- login,
- bind,
- unbind,
- checkUpdate,
- bindUserPhoneNumber,
- subscribeMessage,
- };
|