beego 阿里大鱼短信验证码接口

Deadly 提交于 2020-03-24 23:50:05

3 月,跳不动了?>>>

工作中需要用到短信登录注册验证,所以自己用beego写了个阿里大鱼的短信验证码接口

一、配置,beego的配置文件  conf/app.conf,这些注册阿里大鱼帐号就会分配给你,注册地址:http://www.alidayu.com/

sms_url=http://gw.api.taobao.com/router/rest
sms_type=normal
sms_AppKey=46745674567
sms_AppSecret=678467456745674567
sms_free_sign_name=一点通
sms_template_code=SMS_11060567

二、阿里大鱼的短信发送工具函数,我参照了https://github.com/ltt1987/alidayu这个包写的

package tools

import (
	"crypto/md5"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"sort"
	"strings"
	"time"

	"fmt"
)

func Send_alidayu(phone, sms_param string) (string, error) {
	sms_url := beego.AppConfig.String("sms_url")
	sms_type := beego.AppConfig.String("sms_type")
	sms_free_sign_name := beego.AppConfig.String("sms_free_sign_name")
	sms_template_code := beego.AppConfig.String("sms_template_code")
	sms_AppKey := beego.AppConfig.String("sms_AppKey")
	sms_AppSecret := beego.AppConfig.String("sms_AppSecret")

	req := httplib.Post(sms_url)

	m := map[string]string{
		"app_key":                     sms_AppKey,
		"timestamp":                   time.Now().Format("2006-01-02 15:04:05"),
		"v":                           "2.0",
		"method":                      "alibaba.aliqin.fc.sms.num.send",
		"partner_id":                  "top-apitools",
		"format":                      "json",
		"sms_type":                    sms_type,
		"rec_num":                     phone,
		"sms_free_sign_name":          sms_free_sign_name,
		"sms_template_code":           sms_template_code,
		"force_sensitive_param_fuzzy": "true",
		"sign_method":                 "md5",
		"sms_param":                   sms_param,
	}

	var keys []string
	for k := range m {
		keys = append(keys, k)
	}

	sort.Strings(keys)

	singString := sms_AppSecret
	for _, k := range keys {
		req.Param(k, m[k])
		singString += k + m[k]
	}
	singString += sms_AppSecret

	signByte := md5.Sum([]byte(singString))
	sign := strings.ToUpper(fmt.Sprintf("%x", signByte))
	req.Param("sign", sign)

	result, err := req.String()
	return result, err
}

三、使用方法,beego的controller中直接使用

func (this *Register) Test() {
	req, err := tools.Send_alidayu("15953163355", "{code:'8558',product:'一点通'}")
	fmt.Println(err)
	this.Ctx.WriteString(req)
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!