Esempio n. 1
0
        static void Main(string[] args)
        {
            //以下字段换成自己的
            string regionId        = "cn-hangzhou";
            string accessKeyId     = "xxxxxxxx";
            string accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
            string signName        = "xxxxxxxxxx";
            string phoneNumbers    = "15xxxxxxxxx";
            string templateCode    = "SMS_73985016";
            string templateParam   = "{\"code\":\"123456\", \"product\":\"MyProduct\"}";


            IClientProfile clientProfile = DefaultProfile.GetProfile(regionId, accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint(regionId, regionId, "Dysmsapi", "dysmsapi.aliyuncs.com");

            IAcsClient acsClient = new DefaultAcsClient(clientProfile);

            SendSmsRequest request = new SendSmsRequest();

            request.SignName      = signName;
            request.TemplateCode  = templateCode;
            request.PhoneNumbers  = phoneNumbers;
            request.TemplateParam = templateParam;

            try
            {
                SendSmsResponse response = acsClient.GetAcsResponse(request);
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 2
0
        public static int SendFailSMS(Record record)
        {
            Credential cred = new Credential
            {
                SecretId  = "AKIDqZ1DBslX2NUSJvv0U4RYP0LJ4YEeEnTu",
                SecretKey = "PULL6aoKagW5PSFp0sUqxiDSRGpg6EBu"
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = ("sms.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            SmsClient      client = new SmsClient(cred, "ap-nanjing", clientProfile);
            SendSmsRequest req    = new SendSmsRequest();

            req.PhoneNumberSet   = new String[] { "+86" + record.phone };
            req.TemplateID       = "692782";
            req.SmsSdkAppid      = "1400410910";
            req.Sign             = "EVA记录";
            req.TemplateParamSet = new String[] { record.name };

            SendSmsResponse resp = client.SendSmsSync(req);

            if (resp.SendStatusSet[0].Code == "Ok")
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
        public virtual async Task HandleEventAsync(UserUpdatedEventData eventData)
        {
            var user = await _userManager.GetUserByIdAsync(eventData.UserId);

            user.Surname = eventData.PhoneNumber;
            await _userManager.UpdateAsync(user);

            await _userManager.ChangePhoneNumberAsync(user, eventData.PhoneNumber, string.Empty);

            try
            {
                Credential cred = new Credential
                {
                    SecretId  = "AKID1sZ03uwxf9Ub",
                    SecretKey = "JEyWwAA0bxBE4jAML"
                };

                ClientProfile clientProfile = new ClientProfile();
                HttpProfile   httpProfile   = new HttpProfile();
                httpProfile.Endpoint      = ("sms.tencentcloudapi.com");
                clientProfile.HttpProfile = httpProfile;

                SmsClient      client    = new SmsClient(cred, "ap-shanghai", clientProfile);
                SendSmsRequest req       = new SendSmsRequest();
                string         strParams = "{\"PhoneNumberSet\":[\"+8618538705067\"],\"TemplateID\":\"186797\",\"Sign\":\"江南艺考\",\"TemplateParamSet\":[\"王彤\",\"最近学习好\",\"成绩提升很快\"],\"SmsSdkAppid\":\"1466134967\"}";
                req = SendSmsRequest.FromJsonString <SendSmsRequest>(strParams);

                SendSmsResponse resp = client.SendSms(req).ConfigureAwait(false).GetAwaiter().GetResult();;
                Logger.Info(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Logger.Error(e.ToString());
            }
        }
Esempio n. 4
0
    public static SendSmsResponse sendSms()
    {
        IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

        DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient      acsClient = new DefaultAcsClient(profile);
        SendSmsRequest  request   = new SendSmsRequest();
        SendSmsResponse response  = null;

        try
        {
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限�?1000个手机号�?,批量调用相对于单条调用及时�?�稍有延�?,验证码类型的短信推荐使用单条调用的方�?
            request.PhoneNumbers = "19940867612";
            //必填:短信签名-可在短信控制台中找到
            request.SignName = "小龙�?123";
            //必填:短信模板-可在短信控制台中找到
            request.TemplateCode = "SMS_135027712";
            //可�??:模板中的变量替换JSON�?,如模板内容为"亲爱�?${name},您的验证码为${code}"�?,此处的�?�为
            request.TemplateParam = "{\"code\":\"123456\"}";
            //可�??:outId为提供给业务方扩展字�?,�?终在短信回执消息中将此�?�带回给调用�?
            request.OutId = "yourOutId";
            //请求失败这里会抛ClientException异常
            response = acsClient.GetAcsResponse(request);
        }
        catch (ServerException e)
        {
            Console.WriteLine(e.ErrorCode);
        }
        catch (ClientException e)
        {
            Console.WriteLine(e.ErrorCode);
        }
        return(response);
    }
Esempio n. 5
0
        public bool SendMessage(string mobile, string signName, string tempCode, string param)
        {
            IAcsClient     acsClient = new DefaultAcsClient(_clientProfile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = mobile;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = signName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = tempCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = param;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "21212121211";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                System.Console.WriteLine(sendSmsResponse.Message);
                return(true);
            }
            catch (ServerException e)
            {
                System.Console.WriteLine("Hello World!");
                return(false);
            }
            catch (ClientException e)
            {
                System.Console.WriteLine("Hello World!");
                return(false);
            }
        }
Esempio n. 6
0
        public static Message Execute(string restaurantName, string deliveryTime, string customerPhoneNumber)
        {
            var TO_NUMBER        = customerPhoneNumber;
            var FROM_NAME        = "Takeaway.com";
            var TEXT             = $"Thank you for ordering from {restaurantName}! You will recieve your order in {deliveryTime}.";
            var NEXMO_API_KEY    = Environment.GetEnvironmentVariable("NEXMO_API_KEY");
            var NEXMO_API_SECRET = Environment.GetEnvironmentVariable("NEXMO_API_SECRET");

            var credentials = Credentials.FromApiKeyAndSecret(
                NEXMO_API_KEY,
                NEXMO_API_SECRET
                );

            var vonageClient = new NexmoClient(credentials);


            SendSmsResponse response = vonageClient.SmsClient.SendAnSms(new SendSmsRequest()
            {
                To   = TO_NUMBER,
                From = FROM_NAME,
                Text = TEXT
            });

            return(new Message(TEXT, response.Messages.FirstOrDefault().Status));
        }
Esempio n. 7
0
        // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
        //const String accessKeyId = "LTAIUUvOWA7LmOVz";
        //const String accessKeySecret = "nIpEkq1SEvRndAcyGIqsLiisIQLo6e";
        public static SendSmsResponse sendSms(String accessKeyId, String accessKeySecret, SendSmsRequest request)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //SendSmsRequest request = new SendSmsRequest();
            SendSmsResponse response = null;

            try
            {
                ////必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                //request.PhoneNumbers = "13918416905";
                ////必填:短信签名-可在短信控制台中找到
                //request.SignName = "晟湾国际";
                ////必填:短信模板-可在短信控制台中找到
                //request.TemplateCode = "SMS_127515001";
                ////可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                //request.TemplateParam = "{\"code\":\"123456\"}";
                ////可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = System.DateTime.Now.ToLongTimeString(); //"yourOutId";
                //请求失败这里会抛ClientException异常
                response = acsClient.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                throw e;
            }
            catch (ClientException e)
            {
                throw e;
            }
            return(response);
        }
Esempio n. 8
0
        /// <summary>
        /// Парсит ответ запроса отправки смс и мапит к классу SendSmsResponse
        /// </summary>
        /// <param name="xml">XML ответ запроса отправки смс</param>
        /// <returns>Возвращает ответ приведенный к классу SendSmsResponse</returns>
        public static SendSmsResponse ParseSendSmsResponse(string xml)
        {
            if (string.IsNullOrWhiteSpace(xml))
            {
                throw new ArgumentException("xml не может быть пустым", "xml");
            }
            try
            {
                var document = new XmlDocument();
                document.LoadXml(xml);
                var response = new SendSmsResponse()
                {
                    Id                = document.GetElementsByTagName("id").Item(0).InnerText,
                    Status            = int.Parse(document.GetElementsByTagName("status").Item(0).InnerText),
                    StatusDescription = SmsProNikitaStatuses.GetSendSmsStatusDescription(int.Parse(document.GetElementsByTagName("status").Item(0).InnerText)),
                    Phones            = int.Parse(document.GetElementsByTagName("phones").Item(0).InnerText),
                    SmsPart           = int.Parse(document.GetElementsByTagName("smscnt").Item(0).InnerText),
                    Message           = document.GetElementsByTagName("message").Item(0)?.InnerText
                };

                return(response);
            }
            catch (Exception e)
            {
                throw new ParseResponseException("Error Parse Send Sms Response", e);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 发送短信
        /// add by fruitchan
        /// update liuyu 2018/03/19
        /// 2016-12-18 00:12:30
        /// </summary>
        /// <param name="recNum">目标手机号,多个手机号可以逗号分隔</param>
        /// <param name="templateCode">管理控制台中配置的审核通过的短信模板的模板CODE(状态必须是验证通过)</param>
        /// <param name="paramString">短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。 例如:短信模板为:“接受短信验证码${no}”,此参数传递{“no”:”123456”},用户将接收到[短信签名]接受短信验证码123456</param>
        /// <returns>发送结果</returns>
        private static string SendSMS(string recNum, string templateCode, string paramString)
        {
            IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, AccessKeyID, AccessKeySecret);

            DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
            IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();
            SendSmsRequest request = new SendSmsRequest();

            try
            {
                request.SignName     = "我要去度假";
                request.TemplateCode = templateCode;
                //request.RecNum = recNum;
                //request.ParamString = paramString;
                //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                request.PhoneNumbers  = recNum;
                request.TemplateParam = paramString;
                SendSmsResponse httpResponse = client.GetAcsResponse(request);
                if (httpResponse.HttpResponse.Status == 200)
                {
                    return("ok");
                }
            }
            catch (ServerException se)
            {
                return("发送短信频繁,请1小时后再试!");
            }
            catch (ClientException ce)
            {
                return("发送短信频繁,请1小时后再试!");
            }

            return("发送短信失败!");
        }
Esempio n. 10
0
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <returns></returns>
        static SendSmsResponse SendSms()
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", _accessKey, _accessSecret);
            IAcsClient     client  = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();

            try
            {
                request.PhoneNumbers  = "<your phoneNumbers>";
                request.SignName      = "<your signname>";
                request.TemplateCode  = "<your templatecode>";
                request.TemplateParam = "<your templateparam>";
                SendSmsResponse httpResponse = client.GetAcsResponse(request);
                Console.WriteLine(httpResponse.Code);
                Console.WriteLine(httpResponse.BizId);
                Console.WriteLine(httpResponse.Message);
                Console.WriteLine(httpResponse.RequestId);
                return(httpResponse);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                throw e;
            }
            catch (ClientException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                throw e;
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            SendSmsResponse reponse = sendSms();

            Console.Write("短信发送接口返回的结果----------------");
            Console.WriteLine("Code=" + reponse.Code);
            Console.WriteLine("Message=" + reponse.Message);
            Console.WriteLine("RequestId=" + reponse.RequestId);
            Console.WriteLine("BizId=" + reponse.BizId);
            Console.WriteLine();
            Thread.Sleep(3000);

            if (reponse.Code != null && reponse.Code == "OK")
            {
                QuerySendDetailsResponse queryReponse = querySendDetails(reponse.BizId);

                Console.WriteLine("短信明细查询接口返回数据----------------");
                Console.WriteLine("Code=" + queryReponse.Code);
                Console.WriteLine("Message=" + queryReponse.Message);
                foreach (QuerySendDetailsResponse.QuerySendDetails_SmsSendDetailDTO smsSendDetailDTO in queryReponse.SmsSendDetailDTOs)
                {
                    Console.WriteLine("Content=" + smsSendDetailDTO.Content);
                    Console.WriteLine("ErrCode=" + smsSendDetailDTO.ErrCode);
                    Console.WriteLine("OutId=" + smsSendDetailDTO.OutId);
                    Console.WriteLine("PhoneNum=" + smsSendDetailDTO.PhoneNum);
                    Console.WriteLine("ReceiveDate=" + smsSendDetailDTO.ReceiveDate);
                    Console.WriteLine("SendDate=" + smsSendDetailDTO.SendDate);
                    Console.WriteLine("SendStatus=" + smsSendDetailDTO.SendStatus);
                    Console.WriteLine("Template=" + smsSendDetailDTO.TemplateCode);
                }
            }
        }
Esempio n. 12
0
        //internal void send()
        //{
        //    try
        //    {
        //        /* 必要步骤:
        //         * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        //         * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        //         * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        //         * 以免泄露密钥对危及你的财产安全。
        //         * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
        //        Credential cred = new Credential
        //        {
        //            SecretId = "我的id",
        //            SecretKey = "密匙"
        //        };
        //        /*
        //        Credential cred = new Credential {
        //            SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
        //            SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
        //        };*/

        //        /* 非必要步骤:
        //         * 实例化一个客户端配置对象,可以指定超时时间等配置 */
        //        ClientProfile clientProfile = new ClientProfile();
        //        /* SDK默认用TC3-HMAC-SHA256进行签名
        //      * 非必要请不要修改这个字段 */
        //        clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
        //        /* 非必要步骤
        //         * 实例化一个客户端配置对象,可以指定超时时间等配置 */
        //        HttpProfile httpProfile = new HttpProfile();
        //        /* SDK默认使用POST方法。
        //      * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
        //        httpProfile.ReqMethod = "GET";
        //        /* SDK有默认的超时时间,非必要请不要进行调整
        //      * 如有需要请在代码中查阅以获取最新的默认值 */
        //        httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)
        //        /* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务
        //      * 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */
        //        httpProfile.Endpoint = "sms.tencentcloudapi.com";
        //        // 代理服务器,当你的环境下有代理服务器时设定
        //        httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

        //        clientProfile.HttpProfile = httpProfile;
        //        /* 实例化要请求产品(以sms为例)的client对象
        //      * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */
        //        SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

        //        /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        //      * 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        //      * 属性可能是基本类型,也可能引用了另一个数据结构
        //      * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
        //        SendSmsRequest req = new SendSmsRequest();

        //        /* 基本类型的设置:
        //      * SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        //      * SDK提供对基本类型的指针引用封装函数
        //      * 帮助链接:
        //      * 短信控制台: https://console.cloud.tencent.com/sms/smslist
        //      * sms helper: https://cloud.tencent.com/document/product/382/3773 */

        //        req.SmsSdkAppid = "1400787878";
        //        /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */
        //        req.Sign = "雪雪雪个人技术站";
        //        /* 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper] */
        //        req.ExtendCode = "x";
        //        /* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */
        //        req.SenderId = "";
        //        /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
        //        req.SessionContext = "";
        //        /* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        //         * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/
        //        req.PhoneNumberSet = new String[] { "+8618030297576" };
        //        /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
        //        req.TemplateID = "590943";
        //        /* 模板参数: 若无模板参数,则设置为空*/
        //        req.TemplateParamSet = new String[] { "666" };


        //        // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
        //        // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
        //        SendSmsResponse resp = client.SendSmsSync(req);

        //        // 输出json格式的字符串回包
        //        Console.WriteLine(AbstractModel.ToJsonString(resp));
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.ToString());
        //    }
        //    Console.Read();
        //}

        internal void Send()
        {
            try
            {
                Credential cred = new Credential
                {
                    SecretId  = "AKIDKeRJuDD5i4AKVjdwvjfLkwrUqMzLdGpW",
                    SecretKey = "avzqRlB44AONALIzJMccMp42jBMwFIzP"
                };

                ClientProfile clientProfile = new ClientProfile();
                HttpProfile   httpProfile   = new HttpProfile();
                httpProfile.Endpoint      = ("sms.tencentcloudapi.com");
                clientProfile.HttpProfile = httpProfile;

                SmsClient      client    = new SmsClient(cred, "ap-beijing", clientProfile);
                SendSmsRequest req       = new SendSmsRequest();
                string         strParams = "{\"PhoneNumberSet\":[\"+8618030297576\"],\"TemplateID\":\"590943\",\"Sign\":\"雪雪雪个人技术站\",\"TemplateParamSet\":[\"123\"],\"SmsSdkAppid\":\"1400358718\"}";
                req = SendSmsRequest.FromJsonString <SendSmsRequest>(strParams);
                SendSmsResponse resp = client.SendSmsSync(req);
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
Esempio n. 13
0
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="content"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public SendSmsResponse SendSms(string phone, string content, SmsTemplateState template)
        {
            var templateParam    = string.Empty;
            var verificationCode = string.Empty;

            switch (template)
            {
            case SmsTemplateState.Login:
                verificationCode = new Random().Next(1000, 10000).ToString();
                templateParam    = "{\"code\":\"" + verificationCode + "\"}";
                break;

            case SmsTemplateState.Inform:
                templateParam = "{\"code\":\"" + content + "\"}";
                //templateParam = "{\"code\":\"" + content + "\",\"address\":\"" + Address + "\"}";
                break;
            }
            //IsSms = 1 表示启用短信验证
            SendSmsResponse result;

            if (IsSms == "1")
            {
                result      = SendValMsg(phone, GetDescription(template), templateParam);
                result.Code = verificationCode;
            }
            else
            {
                result = new SendSmsResponse()
                {
                    Code = "8888"
                };
            }
            return(result);
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            DefaultProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);

            profile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名(状态必须是验证通过)"
                //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE(状态必须是验证通过)"
                //request.RecNum = "13567939485";//"接收号码,多个号码可以逗号分隔"
                //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。"
                //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                request.PhoneNumbers  = "18843406621";
                request.SignName      = "李华明";
                request.TemplateCode  = "SMS_140275003";
                request.TemplateParam = "{\"code\":\"dazhutizi\"}";
                request.OutId         = "xxxxxxxx";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                System.Console.WriteLine(sendSmsResponse.Message);
            }
            catch (ServerException e)
            {
                System.Console.WriteLine("ServerException");
            }
            catch (ClientException e)
            {
                System.Console.WriteLine("ClientException");
            }
        }
Esempio n. 15
0
        private static string accessKeySecret = "NuW1BiPbBRxGTYvyB6zASvjUccaDOd"; //你的accessKeySecret

        private bool Send(string mobile, string template, string param)
        {
            var            result  = true;
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = mobile;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "五福天下";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = template;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = param;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "21212121211";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                result = false;
            }
            catch (ClientException e)
            {
                result = false;
            }

            return(result);
        }
Esempio n. 16
0
        public void Send(string phone, string signName, string templateCode, object param, string outId = null)
        {
            SendSmsRequest sendSmsRequest = new SendSmsRequest();

            try
            {
                sendSmsRequest.PhoneNumbers  = phone;
                sendSmsRequest.SignName      = signName;
                sendSmsRequest.TemplateCode  = templateCode;
                sendSmsRequest.TemplateParam = SerializeHelper.ToJson(param);
                sendSmsRequest.OutId         = outId;
                SendSmsResponse acsResponse = Client.GetAcsResponse(sendSmsRequest);
                if (!acsResponse.HttpResponse.isSuccess())
                {
                    throw new AceException("Send sms failed: " + acsResponse.Message);
                }
            }
            catch (ServerException ex)
            {
                logger.LogError(ex, "Send sms to [" + phone + "," + signName + "," + templateCode + "] failed!");
                throw new AceException("Send sms failed: " + ex.Message);
            }
            catch (ClientException ex2)
            {
                logger.LogError(ex2, "Send sms to [" + phone + "," + signName + "," + templateCode + "] failed!");
                throw new AceException("Send sms failed: " + ex2.Message);
            }
        }
Esempio n. 17
0
        internal static AliYunSmsResponse SMSRequest(SendSmsRequest request)
        {
            AliYunSmsResponse rsp     = new AliYunSmsResponse();
            IClientProfile    profile = DefaultProfile.GetProfile("cn-hangzhou", Config.accessKeyId, Config.accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", Config.product, Config.domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            try
            {
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                rsp = CheckSMSCode.CheckResponse(sendSmsResponse.Code);
            }
            catch (ServerException e)
            {
                rsp.IsSuccess = false;
                rsp.ErrorMsg  = e.Message;
            }
            catch (ClientException e)
            {
                rsp.IsSuccess = false;
                rsp.ErrorMsg  = e.Message;
            }
            return(rsp);
        }
Esempio n. 18
0
        //语音短信
        public static void Voice(string apiurl)
        {
            StringBuilder arge = new StringBuilder();

            arge.AppendFormat("Account={0}", "账号");
            arge.AppendFormat("&Pwd={0}", "接口号码");
            arge.AppendFormat("&Content={0}", "123456");//4-8位数字
            arge.AppendFormat("&Mobile={0}", "手机号码");
            string weburl = apiurl + "/SmsService/Voice";
            string resp   = common.PushToWeb(weburl, arge.ToString(), Encoding.UTF8);

            Console.WriteLine("Voice:" + resp);
            try
            {
                SendSmsResponse response = JsonConvert.DeserializeObject <SendSmsResponse>(resp);
                if (response.Code == 0)
                {
                    //成功
                }
                else
                {
                    //失败
                }
            }
            catch (Exception ex)
            {
                //记录日志
            }
        }
Esempio n. 19
0
        public static void SendMsg()
        {
            IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);

            DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名(状态必须是验证通过)"
                //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE(状态必须是验证通过)"
                //request.RecNum = "13567939485";//"接收号码,多个号码可以逗号分隔"
                //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。"
                //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                request.PhoneNumbers  = "1350000000";
                request.SignName      = "xxxxxx";
                request.TemplateCode  = "SMS_xxxxxxx";
                request.TemplateParam = "{\"code\":\"123\"}";
                request.OutId         = "xxxxxxxx";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                //todo 接口错误码 https://help.aliyun.com/knowledge_detail/57717.html?spm=5176.doc56189.6.582.Emujs1
                //System.Console.WriteLine(sendSmsResponse.Message);
            }
            catch (ServerException e)
            {
                System.Console.WriteLine("ServerException");
            }
            catch (ClientException e)
            {
                System.Console.WriteLine("ClientException");
            }
        }
Esempio n. 20
0
    public static SendSmsResponse sendSms(string phone, string verCode)
    {
        IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

        DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient      acsClient = new DefaultAcsClient(profile);
        SendSmsRequest  request   = new SendSmsRequest();
        SendSmsResponse response  = null;

        try
        {
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.PhoneNumbers = phone;
            //必填:短信签名-可在短信控制台中找到
            request.SignName = "大富豪";
            //必填:短信模板-可在短信控制台中找到
            request.TemplateCode = "SMS_133510033";
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.TemplateParam = "{\"code\":\"" + verCode + "\"}";
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.OutId = "yourOutId";
            //请求失败这里会抛ClientException异常
            response = acsClient.GetAcsResponse(request);
        }
        catch (Aliyun.Acs.Core.Exceptions.ServerException e)
        {
            Debug.Log(e.ErrorCode);
        }
        catch (ClientException e)
        {
            Debug.Log(e.ErrorCode);
        }
        return(response);
    }
Esempio n. 21
0
        public static SendSmsResponse sendSms(AliyunSendMsgModel msg)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient      acsClient = new DefaultAcsClient(profile);
            SendSmsRequest  request   = new SendSmsRequest();
            SendSmsResponse response  = null;

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = msg.PhoneNumbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = msg.SignName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = msg.TemplateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = msg.TemplateParam;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = msg.OutId;
                //请求失败这里会抛ClientException异常
                response = acsClient.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e.ErrorCode);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e.ErrorCode);
            }
            return(response);
        }
Esempio n. 22
0
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="phoneNumber">手机号</param>
        /// <param name="SMSCode">验证码</param>
        public static string SendMessage(string phoneNumber, string SMSCode)
        {
            string         Result  = string.Empty;
            IClientProfile profile = DefaultProfile.GetProfile("cn-hanghzou", accessKeyId, accessKeySeret);

            DefaultProfile.AddEndpoint("cn-hanghzou", "cn-hanghzou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = phoneNumber;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "正品汇";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = "SMS_67206006";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = "{\"code\":\"" + SMSCode + "\"}";
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "yourOutId";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                Result = sendSmsResponse.Code;
            }
            catch (Exception)
            {
                throw;
            }

            return(Result);
        }
Esempio n. 23
0
        public String accessKeySecret = "hNHBRsNbOCbyyK0XVyVnj64Xv9OwHN"; //阿里短信accessKeySecret,

        /// <summary>
        /// 发送短信
        /// </summary>
        public String SendMsm(YaeherSendMsm sendMsmInfo)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            //初始化ascClient,暂时不支持多region(请勿修改)
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式,发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
                request.PhoneNumbers = sendMsmInfo.PhoneNumbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "深圳怡禾健康管理有限公司";
                //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
                request.TemplateCode = MsnTemplateCode(sendMsmInfo.MessageType);
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = sendMsmInfo.TemplateParam;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = sendMsmInfo.OutId;
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                return(sendSmsResponse.Message);
            }
            catch (ServerException e)
            {
                return(e.ToString());
            }
        }
Esempio n. 24
0
 /// <summary>
 /// 设置用户手机验证码
 /// </summary>
 /// <param name="Phone">手机号码</param>
 /// <returns></returns>
 public string SetUserPhoneCodeCached(string Phone)
 {
     //设置验证码是否能重新发送
     if (MemCacheHelper2.Instance.Cache.Add("ResetPhoneCode_" + Phone, true, DateTime.Now.AddMinutes(1)))
     {
         var randNum = RandHelper.Instance.Number(4);
         //发送手机验证码
         SendSmsResponse Email = SendMail.Instance.SendResetEmail(Phone, randNum);
         if (Email.Code.ToUpper() == "OK")
         {
             //储存手机验证码
             if (MemCacheHelper2.Instance.Cache.Set("UserPhoneCode_" + Phone, randNum, DateTime.Now.AddMinutes(30)))
             {
                 return("手机验证码发送成功!");
             }
             else
             {
                 return("手机验证码储存失败,请联系管理员!");
             }
         }
         else
         {
             return("阿里云错误:" + Email.Message);
         }
     }
     else
     {
         return("还未到1分钟,验证码不能重新发送!");
     }
 }
        public async Task SendingAnSmsMessage()
        {
            SmsClient client = InstrumentClient(
                new SmsClient(
                    TestEnvironment.ConnectionString,
                    InstrumentClientOptions(new SmsClientOptions())));

            #region Snippet:Azure_Communication_Sms_Tests_Troubleshooting
            try
            {
                #region Snippet:Azure_Communication_Sms_Tests_SendAsync
                SendSmsResponse result = await client.SendAsync(
                    //@@ from: new PhoneNumber("+18001230000"), // Phone number acquired on your Azure Communication resource
                    //@@ to: new PhoneNumber("+18005670000"),
                    /*@@*/ from : new PhoneNumberIdentifier(TestEnvironment.PhoneNumber),
                    /*@@*/ to : new PhoneNumberIdentifier(TestEnvironment.PhoneNumber),
                    message : "Hi");

                Console.WriteLine($"Sms id: {result.MessageId}");
                #endregion Snippet:Azure_Communication_Sms_Tests_SendAsync
                /*@@*/ Assert.IsFalse(string.IsNullOrWhiteSpace(result.MessageId));
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
            }
            #endregion Snippet:Azure_Communication_Sms_Tests_Troubleshooting
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
Esempio n. 26
0
        public static int SendQueRenSms(Record record, InterviewTime interview)
        {
            Credential cred = new Credential
            {
                SecretId  = "*******************",
                SecretKey = "**********************"
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = ("sms.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            SmsClient      client = new SmsClient(cred, "ap-nanjing", clientProfile);
            SendSmsRequest req    = new SendSmsRequest();

            req.PhoneNumberSet   = new String[] { "+86" + record.phone };
            req.TemplateID       = "724175";
            req.SmsSdkAppid      = "1400410910";
            req.Sign             = "EVA记录";
            req.TemplateParamSet = new String[] { record.name, interview.Day + " " + interview.BeginTime, interview.Place + "室" };

            SendSmsResponse resp = client.SendSmsSync(req);

            if (resp.SendStatusSet[0].Code == "Ok")
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Esempio n. 27
0
        public void SendSms(string destMobile, string code)
        {
            String         product         = "Dysmsapi";                                   //短信API产品名称
            String         domain          = "dysmsapi.aliyuncs.com";                      //短信API产品域名
            String         accessKeyId     = MiddleTier.BusinessConfig.SmsAccessKeyId;
            String         accessKeySecret = MiddleTier.BusinessConfig.SmsAccessKeySecret; //你的accessKeySecret
            IClientProfile profile         = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = destMobile;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = MiddleTier.BusinessConfig.SmsSignName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = MiddleTier.BusinessConfig.SmsTemplateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = JsonUtilities.Serialize(new { code = code });
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "0";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
            }
            catch (Exception e)
            {
                MiddleTier.LogManager.Error(e);
            }
        }
Esempio n. 28
0
        //国际短信代码
        public static void InterSms(string apiurl)
        {
            StringBuilder arge = new StringBuilder();

            arge.AppendFormat("Account={0}", "账号");
            arge.AppendFormat("&Pwd={0}", "接口密码");
            arge.AppendFormat("&Content={0}", "模板变量");
            arge.AppendFormat("&Mobile={0}", "手机号码");
            arge.AppendFormat("&CountryCode={0}", "接口国际代码");
            arge.AppendFormat("&SignId={0}", "签名id");
            arge.AppendFormat("&TemplateId={0}", "模板id");
            string weburl = apiurl + "/SmsService/InterSms";
            string resp   = common.PushToWeb(weburl, arge.ToString(), Encoding.UTF8);

            Console.WriteLine("InterSms:" + resp);
            try
            {
                SendSmsResponse response = JsonConvert.DeserializeObject <SendSmsResponse>(resp);
                if (response.Code == 0)
                {
                    //成功
                }
                else
                {
                    //失败
                }
            }
            catch (Exception ex)
            {
                //记录日志
            }
        }
Esempio n. 29
0
        /// <summary>
        /// time: 2020-7-2
        ///  message:发送短信封装方法
        ///  author:Thomars
        /// </summary>
        /// <param name="PhoneNumbers">手机号码</param>
        /// <param name="SignName">短信签名</param>
        /// <param name="TemplateCode">模版编号</param>
        /// <param name="TemplateParam">模版</param>
        /// <returns></returns>
        public string SendSms(string PhoneNumbers, string SignName, string TemplateCode, string TemplateParam)
        {
            try
            {
                String         product         = "Dysmsapi";                       //短信API产品名称(短信产品名固定,无需修改)
                String         domain          = "dysmsapi.aliyuncs.com";          //短信API产品域名(接口地址固定,无需修改)
                String         accessKeyId     = "LTAI4GDFrkcmPmLMV9mPbrxa";       //"LTAIYcJupvlyI3Wj";//你的accessKeyId,参考本文档步骤2
                String         accessKeySecret = "g8LY92a1cFv0eDHJVOOq7IVMIu2A0E"; //"wwWGIV226n7O0Hmxyrah4zDqRq70RO";//你的accessKeySecret,参考本文档步骤2
                IClientProfile profile         = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
                //IAcsClient client = new DefaultAcsClient(profile);
                // SingleSendSmsRequest request = new SingleSendSmsRequest();
                //初始化ascClient,暂时不支持多region(请勿修改)
                DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
                IAcsClient     acsClient = new DefaultAcsClient(profile);
                SendSmsRequest request   = new SendSmsRequest();

                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式,发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
                request.PhoneNumbers = PhoneNumbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = SignName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = TemplateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = TemplateParam;      // "{\"name\":\"Tom\", \"code\":\"123\"}";
                                                            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "yourOutId";                //可以忽略
                                                            //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                return(sendSmsResponse.Message);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 30
0
        //分割线,以上已写接口文档
        /*————————————————————————————————————————————————*/

        /// <summary>
        /// 留着,不知道需不需要
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public HttpResponseMessage SendMail(UserReq user)
        {
            var phone = user.phone;

            if (true)
            {
                string             verification = CacheHelper.SetRiderVerificationCode(phone);
                Enum_SendEmailCode SendEmail;
                SendEmail = Enum_SendEmailCode.UserRegistrationVerificationCode;
                SendSmsResponse Email = AliyunHelper.SendMail.SendMail.Instance.SendEmail(phone, verification, SendEmail);
                //string str = "";
                if (Email.Code.ToUpper() == "OK")
                {
                    return(ControllerHelper.Instance.JsonResult(200, "短信验证码发送成功"));
                }
                else
                {
                    return(ControllerHelper.Instance.JsonResult(500, Email.Message));
                }
            }
            else
            {
                //string str = JsonHelper.JsonMsg(false, "请过段时间重新发送");
                return(ControllerHelper.Instance.JsonResult(500, "请过段时间重新发送"));
            }
        }
        public void SmsServiceAuthenticationFailed()
        {
            var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") };
            var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>();
            var smsService = new SmsService { SmsTechWrapper = smsTechWrapper };

            var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "AUTH_FAILED", Description = "we don't know who you are!" } };
            smsTechWrapper
                .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message))
                .Return(smsMessageSending);

            Assert.That(() => smsService.Send(messageToSend), Throws.Exception.TypeOf<SmsTechAuthenticationFailed>().With.Message.EqualTo(smsMessageSending.Error.Description));
        }
        public void SmsServiceOutOfMoney()
        {
            var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") };
            var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>();
            var smsService = new SmsService { SmsTechWrapper = smsTechWrapper };

            var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "LEDGER_ERROR", Description = "can't send a message to those dudes!" } };
            const string accountIsCurrentlyOutOfMoney = "Could not send message - account is currently out of money";
            smsTechWrapper
                .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message))
                .Return(smsMessageSending);

            Assert.That(() => smsService.Send(messageToSend), Throws.Exception.TypeOf<AccountOutOfMoneyException>().With.Message.EqualTo(accountIsCurrentlyOutOfMoney));
        }
Esempio n. 33
0
        internal static SendSmsResult FromSmsResponse(SendSmsResponse sendSmsResponse)
        {
            Contract.Requires(sendSmsResponse != null);
            Contract.Ensures(Contract.Result<SendSmsResult>() != null);

            return new SendSmsResult
            {
                StatusCode = sendSmsResponse.StatusCode,
                MessageId = sendSmsResponse.MessageId,
                MessageParts = sendSmsResponse.MessageParts,
                From = sendSmsResponse.From,
                To = sendSmsResponse.To,
                NetCost = sendSmsResponse.NetCost
            };
        }
        public void SmsServiceSending()
        {
            var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") };
            var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>();
            var smsService = new SmsService { SmsTechWrapper = smsTechWrapper };

            var smsMessageSending = new SendSmsResponse {Cost = (float) 0.06, MessageId = 123456, Error = new Error { Code = "SUCCESS"} };
            smsTechWrapper
                .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message))
                .Return(smsMessageSending);

            var response = smsService.Send(messageToSend);

            Assert.That(response, Is.TypeOf(typeof (SmsSending)));
            Assert.That(response.Sid, Is.EqualTo(smsMessageSending.MessageId.ToString()));
            var smsSending = response as SmsSending;
            Assert.That(smsSending.Price, Is.EqualTo(smsMessageSending.Cost));
            smsTechWrapper.VerifyAllExpectations();
        }
        public void SmsServiceInvalidNumber()
        {
            var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") };
            var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>();
            var smsService = new SmsService { SmsTechWrapper = smsTechWrapper };

            var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "RECIPIENTS_ERROR", Description = "can't send a message to those dudes!"} };
            smsTechWrapper
                .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message))
                .Return(smsMessageSending);

            var response = smsService.Send(messageToSend);

            Assert.That(response, Is.TypeOf(typeof(SmsFailed)));
            Assert.That(response.Sid, Is.EqualTo(smsMessageSending.MessageId.ToString()));
            var smsFailed = response as SmsFailed;
            Assert.That(smsFailed.Code, Is.EqualTo(smsMessageSending.Error.Code));
            Assert.That(smsFailed.Message, Is.EqualTo(smsMessageSending.Error.Description));
            smsTechWrapper.VerifyAllExpectations();
        }
        public void SmsServiceSending_WithoutERRORCode_ThrowsException()
        {
            var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") };
            var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>();
            var smsService = new SmsService { SmsTechWrapper = smsTechWrapper };

            var smsMessageSending = new SendSmsResponse {Cost = (float) 0.06, MessageId = 123456, Error = new Error { Code = string.Empty } };
            smsTechWrapper
                .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message))
                .Return(smsMessageSending);

            Assert.That(() => smsService.Send(messageToSend), Throws.ArgumentException.With.Message.Contains("Error code expected"));

            smsTechWrapper.VerifyAllExpectations();
        }