net core and WPF to develop shengxunwei online customer service system: call Baidu translation interface to realize real-time automatic translation

🚀 Quality resource sharing 🚀

Learning route guidance (click to unlock)Knowledge orientationCrowd positioning
🧡 Python actual wechat ordering applet 🧡Progressive classThis course is a perfect combination of python flask+ wechat applet. From project construction to Tencent cloud deployment and launch, it creates a full stack ordering system.
💛 Python quantitative transaction practice 💛beginner Take you hand in hand to build an easy to expand, safer and more efficient quantitative trading system

In my spare time net core wrote an online customer service system. And I wrote a series of articles in the blog Garden to introduce the development process.

I left this small system I wrote in my spare time on the Internet. One after another, people came to me for a private version, and I gave it to them. After all, the original intention of the software industry was to provide free and shared services. Later, I simply officially sent a private version to others to download directly. Hope to build: open, open source and sharing. Strive to build net community.

In the second half of 2021, I was contacted by friends who said they were engaged in the foreign trade industry and hoped that the customer service system could realize two-way real-time automatic translation between customer service and visitors.

At first, I thought it was complicated. I didn't do this function. Later, more and more friends asked me. I carefully investigated this requirement and found that it is very simple to implement it through the interface on the public cloud! It is no exaggeration to say that the whole docking process is completed in 10 minutes.

This article will introduce in detail the whole process of Baidu translation interface registration, opening and docking, as well as the source code, hoping to be useful to you.

See the implementation effect first

The customer service end program is displayed by comparing the original text with the translation.

The visitor side is displayed in the visitor language.

To set the default translation of all visitors' messages, or the customer service can decide whether to translate according to different visitors.

brief introduction

Sunway online customer service and marketing system is based on net core / WPF, an online customer service software, aims to be open, open source and shared. Strive to build net community.

Full privatization package download address

💾 https://kf.shengxunwei.com

If you like it, please give it a favor. Thank you~

Installation and deployment instructions

📕 https://docs.shengxunwei.com/Post/f7bc8496-14ee-4a53-07b4-08d8e3da6269

Docking use of Baidu translation

Visit Baidu translation open platform, register an account and authenticate.

https://fanyi-api.baidu.com

Open general translation API

Note:

  • In rare languages (e.g. Ukraine, Philippines, Indonesia), only the enterprise certified Premium Edition can be called, and the uncertified non Premium Edition interface will return an error of 58001.
  • Please select to open "exclusive edition". The "Standard Version" QPS is only 1, and only one translation interface can be called per second, which cannot meet the normal use needs of the customer service system.

Create app

"Server callback address" is left blank.
"Server address" can be left blank, or the IP address of the server deploying the customer service system can be filled in.

Get APP ID and key

Enter the "Developer Information" screen, view the APP ID and key in the "application information", save them for backup, and use them in the subsequent main program configuration of the customer service system.

Call the translation interface with C\

Access mode
The translation API provides multilingual translation services through the HTTP interface. You only need to call the general translation API, pass in the content to be translated, and specify the source language to be translated (support automatic detection of source language) and the type of target language to get the corresponding translation results.

Generic translation API HTTPS address:
https://fanyi-api.baidu.com/api/trans/vip/translate

Signature generation method
Signature is a string generated by MD5 algorithm to ensure call security. The length of the generated signature is 32 bits, and the English characters in the signature are in lowercase format.

Generation method:
Step1. splice the APPID(appid), translation query(q, note that it is UTF-8 encoding), random number (salt), and the key allocated by the platform (which can be viewed in the management console) in the request parameters to obtain the string 1 in the order of appid+q+salt+ key.
Step2. md5 the string 1 to get a 32-bit lowercase sign.
Note:

  1. The text (q) to be translated shall be encoded in UTF-8;
  2. When generating the signature splicing appid+q+salt+ key string, Q does not need to do URL encode. After generating the signature, it is necessary to do URL encode for the text field Q to be translated before sending the HTTP request;
    3. if you encounter a 54001 signature error, please check whether your signature generation method is correct. When splicing and encrypting a sign, q does not need to do URL encode. Many developers encounter a signature error because they did URL encode before splicing a sign;
    4. after the signature is generated and the HTTP request is sent, if the query is spliced on the url, the query needs to be url encoded.

input parameter
Request method: GET or POST can be used. If POST is used, please specify the content type as: application/x-www-form-urlencoded
Character coding: unified UTF-8 coding format
query length: to ensure the translation quality, please control the length of a single request within 6000 bytes (Chinese characters are about 2000 input parameters)

code

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Web;

namespace TransAPICSharpDemo
{
    class Program
 {
        static void Main(string[] args)
        {
            // original text
            string q = "apple";
            // source language
            string from = "en";
            // target language
            string to = "zh";
            // Change to your APP ID
            string appId = "2015063000000001";
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            // Change to your key
            string secretKey = "12345678";
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            Console.WriteLine(retString);
            Console.ReadLine();
        }
        // Calculate MD5 value
        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // Convert string to byte array
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // Call encryption method
            byte[] byteNew = md5.ComputeHash(byteOld);
            // Convert encrypted results to strings
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // Converts bytes to hexadecimal strings,
                sb.Append(b.ToString("x2"));
            }
            // Returns an encrypted string
            return sb.ToString();
        }
    }
}


When writing your code, replace the APP ID and key in the above example code with the one you got when you registered and opened Baidu translate!

Hope to build: open, open source and sharing. Strive to build net community.

If you like it, please give it a favor. Thank you~

Tags: Flask .NET computer

Posted by zak on Mon, 30 May 2022 23:59:33 +0530