import axios from 'axios'; import config from 'config'; import debug from 'debug'; var log = debug('hms'); const { client_id, client_secret } = config.has('service.hms') ? config.get('service.hms') : {}; const refreshToken = async () => { if (client_id) { const params = new URLSearchParams(); params.append('grant_type', 'client_credentials'); params.append('client_id', client_id); params.append('client_secret', client_secret); const res = await axios.post('https://oauth-login.cloud.huawei.com/oauth2/v3/token', params).catch(console.log); try { log(`HMS response: ${JSON.stringify(res.data)}`); const access = res.data; log(`HMS access token: ${access.access_token}`); return access.access_token; } catch (error) { log(error); return ''; } } return ''; }; export const send = async (msg, tokenList = []) => { const adminToken = await refreshToken(); if (adminToken) { const response = await axios.post(`https://push-api.cloud.huawei.com/v1/${client_id}/messages:send`, { headers: { 'Authorization': adminToken, 'Content-Type': 'application/json' }, body: { 'validate_only': false, 'message': { 'android': { 'fast_app_target': 2 }, 'data': { 'pushtype': 1, 'pushbody': { 'custom': { 'message': msg } } }, 'priority': 'high', 'delayWhileIdle': false, 'token': tokenList } } }).catch(log); log(`hcm: ${response.status}`); } };