helper.js
2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Created by Tommy Huang on 18/03/21.
*/
const config = require('config-lite')({
config_basedir: __dirname,
config_dir: 'config'
})
const axios = require('axios')
const {URL} = require('url')
/**
* 获取用户微信 Token
* @param {string} code 微信返回的用户 code
*/
exports.getUserWxAccessTokenInfo = async function(code) {
const {data} = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.wx.appId}&secret=${config.wx.appSecret}&code=${code}&grant_type=authorization_code`)
if (data.access_token && data.refresh_token && data.openid) {
return data
} else {
return false
}
}
/**
* 刷新用户的 Token
* @param {string} refreshToken 微信返回的用户 refresh_token
*/
exports.refreshUserWxToken = async function(refreshToken) {
const {data} = await axios.get(`https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${config.wx.appId}&grant_type=refresh_token&refresh_token=${refreshToken}`)
if (data.access_token && data.refresh_token && data.openid) {
return data
} else {
return false
}
}
/**
* 拉取用户信息
* @param {string} token 微信返回的用户 access_token
* @param {string} openId 微信返回的用户 openid
*/
exports.getUserWxInfo = async function(token, openId) {
const {data} = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openId}&lang=zh_CN`)
if (data.openid && data.nickname && data.headimgurl) {
return data
} else {
return false
}
}
/**
* 发送验证码
* @param {string} phone 要发送验证码的手机号
*/
exports.sendVerificationCode = async function (phone) {
if (!phone) return {success: false, msg: '缺少参数'}
const code = randomWord(false, 4, 4)
var url = `http://api.chanzor.com/send?account=${config.sms.account}&password=${config.sms.password}&mobile=${phone}&content=【七彩贷】验证码:${code},如非本人操作,请忽略本短信`
url = new URL(url).href
let { data } = await axios.get(url)
console.log(data)
if (data.status === 0) {
return {success: true, code: code}
} else {
return {success: false, msg: data.desc}
}
}
/**
* 产生任意长度随机数字组合
* @param {bool} randomFlag 是否任意长度
* @param {num} min 任意长度最小位[固定位数]
* @param {num} max 任意长度最大位
*/
function randomWord (randomFlag, min, max) {
let str = ""
let range = min
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if (randomFlag) {
range = Math.round(Math.random() * (max - min)) + min
}
for (let i = 0 ; i < range; i++) {
let pos = Math.round(Math.random() * (arr.length-1))
str += arr[pos]
}
return str
}