1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- const request = require('./httpRequest.js');
- const url = require('./const.js');
- const HOST = url.apiUrl;
- function genAPIUrl(action) {
- return HOST + action;
- }
- // 登录
- function wxLogin(successcallback, failcallback) {
- wx.showToast({
- title: '登录中...',
- icon: 'loading',
- duration: 1500
- })
- wx.login({
- success: function(res) {
- if (res.code) {
- // 获取openid
- let url = genAPIUrl('wx/user/openId')
- let data = { code: res.code }
- return request.getInstance().url(url).data(data).send().success(successcallback).fail(failcallback);
- } else {
- console.log('获取用户登录态失败!' + res.errMsg)
- }
- }
- })
- }
- // 获取原来的 openid 和 session_key
- function getOpenidSessionKey(successcallback, failcallback) {
- if (wx.getStorageSync('user')) {
- successcallback(
- wx.getStorageSync('user'),
- //分享小程序按钮
- // wx.showShareMenu({
- // withShareTicket: true
- // })
- );
- return;
- }
- wxLogin(function(res) {
- if(res.statusCode == 200){
- let sessionKey = JSON.parse(res.data).session_key;
- getLoginSchedule(sessionKey, successcallback, failcallback);
- }
- },function(res) {
- failcallback(res);
- })
- }
- //登录
- function getLoginSchedule(sessionKey, successcallback, failcallback) {
- wx.getSetting({
- success: function(res) {
- // 已经授权,可以直接调用 getUserInfo 获取头像昵称
- wx.getUserInfo({
- withCredentials: true,
- success: function (res) {
- let url = genAPIUrl('wx/user');
- const userData = {
- encryptedData: res.encryptedData,
- sessionKey: sessionKey,
- iv: res.iv,
- code: wx.getStorageSync('uid') ? wx.getStorageSync('uid') : ''
- }
- request.getInstance().header({
- 'content-type': 'application/x-www-form-urlencoded'
- }).url(url).data(userData).method('POST').send().success(res => {
- wx.hideToast()
- wx.showToast({
- title: '登录成功',
- icon: 'success',
- duration: 1500
- })
- wx.setStorageSync('uid', res.data.data.id)
- wx.setStorageSync('user', res)
- successcallback(res)
- });
- },
- fail: function(res) {
- failcallback(res)
- }
- })
- }
- })
-
- }
- module.exports = {
- getOpenidSessionKey
- }
|