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); } }
public virtual async Task SendAsync(SmsMessage smsMessage) { var request = new SendSmsRequest( new[] { smsMessage.PhoneNumber }, GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.TemplateIdPropertyName), GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.SmsSdkAppidPropertyName, await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultSmsSdkAppid)), GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.SignPropertyName, await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultSign)), GetTemplateParamSet(smsMessage), GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.ExtendCodePropertyName, await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultExtendCode)), GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.SessionContextPropertyName), GetStringProperty(smsMessage, AbpSmsTencentCloudConsts.SenderIdPropertyName, await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultSenderId)) ); var commonOptions = new AbpTencentCloudCommonOptions { SecretId = await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultSecretId), SecretKey = await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.DefaultSecretKey) }; await _requester.SendRequestAsync <SendSmsResponse>(request, await _settingProvider.GetOrNullAsync(AbpSmsTencentCloudSettings.EndPoint), commonOptions); }
static async ValueTask <IApiResponse> SendSms(this IViewModel i, SendSmsRequest request, bool isStartSendSmsTimer) { i.TbSmsCodeFocus?.Invoke(); var client = ICloudServiceClient.Instance; var response = await client.AuthMessage.SendSms(request); if (!response.IsSuccess) { if (isStartSendSmsTimer) { i.CTS?.Cancel(); } if (response.Code == ApiResponseCode.BadRequest || response.Code == ApiResponseCode.RequestModelValidateFail || response.Code == ApiResponseCode.Fail) { i.TbPhoneNumberFocus?.Invoke(); } } if (!i.SendSmsCodeSuccess && response.IsSuccess) { i.SendSmsCodeSuccess = true; } return(response); }
public void Send(string to, string templateParam, string templateCode) { try { var request = new SendSmsRequest() { PhoneNumbers = to, SignName = AliyunSmsSettingConfigs.SignName, TemplateCode = templateCode, TemplateParam = templateParam, OutId = "Clmeng" }; var result = _acsClient.GetAcsResponse(request); if (result.Code == "") { } } catch (ServerException e) { throw new LotteryException("短信服务端异常", e); } catch (ClientException e) { throw new LotteryException("短信客户端异常", e); } }
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); }
/// <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("发送短信失败!"); }
/// <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; } }
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()); } }
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); }
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 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); }
public async Task <ActionResult <BoolResult> > SendSms([FromBody] SendSmsRequest request) { var administrator = await _administratorRepository.GetByMobileAsync(request.Mobile); if (administrator == null) { return(this.Error("此手机号码未关联管理员,请更换手机号码")); } var(success, errorMessage) = await _administratorRepository.ValidateLockAsync(administrator); if (!success) { return(this.Error(errorMessage)); } var code = StringUtils.GetRandomInt(100000, 999999); (success, errorMessage) = await _smsManager.SendAsync(request.Mobile, SmsCodeType.ChangePassword, code); if (!success) { return(this.Error(errorMessage)); } var cacheKey = GetSmsCodeCacheKey(request.Mobile); _cacheManager.AddOrUpdateAbsolute(cacheKey, code, 10); return(new BoolResult { Value = true }); }
//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(); }
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) { } }
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"); } }
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); } }
public async Task <IActionResult> Post([FromBody] SendSmsRequest payload) { if (string.IsNullOrEmpty(payload.PhoneNumber)) { return(BadRequest("Invalid phone number")); } var userAccountInfo = await _accountService.GetUserAccountInfo(); if (userAccountInfo.Balance == 0) { return(StatusCode((int)HttpStatusCode.PaymentRequired)); } try { var btcExchangeRate = await _bitcoinExchangeRateService.GetBitcoinExchangeRate(); var message = $"1 Bitcoin is currently worth ${btcExchangeRate} USD."; await _smsService.SendSms(message, payload.PhoneNumber); await _accountService.UpdateUserTotalQueries(1); await _accountService.UpdateUserBalance(-PaymentService.CostPerQuery); userAccountInfo = await _accountService.GetUserAccountInfo(); return(Ok(userAccountInfo)); } catch (Exception ex) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } }
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); } }
/// <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; } }
public State DispatchSms(SendSmsRequest message) { Console.WriteLine("sms message was sent successfully"); message.PrintDump(); return(State.Success); }
public async Task <ActionResult <BoolResult> > SendSms([FromBody] SendSmsRequest request) { var user = await _authManager.GetUserAsync(); if (!StringUtils.EqualsIgnoreCase(user.Mobile, request.Mobile)) { var exists = await _userRepository.IsMobileExistsAsync(request.Mobile); if (exists) { return(this.Error("此手机号码已注册,请更换手机号码")); } } var code = StringUtils.GetRandomInt(100000, 999999); var(success, errorMessage) = await _smsManager.SendAsync(request.Mobile, SmsCodeType.Authentication, code); if (!success) { return(this.Error(errorMessage)); } var cacheKey = GetSmsCodeCacheKey(request.Mobile); _cacheManager.AddOrUpdateAbsolute(cacheKey, code, 10); return(new BoolResult { Value = true }); }
public async Task <SendSmsResponse> SendSmsAsync(IEnumerable <string> phoneNumbers, IDictionary <string, string> variables, string templateCode) { if (phoneNumbers == null || !phoneNumbers.Any()) { throw new ArgumentException("手机号码错误"); } if (variables == null || !variables.Any()) { throw new ArgumentException("短信通知变量错误"); } if (string.IsNullOrWhiteSpace(templateCode) || !_options.TemplateCodes.ContainsKey(templateCode)) { throw new ArgumentException("模板编号错误"); } var request = new SendSmsRequest { PhoneNumbers = string.Join(",", phoneNumbers), SignName = _options.SignName, TemplateCode = _options.TemplateCodes[templateCode], TemplateParam = JsonConvert.SerializeObject(variables) }; return(await _client.SendSmsAsync(request)); }
public void Test_ValidatePath() { var path = "v4/sms-send"; var req = new SendSmsRequest(new SmsMessage(), MailjetOptions); Assert.Equal(path, req.Path); }
public async Task <ActionResult <BoolResult> > SendSms([FromBody] SendSmsRequest request) { var user = await _userRepository.GetByMobileAsync(request.Mobile); if (user == null) { return(this.Error("此手机号码未关联用户")); } var(success, errorMessage) = await _userRepository.ValidateStateAsync(user); if (!success) { return(this.Error(errorMessage)); } var code = StringUtils.GetRandomInt(100000, 999999); (success, errorMessage) = await _smsManager.SendAsync(request.Mobile, SmsCodeType.LoginConfirmation, code); if (!success) { return(this.Error(errorMessage)); } var cacheKey = GetSmsCodeCacheKey(request.Mobile); _cacheManager.AddOrUpdateAbsolute(cacheKey, code, 10); return(new BoolResult { Value = true }); }
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); }
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); } }
/// <summary> /// 发送短信验证码 /// </summary> /// <returns></returns> private SendSmsResponse RequestSendFromApi(string phone) { IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", AccessKeyId, AccessKeySecret); DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", Product, Domain); IAcsClient acsClient = new DefaultAcsClient(profile); var request = new SendSmsRequest(); SendSmsResponse response; try { //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 request.PhoneNumbers = phone; //必填:短信签名-可在短信控制台中找到 request.SignName = SignName; //必填:短信模板-可在短信控制台中找到 request.TemplateCode = TemplateCode; //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.TemplateParam = _templatePattern; //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 request.OutId = OutId; //请求失败这里会抛ClientException异常 response = acsClient.GetAcsResponse(request); } catch { return(null); } return(response); }
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); }
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"); } }
public JsonResult SendSMS(string text, string mobile) { try { var smsServiceRequest = new SendSmsRequest() { Url = SettingHelper.GetOrCreate(Constants.SystemSettings.SMSApiUrl, "https://019sms.co.il/api").Value, Username = SettingHelper.GetOrCreate(Constants.SystemSettings.SMSUsername, "sectorspr").Value, Password = SettingHelper.GetOrCreate(Constants.SystemSettings.SMSPassword, "faraj123").Value, Destinations = new List<string>(), Message = string.Empty, Source = SettingHelper.GetOrCreate(Constants.SystemSettings.SMSSource, "123").Value }; var smsService = new Crm.Sms.SmsService(); smsServiceRequest.Destinations = new List<string> { mobile}; smsServiceRequest.Message = text; smsService.Execute(smsServiceRequest); TempData["SMSmessage"] = "SMS Sent Succesfully"; return Json(smsServiceRequest, JsonRequestBehavior.AllowGet); } catch(Exception ex) { LogHelper.LogException(User.Identity.Name, ex, "Error While Sending SMS to Lead (Post)"); return null; } }
/// <remarks/> public void SendSmsAsync(SendSmsRequest SendSmsRequest, object userState) { if ((this.SendSmsOperationCompleted == null)) { this.SendSmsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSendSmsOperationCompleted); } this.InvokeAsync("SendSms", new object[] { SendSmsRequest}, this.SendSmsOperationCompleted, userState); }
private static void testClient(SendSmsClient client) { SendSmsRequest request = new SendSmsRequest( "This is a test message.", new List<string>() { "447956247525", "34637975280", "999" }); SendSmsResponse response = client.SendSms(request); Debug.Assert(response != null && response.Messages != null && response.Messages.Count() == 3); Sms sms; sms = response.Messages[0]; Debug.Assert(sms.Successful); Debug.Assert(sms.Recipient == "447956247525"); Debug.Assert(!String.IsNullOrEmpty(sms.Id)); Debug.Assert(sms.SubmissionReport == "00"); Debug.Assert(String.IsNullOrEmpty(sms.ErrorDescription)); sms = response.Messages[1]; Debug.Assert(sms.Successful); Debug.Assert(sms.Recipient == "34637975280"); Debug.Assert(!String.IsNullOrEmpty(sms.Id)); Debug.Assert(sms.SubmissionReport == "00"); Debug.Assert(String.IsNullOrEmpty(sms.ErrorDescription)); sms = response.Messages[2]; Debug.Assert(!sms.Successful); Debug.Assert(sms.Recipient == "999"); Debug.Assert(String.IsNullOrEmpty(sms.Id)); Debug.Assert(sms.SubmissionReport == "43"); Debug.Assert(!String.IsNullOrEmpty(sms.ErrorDescription)); }
static void Main(string[] args) { // // Credentials (unlike in Java and PHP, in C# we use System.Net.NetworkCredential, // which allows empty values, so validation is done inside the SendSmsClient constructor) // // UserName=null assertException(delegate() { new SendSmsClient("endpoint", new NetworkCredential() { UserName = null, Password = "******" }); }, typeof(ArgumentNullException), "No UserName provided."); // UserName="" assertException(delegate() { new SendSmsClient("endpoint", new NetworkCredential() { UserName = "", Password = "******" }); }, typeof(ArgumentNullException), "No UserName provided."); // Password=null assertException(delegate() { new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = null }); }, typeof(ArgumentNullException), "No Password provided."); // Password="" assertException(delegate() { new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = "" }); }, typeof(ArgumentNullException), "No Password provided."); // // SmsSendRequest constructors // // message=(string)null assertException(delegate() { new SendSmsRequest((string)null, "recipient"); }, typeof(ArgumentNullException), "No message provided."); // message="" assertException(delegate() { new SendSmsRequest("", "recipient"); }, typeof(ArgumentNullException), "No message provided."); // message=(List<string>)null assertException(delegate() { new SendSmsRequest((List<string>)null, "recipient"); }, typeof(ArgumentNullException), "No messages provided."); // message=<empty list> assertException(delegate() { new SendSmsRequest(new List<string>(), "recipient"); }, typeof(ArgumentNullException), "No messages provided."); // recipient=(string)null assertException(delegate() { new SendSmsRequest("message", (string)null); }, typeof(ArgumentNullException), "No recipient provided."); // recipient="" assertException(delegate() { new SendSmsRequest("message", ""); }, typeof(ArgumentNullException), "No recipient provided."); // recipient=(List<string>)null assertException(delegate() { new SendSmsRequest("message", (List<string>)null); }, typeof(ArgumentNullException), "No recipients provided."); // recipient=<empty list> assertException(delegate() { new SendSmsRequest("message", new List<string>()); }, typeof(ArgumentNullException), "No recipients provided."); // // SmsSendRequest constructor setters // SendSmsRequest request = new SendSmsRequest("message", "recipient"); // message=null assertException(delegate() { request.Message = null; }, typeof(ArgumentNullException), "No message provided."); // message="" assertException(delegate() { request.Message = ""; }, typeof(ArgumentNullException), "No message provided."); // messages=null assertException(delegate() { request.Messages = null; }, typeof(ArgumentNullException), "No messages provided."); // messages=<empty list> assertException(delegate() { request.Messages = new List<string>(); }, typeof(ArgumentNullException), "No messages provided."); // recipient=null assertException(delegate() { request.Recipient = null; }, typeof(ArgumentNullException), "No recipient provided."); // recipient="" assertException(delegate() { request.Recipient = ""; }, typeof(ArgumentNullException), "No recipient provided."); // recipients=null assertException(delegate() { request.Recipients = null; }, typeof(ArgumentNullException), "No recipients provided."); // recipients=<empty list> assertException(delegate() { request.Recipients = new List<string>(); }, typeof(ArgumentNullException), "No recipients provided."); // // SmsSendRequest constructor getters // request = new SendSmsRequest("message", "recipient"); Debug.Assert(Enumerable.SequenceEqual(request.Messages, new List<string>() { "message" })); Debug.Assert(Enumerable.SequenceEqual(request.Recipients, new List<string>() { "recipient" })); request.Message = "message2"; request.Recipient = "recipient2"; Debug.Assert(Enumerable.SequenceEqual(request.Messages, new List<string>() { "message2" })); Debug.Assert(Enumerable.SequenceEqual(request.Recipients, new List<string>() { "recipient2" })); request = new SendSmsRequest(new List<string>() { "message", "message2" }, new List<string>() { "recipient", "recipient2" }); Debug.Assert(Enumerable.SequenceEqual(request.Messages, new List<string>() { "message", "message2" })); Debug.Assert(Enumerable.SequenceEqual(request.Recipients, new List<string>() { "recipient", "recipient2" })); request.Messages = new List<string>() { "message", "message2", "message3" }; request.Recipients = new List<string>() { "recipient", "recipient2", "recipient3" }; Debug.Assert(Enumerable.SequenceEqual(request.Messages, new List<string>() { "message", "message2", "message3" })); Debug.Assert(Enumerable.SequenceEqual(request.Recipients, new List<string>() { "recipient", "recipient2", "recipient3" })); // // SmsSendRequest other getters/setters // request = new SendSmsRequest("message", "recipient"); // Sender Debug.Assert(request.Sender == null); request.Sender = "Sender"; Debug.Assert(request.Sender == "Sender"); Debug.Assert(request["X-E3-Originating-Address"] == "Sender"); request.Sender = null; Debug.Assert(request.Sender == null); Debug.Assert(!request.ContainsKey("X-E3-Originating-Address")); // ConcatenationLimit Debug.Assert(request.ConcatenationLimit == null); request.ConcatenationLimit = 255; Debug.Assert(request.ConcatenationLimit == 255); Debug.Assert(request["X-E3-Concatenation-Limit"] == "255"); request.ConcatenationLimit = null; Debug.Assert(request.ConcatenationLimit == null); Debug.Assert(!request.ContainsKey("X-E3-Concatenation-Limit")); // ScheduleFor Debug.Assert(request.ScheduleFor == null); // Europe/London: 01/09/2012 12:30:00 -> UTC: 01/09/2012 11:30:00 request.ScheduleFor = new DateTime(2012, 9, 1, 11, 30, 0, 0, DateTimeKind.Utc); Debug.Assert(request.ScheduleFor.Equals(new DateTime(2012, 9, 1, 11, 30, 0, 0, DateTimeKind.Utc))); Debug.Assert(request["X-E3-Schedule-For"] == "20120901123000"); // Europe/Berlin: 01/09/2012 12:30:00 -> UTC: 01/09/2012 10:30:00 request.ScheduleFor = new DateTime(2012, 9, 1, 10, 30, 0, 0, DateTimeKind.Utc); Debug.Assert(request.ScheduleFor.Equals(new DateTime(2012, 9, 1, 10, 30, 0, 0, DateTimeKind.Utc))); Debug.Assert(request["X-E3-Schedule-For"] == "20120901113000"); // GMT: 01/09/2012 12:30:00 -> UTC: 01/09/2012 12:30:00 request.ScheduleFor = new DateTime(2012, 9, 1, 12, 30, 0, 0, DateTimeKind.Utc); Debug.Assert(request.ScheduleFor.Equals(new DateTime(2012, 9, 1, 12, 30, 0, 0, DateTimeKind.Utc))); Debug.Assert(request["X-E3-Schedule-For"] == "20120901133000"); request.ScheduleFor = null; Debug.Assert(request.ScheduleFor == null); Debug.Assert(!request.ContainsKey("X-E3-Schedule-For")); // ConfirmDelivery Debug.Assert(request.ConfirmDelivery == null); request.ConfirmDelivery = true; Debug.Assert(request.ConfirmDelivery == true); Debug.Assert(request["X-E3-Confirm-Delivery"] == "on"); request.ConfirmDelivery = false; Debug.Assert(request.ConfirmDelivery == false); Debug.Assert(request["X-E3-Confirm-Delivery"] == "off"); request.ConfirmDelivery = null; Debug.Assert(request.ConfirmDelivery == null); Debug.Assert(!request.ContainsKey("X-E3-Confirm-Delivery")); // ReplyPath Debug.Assert(request.ReplyPath == null); request.ReplyPath = "http://www.server.com/path"; Debug.Assert(request.ReplyPath == "http://www.server.com/path"); Debug.Assert(request["X-E3-Reply-Path"] == "http://www.server.com/path"); request.ReplyPath = null; Debug.Assert(request.ReplyPath == null); Debug.Assert(!request.ContainsKey("X-E3-Reply-Path")); // UserKey Debug.Assert(request.UserKey == null); request.UserKey = "123457890"; Debug.Assert(request.UserKey == "123457890"); Debug.Assert(request["X-E3-User-Key"] == "123457890"); request.UserKey = null; Debug.Assert(request.UserKey == null); Debug.Assert(!request.ContainsKey("X-E3-User-Key")); // SessionReplyPath Debug.Assert(request.SessionReplyPath == null); request.SessionReplyPath = "http://www.server.com/path"; Debug.Assert(request.SessionReplyPath == "http://www.server.com/path"); Debug.Assert(request["X-E3-Session-Reply-Path"] == "http://www.server.com/path"); request.SessionReplyPath = null; Debug.Assert(request.SessionReplyPath == null); Debug.Assert(!request.ContainsKey("X-E3-Session-Reply-Path")); // SessionId Debug.Assert(request.SessionId == null); request.SessionId = "123457890"; Debug.Assert(request.SessionId == "123457890"); Debug.Assert(request["X-E3-Session-ID"] == "123457890"); request.SessionId = null; Debug.Assert(request.SessionId == null); Debug.Assert(!request.ContainsKey("X-E3-Session-ID")); // UserTag Debug.Assert(request.UserTag == null); request.UserTag = "123457890"; Debug.Assert(request.UserTag == "123457890"); Debug.Assert(request["X-E3-User-Tag"] == "123457890"); request.UserTag = null; Debug.Assert(request.UserTag == null); Debug.Assert(!request.ContainsKey("X-E3-User-Tag")); // ValidityPeriod Debug.Assert(request.ValidityPeriod == null); request.ValidityPeriod = new TimeSpan(14, 0, 0, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(14, 0, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "2w"); request.ValidityPeriod = new TimeSpan(7, 0, 0, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(7, 0, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "1w"); request.ValidityPeriod = new TimeSpan(2, 0, 0, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(2, 0, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "2d"); request.ValidityPeriod = new TimeSpan(24, 0, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(24, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "1d"); request.ValidityPeriod = new TimeSpan(2, 0, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(2, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "2h"); request.ValidityPeriod = new TimeSpan(0, 60, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(0, 60, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "1h"); request.ValidityPeriod = new TimeSpan(0, 2, 0); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(0, 2, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "2m"); request.ValidityPeriod = new TimeSpan(0, 0, 1); Debug.Assert(request.ValidityPeriod.Equals(new TimeSpan(0, 0, 0))); Debug.Assert(request["X-E3-Validity-Period"] == "0m"); request.ValidityPeriod = null; Debug.Assert(request.ValidityPeriod == null); Debug.Assert(!request.ContainsKey("X-E3-Validity-Period")); // Custom properties request["X-E3-Custom-Property"] = "test1234"; Debug.Assert(request["X-E3-Custom-Property"] == "test1234"); request.Remove("X-E3-Custom-Property"); Debug.Assert(!request.ContainsKey("X-E3-Custom-Property")); // // toString() (XML generation) // request = new SendSmsRequest( new List<string>() { "message", "message2" }, new List<string>() { "recipient", "recipient2" } ); request.Sender = "sender"; request.ConcatenationLimit = 255; request.ScheduleFor = new DateTime(2012, 9, 1, 11, 30, 0, 0, DateTimeKind.Utc); request.ConfirmDelivery = true; request.ReplyPath = "http://www.server.com/path"; request.UserKey = "123457890"; request.SessionReplyPath = "http://www.server.com/path"; request.SessionId = "1234567890"; request.UserTag = "123457890"; request.ValidityPeriod = new TimeSpan(14, 0, 0, 0); var sw = new StringWriter(); var xw = XmlWriter.Create(sw); xw.WriteStartDocument(); xw.WriteStartElement("sendSmsRequest"); request.WriteXml(xw); xw.WriteEndElement(); xw.WriteEndDocument(); xw.Flush(); Debug.Assert(sw.ToString() == "<?xml version=\"1.0\" encoding=\"utf-16\"?><sendSmsRequest><X-E3-Message>message</X-E3-Message><X-E3-Message>message2</X-E3-Message><X-E3-Recipients>recipient</X-E3-Recipients><X-E3-Recipients>recipient2</X-E3-Recipients><X-E3-Originating-Address>sender</X-E3-Originating-Address><X-E3-Concatenation-Limit>255</X-E3-Concatenation-Limit><X-E3-Schedule-For>20120901123000</X-E3-Schedule-For><X-E3-Confirm-Delivery>on</X-E3-Confirm-Delivery><X-E3-Reply-Path>http://www.server.com/path</X-E3-Reply-Path><X-E3-User-Key>123457890</X-E3-User-Key><X-E3-Session-Reply-Path>http://www.server.com/path</X-E3-Session-Reply-Path><X-E3-Session-ID>1234567890</X-E3-Session-ID><X-E3-User-Tag>123457890</X-E3-User-Tag><X-E3-Validity-Period>2w</X-E3-Validity-Period></sendSmsRequest>" ); // // SendSmsClient constructor // var credentials = new NetworkCredential() { UserName = "******", Password = "******" }; // endpoint=null assertException(delegate() { new SendSmsClient(null, credentials); }, typeof(ArgumentNullException), "No Endpoint provided."); // endpoint="" assertException(delegate() { new SendSmsClient("", credentials); }, typeof(ArgumentNullException), "No Endpoint provided."); // credentials=null assertException(delegate() { new SendSmsClient("endpoint", null); }, typeof(ArgumentNullException), "No Credentials provided."); // // SendSmsClient constructor setters // SendSmsClient client; client = new SendSmsClient(); client = new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = "******" } ); // endpoint=null assertException(delegate() { client.Endpoint = null; }, typeof(ArgumentNullException), "No Endpoint provided."); // endpoint="" assertException(delegate() { client.Endpoint = ""; }, typeof(ArgumentNullException), "No Endpoint provided."); // credentials=null assertException(delegate() { client.Credentials = null; }, typeof(ArgumentNullException), "No Credentials provided."); // // SendSmsClient constructor getters // client = new SendSmsClient(); Debug.Assert(client.Endpoint == null); Debug.Assert(client.Credentials == null); client = new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = "******" }); Debug.Assert(client.Endpoint == "endpoint"); client.Endpoint = "endpoint2"; Debug.Assert(client.Endpoint == "endpoint2"); Debug.Assert(client.Credentials.UserName == "user"); Debug.Assert(client.Credentials.Password == "pass"); client.Credentials = new NetworkCredential() { UserName = "******", Password = "******" }; Debug.Assert(client.Credentials.UserName == "user2"); Debug.Assert(client.Credentials.Password == "pass2"); // // SendSmsClient Path // client = new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = "******" }); Debug.Assert(client.Path == "/submit_sm"); // path=null assertException(delegate() { client.Path = null; }, typeof(ArgumentNullException), "No Path provided."); // path="" assertException(delegate() { client.Path = ""; }, typeof(ArgumentNullException), "No Path provided."); // path invalid assertException(delegate() { client.Path = "path"; }, typeof(ArgumentException), "The path must start with '/'."); client.Path = "/path"; Debug.Assert(client.Path == "/path"); // // SendSmsClient Secure // client = new SendSmsClient("endpoint", new NetworkCredential() { UserName = "******", Password = "******" }); Debug.Assert(client.Secure); client.Secure = false; Debug.Assert(!client.Secure); // // SendSmsClient Submission // if (args.Length != 2 || String.IsNullOrEmpty(args[0]) || String.IsNullOrEmpty(args[1])) { Console.WriteLine("Usage: Test.exe <login> <password>"); return; } string login = args[0]; string password = args[1]; try { client = new SendSmsClient("sms.dialogue.net", new NetworkCredential(login, password)); client.Secure = false; testClient(client); client.Secure = true; testClient(client); client = new SendSmsClient("sendmsg.dialogue.net", new NetworkCredential(login, password)); client.Secure = false; testClient(client); client.Secure = true; testClient(client); } catch (Exception e) { Console.WriteLine(e.ToString()); Debug.Assert(false, e.ToString()); } // Test sending uninitialized request assertException(delegate() { client.SendSms(new SendSmsRequest()); }, typeof(InvalidOperationException), "SendSmsRequest has not been initialized."); // Test wrong password assertException(delegate() { testClient(new SendSmsClient("sendmsg.dialogue.net", new NetworkCredential("wrong", "wrong"))); }, typeof(WebException), "The remote server returned an error: (401) Unauthorized."); // Test wrong endpoint assertException(delegate() { testClient(new SendSmsClient("wrong", new NetworkCredential("wrong", "wrong"))); }, typeof(WebException), "The remote name could not be resolved:"); // // SmsReport // try { SmsReport report = SmsReport.getInstance("<callback X-E3-Delivery-Report=\"20\" X-E3-ID=\"90A9893BC2B645918034F4C358A062CE\" X-E3-Loop=\"1322229741.93646\" X-E3-Network=\"Orange\" X-E3-Recipients=\"447xxxxxxxxx\" X-E3-Timestamp=\"2011-12-01 18:02:21\" X-E3-User-Key=\"myKey1234\"/>"); Debug.Assert(report != null); Debug.Assert(report.Id == "90A9893BC2B645918034F4C358A062CE"); Debug.Assert(report.Recipient == "447xxxxxxxxx"); Debug.Assert(report.DeliveryReport == "20"); Debug.Assert(report.UserKey == "myKey1234"); Debug.Assert(report.Timestamp.Ticks == 634583593410000000); Debug.Assert(report.Network == "Orange"); Debug.Assert(report.ToString() == "Id: 90A9893BC2B645918034F4C358A062CE, Recipient: 447xxxxxxxxx, DeliveryReport: 20, UserKey: myKey1234, Timestamp: 01/12/2011 18:02:21, Network: Orange"); report.DeliveryReport = "00"; Debug.Assert(report.State == State.Delivered); Debug.Assert(report.Successful); report.DeliveryReport = "1F"; Debug.Assert(report.State == State.Delivered); Debug.Assert(report.Successful); report.DeliveryReport = "20"; Debug.Assert(report.State == State.TemporaryError); Debug.Assert(!report.Successful); report.DeliveryReport = "3F"; Debug.Assert(report.State == State.TemporaryError); Debug.Assert(!report.Successful); report.DeliveryReport = "40"; Debug.Assert(report.State == State.PermanentError); Debug.Assert(!report.Successful); report.DeliveryReport = "7F"; Debug.Assert(report.State == State.PermanentError); Debug.Assert(!report.Successful); report.DeliveryReport = "80"; assertException(delegate() { var state = report.State; }, typeof(InvalidOperationException), "Unknown delivery report value:"); report.DeliveryReport = ""; Debug.Assert(report.State == State.Undefined); } catch (Exception e) { Console.WriteLine(e.ToString()); Debug.Assert(false, e.ToString()); } // // SmsReply // try { SmsReply reply = SmsReply.getInstance("<callback X-E3-Account-Name=\"test\" X-E3-Data-Coding-Scheme=\"00\" X-E3-Hex-Message=\"54657374204D657373616765\" X-E3-ID=\"809EF683F022441DB9C4895AED6382CF\" X-E3-Loop=\"1322223264.20603\" X-E3-MO-Campaign=\"\" X-E3-MO-Keyword=\"\" X-E3-Network=\"Orange\" X-E3-Originating-Address=\"447xxxxxxxxx\" X-E3-Protocol-Identifier=\"00\" X-E3-Recipients=\"1234567890\" X-E3-Session-ID=\"1234567890\" X-E3-Timestamp=\"2011-11-25 12:14:23.000000\" X-E3-User-Data-Header-Indicator=\"0\"/>"); Debug.Assert(reply != null); Debug.Assert(reply.Id == "809EF683F022441DB9C4895AED6382CF"); Debug.Assert(reply.Sender == "447xxxxxxxxx"); Debug.Assert(reply.SessionId == "1234567890"); Debug.Assert(reply.HexMessage == "54657374204D657373616765"); Debug.Assert(reply.Message == "Test Message"); Debug.Assert(reply.Timestamp.Ticks == 634578200630000000); Debug.Assert(reply.Network == "Orange"); Debug.Assert(reply.ToString() == "Id: 809EF683F022441DB9C4895AED6382CF, Sender: 447xxxxxxxxx, SessionId: 1234567890, HexMessage: 54657374204D657373616765, Message: Test Message, Timestamp: 25/11/2011 12:14:23, Network: Orange"); } catch (Exception e) { Console.WriteLine(e.ToString()); Debug.Assert(false, e.ToString()); } }
/// <remarks/> public void SendSmsAsync(SendSmsRequest SendSmsRequest) { this.SendSmsAsync(SendSmsRequest, null); }