This article is a mirror article of machine translation, please click here to jump to the original article.

View: 14739|Reply: 3

[Interface] C# does not call Alibaba SMS dll, how to use http interface to send SMS

[Copy link]
Posted on 12/1/2018 6:37:34 PM | | |
  Some time ago, the company had a project that needed to use SMS notifications, and then I bought an Alibaba Cloud SMS for SMS interface development. But the project is running on the XP system, so the project must be the framework of .NET3.5, but the SMS DLL given by Alibaba can only be used in .net 4.0 and above, which is very embarrassing, fortunately Alibaba gave an example of java for HTTP, so I tried to write the method of calling Alibaba Cloud HTTP in C# according to the java code. Back to the point, go to the code! (I have also published in CSDN, personality guarantee is not a pirated post, thank you)  
public class SendShort
    {
        /// <summary>
        SMS interface C# call method
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetHtmlFormUrl(string url)
        {
            string strRet = null;
            if (url == null || url. Trim(). ToString() == "")
            {
                return strRet;
            }
            string targeturl = url. Trim(). ToString();
            try
            {
                HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(targeturl);
                hr. UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
                hr. Method = "GET";
                hr. Timeout = 30 * 60 * 1000;
                WebResponse hs = hr. GetResponse();
                Stream sr = hs. GetResponseStream();
                StreamReader ser = new StreamReader(sr, Encoding.Default);
                strRet = MessageHandle(ser. ReadToEnd());
            }
            catch (Exception ex)
            {
               strRet = "SMS sent failed!" +ex. Message;
            }
            return strRet;
        }
        /// <summary>
        Verify that the mobile number is legitimate
        /// </summary>
        /// <param name="str_handset"></param>
        /// <returns></returns>
        public static bool IsHandset(string str_handset)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_handset, @"^1[3|4|5|7|8][0-9]\d{8}$");
        }
        /// <summary>
        SMS verification code
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string SignDemo(string mobile, int code)
        {
            string accessKeyId = "Your accessKeyId ";
            string accessSecret = "your accessSecret";
            string nowDate = DateTime.Now.ToUniversalTime(). ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); GTM time
            Dictionary<string, string> keyValues = new Dictionary<string, string>(); Declare a dictionary
            1. System parameters
            keyValues.Add("SignatureMethod", "HMAC-SHA1");
            keyValues.Add("SignatureNonce", Guid.NewGuid(). ToString());
            keyValues.Add("AccessKeyId", accessKeyId);
            keyValues.Add("SignatureVersion", "1.0");
            keyValues.Add("Timestamp", nowDate);
            keyValues.Add("Format", "Json"); can be replaced with XML

            2. Business API parameters
            keyValues.Add("Action", "SendSms");
            keyValues.Add("Version", "2017-05-25");
            keyValues.Add("RegionId", "cn-hangzhou");
            keyValues.Add("PhoneNumbers", mobile);
            keyValues.Add("SignName", "Your Signature");
            keyValues.Add("TemplateParam", "{\"code\":\"" + code + "\"}");
            keyValues.Add("TemplateCode", "Your Template Number");
            keyValues.Add("OutId", "123");

            3. Remove the signature keyword
            if (keyValues.ContainsKey("Signature"))
            {
                keyValues.Remove("Signature");
            }

            4. Parameter key sorting
            Dictionary<string, string> ascDic = keyValues.OrderBy(o => o.Key). ToDictionary(o => o.Key, p => p.Value.ToString());
            5. Construct the string to be signed
            StringBuilder builder = new StringBuilder();
            foreach (var item in ascDic)
            {
                if (item. Key == "SignName")
                {

                }
                else
                {
                    builder. Append("&"). Append(specialUrlEncode(item. Key)). Append("="). Append(specialUrlEncode(item. Value));
                }
                if (item. Key == "RegionId")
                {
                    builder. Append("&"). Append(specialUrlEncode("SignName")). Append("="). Append(specialUrlEncode(keyValues["SignName"]));
                }
            }
            string sorteQueryString = builder. ToString(). Substring(1);

            StringBuilder stringToSign = new StringBuilder();
            stringToSign.Append("GET"). Append("&");
            stringToSign.Append(specialUrlEncode("/")). Append("&");
            stringToSign.Append(specialUrlEncode(sorteQueryString));

            string Sign = MySign(accessSecret + "&", stringToSign.ToString());
            6. The signature should also be encoded with a special URL at the end
            string signture = specialUrlEncode(Sign);
            Finally, print out the URL of the legitimate GET request
            string url = "http://dysmsapi.aliyuncs.com/?Signature=" + signture + builder;
            string result = GetHtmlFormUrl(url);
            return result;
        }
        /// <summary>
        URL encoding
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string specialUrlEncode(string temp)
        {

            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < temp. Length; i++)
            {
                string t = temp[i]. ToString();
                string k = HttpUtility.UrlEncode(t, Encoding.UTF8);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString(). Replace("+", "%20"). Replace("*", "%2A"). Replace("%7E", "~");
        }
        /// <summary>
        HMACSHA1 signature
        /// </summary>
        /// <param name="accessSecret"></param>
        /// <param name="stringToSign"></param>
        /// <returns></returns>
        public static string MySign(string accessSecret, string stringToSign)
        {
            try
            {
                var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(accessSecret));
                var dataBuffer = Encoding.UTF8.GetBytes(stringToSign);
                var hashBytes = hmacsha1. ComputeHash(dataBuffer);
                string stringbyte = BitConverter.ToString(hashBytes, 0). Replace("-", string. Empty). ToLower();
                byte[] bytes = strToToHexByte(stringbyte);
                return Convert.ToBase64String(bytes);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        String to 16 byte array
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        /// <summary>
        Message processing mechanisms
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string MessageHandle(string str)
        {
            MessageModel message = JsonConvert.DeserializeObject<MessageModel>(str);
            string result = "";
            switch (message. Code)
            {
                case "OK":
                    result = "SMS sent successful!";
                    break;
                case "isp. RAM_PERMISSION_DENY":
                    result = "RAM Permission DENY";
                    break;
                case "isv. OUT_OF_SERVICE":
                    result = "Business downtime";
                    break;
                case "isv. PRODUCT_UN_SUBSCRIPT":
                    result = "Alibaba Cloud customers who have not opened cloud communication products";
                    break;
                case "isv. PRODUCT_UNSUBSCRIBE":
                    result = "Product not opened";
                    break;
                case "isv. ACCOUNT_NOT_EXISTS":
                    result = "Account does not exist";
                    break;
                case "isv. ACCOUNT_ABNORMAL":
                    result = "Account Exception";
                    break;
                case "isv.SMS_TEMPLATE_ILLEGAL":
                    result = "SMS template is not legal";
                    break;
                case "isv.SMS_SIGNATURE_ILLEGAL":
                    result = "SMS signature is not legal";
                    break;
                case "isv. INVALID_PARAMETERS":
                    result = "parameter exception";
                    break;
                case "isv. MOBILE_NUMBER_ILLEGAL":
                    result = "illegal mobile phone number";
                    break;
                case "isv. MOBILE_COUNT_OVER_LIMIT":
                    result = "Number of mobile numbers exceeds limit";
                    break;
                case "isv. TEMPLATE_MISSING_PARAMETERS":
                    result = "template missing variable";
                    break;
                case "isv. BUSINESS_LIMIT_CONTROL":
                    result = "Business Current";
                    break;
                case "isv. INVALID_JSON_PARAM":
                    result = "JSON parameter is not legitimate, only string values are accepted";
                    break;
                case "isv. PARAM_LENGTH_LIMIT":
                    result = "Parameter exceeds length limit";
                    break;
                case "isv. PARAM_NOT_SUPPORT_URL":
                    result = "URL not supported";
                    break;
                case "isv. AMOUNT_NOT_ENOUGH":
                    result = "Insufficient account balance";
                    break;
                case "isv. TEMPLATE_PARAMS_ILLEGAL":
                    result = "Template variables contain illegal keywords";
                    break;
            }
            return result;
        }
    }

Score

Number of participants2MB+2 contribute+2 Collapse reason
Little scum + 1 + 1 Give it a thumbs up
admin + 1 + 1 Very powerful!

See all ratings





Previous:1000 buildings are hand-painted and beautiful
Next:Former Japanese Navy and Army Materials, PDF
Posted on 12/2/2018 9:00:04 AM |
Posted on 12/2/2018 10:19:01 AM |
Thanks to the code provided by the owner, send SMS through the HTTP simulation request interface, no need to call a large dll, give you a thumbs up
Posted on 12/14/2018 4:03:21 PM |
They are all masters
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com