最近为自己的客服系统增加了在线翻译功能
可以把访客任何语种消息翻译为中文
客服消息一键翻译为英文,详细演示效果可以注册唯一客服系统(gofly.v1kf.com),我审核通过后就可以体验了
详细golang版本的sdk如下:
package lib import ( "fmt" "github.com/tidwall/gjson" "kefu/tools" "net/url" ) type BaiduFanyi struct { AppId, AppSec string } func (this *BaiduFanyi) Translate(query, from, to string) (string, error) { salt := "1435660288" data := url.Values{} data.Set("q", query) data.Set("salt", salt) data.Set("appid", this.AppId) data.Set("from", from) data.Set("to", to) data.Set("sign", this.BuildSign(query, salt)) res, err := tools.PostForm("http://api.fanyi.baidu.com/api/trans/vip/translate", data) fmt.Println(res, err) res = gjson.Get(res, "trans_result.0.dst").String() res = tools.UrlDecode(res) return res, err } func (this *BaiduFanyi) BuildSign(query, salt string) string { str := fmt.Sprintf("%s%s%s%s", this.AppId, query, salt, this.AppSec) ret := tools.Md5(str) return ret }
使用方式如下:
baidu := &BaiduFanyi{ AppId: "2022070xxxxxx5", AppSec: "xxxxxxx", } res, err := baidu.Translate("hello", "en", "zh") log.Print(res, err) time.Sleep(1 * time.Second) res, err = baidu.Translate("taoshihan", "en", "zh") log.Print(res, err) time.Sleep(1 * time.Second) res, err = baidu.Translate("can i help you", "en", "zh") log.Print(res, err) time.Sleep(1 * time.Second) res, err = baidu.Translate("你好", "zh", "en") log.Print(res, err)
这个里面的MD5函数,以及urldeocde函数,以及发送post form数据函数
//发送http post请求数据为form func PostForm(url string, data url.Values) (string, error) { resp, err := http.PostForm(url, data) if err != nil { return "", err } defer resp.Body.Close() content, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(content), nil }
//md5加密 func Md5(src string) string { m := md5.New() m.Write([]byte(src)) res := hex.EncodeToString(m.Sum(nil)) return res }
func UrlDecode(str string) string { res, err := url.QueryUnescape(str) if err != nil { return "" } return res }