【七牛云短信】node.js使用七牛云发送短信demo

百度搜了一遍貌似也没有找到node对接七牛云SMS的案例;自己动手,丰衣足食!!!


const qiniu = require('qiniu')
const axios = require('axios')

 const accessKey = 'accessKey'
    const secretKey = 'secretKey'
    const template_id = 'template_id'
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    let url = 'https://sms.qiniuapi.com/v1/message'
 var tel = new Array("110xxx");
    var reqBody = {
      template_id,
      "mobiles": tel,
      "parameters": {
        "code": "短信模板字段,可能你的不是code;改下就行"
      }
    };
// 自己用axios写的方法
    reqBody = JSON.stringify(reqBody);
    let accessToken = generateAccessTokenV2(mac, url, 'POST', 'application/json', reqBody);

    let smsres = await axios.post(url, reqBody, {
      headers: { Authorization: accessToken, 'Content-Type': 'application/json' }
    })
    console.log(smsres.data);

  • 生成token方法;直接复制即可
// 创建 AccessToken 凭证
// @param mac            AK&SK对象
// @param requestURI     请求URL
// @param reqMethod      请求方法,例如 GET,POST
// @param reqContentType 请求类型,例如 application/json 或者  application/x-www-form-urlencoded
// @param reqBody        请求Body,仅当请求的 ContentType 为 application/json 或者
//                       application/x-www-form-urlencoded 时才需要传入该参数
exports.generateAccessTokenV2 = function (mac, requestURI, reqMethod, reqContentType, reqBody) {
  var u = new url.URL(requestURI);
  var path = u.pathname;
  var search = u.search;
  var host = u.host;
  var port = u.port;

  var access = reqMethod.toUpperCase() + ' ' + path;
  if (search) {
    access += search;
  }
  // add host
  access += '\nHost: ' + host;
  // add port
  if (port) {
    access += ':' + port;
  }

  // add content type
  if (reqContentType && (reqContentType === 'application/json' || reqContentType === 'application/x-www-form-urlencoded')) {
    access += '\nContent-Type: ' + reqContentType;
  }

  access += '\n\n';

  // add reqbody
  if (reqBody) {
    access += reqBody;
  }

  // console.log(access);

  var digest = exports.hmacSha1(access, mac.secretKey);
  var safeDigest = exports.base64ToUrlSafe(digest);
  return 'Qiniu ' + mac.accessKey + ':' + safeDigest;
};



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值