Newer
Older
smartKitchenMiniProgram / utils / request.js
require('regenerator-runtime')
import {LOGIN} from '../utils/api/index'
const EXPIRDCODE = 1010;
const INVALIDCODE = 1004;
let errorInfo = {};
let isloginActions = false;
const loginActions = [
	'user.wx-applet.synchronization',
	'wx-func.schema.get',
	'user.auth.code2Session',
	'user.refreshToken'
];
let wxAppid = 'wx84dba45d4abf799f'; //此处请选择填入您当前的wxappid,默认将从微信请求头中机械获取请求主体wxappid

 const wxRequest = function (config = {
	url: ''
}) {
	return new Promise(function (resolve, reject) {
		wx.request({
			...config,
			success(res) {
				if(res.statusCode === 200) {
					if(res.data.success) {
						resolve(res);
					} else {
						console.log('----', res)
						wx.showToast({
							title: 	`${res.data.msg}`,
							icon: 'none'
						});
					}
				}
			},
			fail(err) {
				reject(err);
			},
		});
	});
}

const getOpenId = async (schema) => {
	let wxLogin = new Promise((resolve, reject) => {
		wx.login({
			success: resolve,
			fail: reject
		});
	});
	let {	code } = (await wxLogin) || "";
	const params = {
		data: {
			action: "user.auth.code2Session",
			params: {
				code,
				schema,
			},
		},
	};
	return request(params);
};

const getSchema = () => {
	const params = {
		data: {
			action: "wx-func.schema.get",
			params: {
				app_id: wxAppid? wxAppid : 'cloud',
			},
		},
	};
	return request(params);
};

// 登录
export function getLogin() {
	console.log('login')
	return new Promise((resolve, reject) => {
		wx.login({
			onlyAuthorize: true,
			success(data) {
				console.log('登录参数', data, wx.getStorageSync('sessionId'))
				LOGIN(data.code).then(res => {
					wx.setStorageSync('sessionId', res);
					wx.showToast({
					  title: `登录成功`,
					  icon: "none",
					  duration: 2000,
					});
					resolve('登录成功');
				});
			},
			fail(err) {
				console.log('login fail', err);
				wx.showToast({
					title: '登录错误',
					icon: 'none'
				});
				reject('登录错误');
			},
		});
	})
}

export const login = async () => {
	if(!wxAppid.length) wxAppid = 'cloud'
	let schema = await getSchema(); 
	if (!schema) {
		wx.showModal({
		content: '未获取到schema,请检查网络',
	})
	return false;
}
	wx.setStorageSync('schema', schema)
	let {
		open_id
	} = await getOpenId(schema) || {};
	if (!open_id) {
		wx.showModal({
			content: '未获取到openId,请检查网络',
		})
		return false;
	}
	wx.setStorageSync('open_id', open_id)
	const params = {
		data: {
			action: 'user.wx-applet.synchronization',
			params: {
				open_id,
				app_schema: 'cloud',
			}
		}
	};
	const {
		uid,
		access_token,
		refresh_token
	} = await request(params);
	wx.setStorageSync('uid', uid);
	wx.setStorageSync('access_token', access_token)
	wx.setStorageSync('refresh_token', refresh_token)
	return uid
};

//刷新token
const refreshToken = async () => {
	let refresh_token_ = wx.getStorageSync('refresh_token');
	if(!refresh_token_) return;
	const params = {
		data: {
			action: 'user.refreshToken',
			params: {
				refresh_token:refresh_token_
			},
		},
	};
 
	const res = await request(params);
	if (!res) return false;
	const {
		uid,
		access_token,
		refresh_token
	} = res;
	wx.setStorageSync('uid', uid);
	wx.setStorageSync('access_token', access_token);
	wx.setStorageSync('refresh_token', refresh_token);
	return true;
}; 

const setUid = async (params) => {
	console.log('setuid', params)
	for (const action in loginActions) {
		action === params.data.action && (isloginActions = true)
	}
	console.log('isloginActions', isloginActions)
	if(isloginActions) return true;
	let uid = wx.getStorageSync('uid');
	let access_token = await wx.getStorageSync('access_token')
	if (access_token && uid && !isloginActions) {
		params.data.params || (params.data.params = {});
		params.data.params['uid'] = uid;
		params.data['access_token'] = access_token;
		return true;
	}
	return false;
};

export const request = async (params) => {
	await setUid(params);
	let schema = wx.getStorageSync("schema");
	if (!schema && isloginActions && params.data.action !== 'wx-func.schema.get') {
		console.log('nengjinlaima')
		schema = wx.getStorageSync('schema') || await getSchema();
		wx.setStorageSync("schema", schema);
	}
	try {
		const opts = {
			url: "https://weapp-public-panel.ismartlife.me/sdk/action",
			method: "POST",
			header: {
				sign_method: "HMAC-SHA256",
				"Content-Type": "application/json",
				"x-fast-schema": schema,
			},
			data: params.data,
			json: true,
		};
		// console.log('00000', opts)
		const {
			statusCode,
			data,
			header
		} = await wxRequest({
			...opts
		});

		if (statusCode === 200) {
			if (data.success) {
				return data.result;
			}

			if ((+data.code === EXPIRDCODE || +data.code === INVALIDCODE) && params.data.action !== 'user.refreshToken') {
				const rSuccess = await refreshToken();
				if(!rSuccess) {
					wx.clearStorageSync();
					return 	wx.showModal({
						content: '登录已过期,请重新登录',
					})
				}
				if (rSuccess) return request(params);
			}
			errorInfo = {
				...errorInfo,
				errMsg: data.msg,
				errCode: data.code,
				t: data.t,
			};
			// console.log('errorInfo', errorInfo);
			wx.showToast({
				title: `code:${data.code}, message:${dara.msg}`,
				icon: 'none',
				duration: 3000,
				mask: true
			});
			return data;
		}
	} catch (e) {
		console.log('errorInfo', errorInfo);
	}
};

export default request;