Git Product home page Git Product logo

abp.net.sms's Introduction

Abp.Net.Sms

Sms interface, that based on aspnet boilerplate, provider abstract sms service and sms configuration.

Install

Install-Package Abp.Net.Sms

How to use

1. Create a sms sender service

For example, use AliDaYu

  • a. Install QifuTopSDK

Install-Package QifuTopSDK

  • b. Write sms sender adapter for AliDaYu
using Abp.Dependency;
using Abp.Net.Sms;
using Abp.UI;
using System;
using System.Threading.Tasks;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

public class AliDayuSmsSender : SmsSenderBase, ITransientDependency
{
    private ITopClient client = null;
    public AliDayuSmsSender(ISmsSenderConfiguration configuration) : base(configuration)
    {
        client = new DefaultTopClient(configuration.GetServiceUrl(),
            configuration.GetAppKey(),
            configuration.GetAppSecret());
    }

    protected override void SendSms(SmsMessage sms)
    {
        var req = new AlibabaAliqinFcSmsNumSendRequest();
        req.SmsType = "normal";
        req.SmsFreeSignName = sms.FreeSignName;
        req.SmsParam = sms.TemplateParams;
        req.RecNum = sms.To;
        req.SmsTemplateCode = string.IsNullOrEmpty(sms.TemplateCode)
                ? _configuration.GetDefaultSmsTemplateCode()
                : sms.TemplateCode;
        AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
        if (rsp.IsError)
        {
            throw new UserFriendlyException("Sms send fail",
                new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}",
                    sms.To,
                    rsp.ErrCode,
                    rsp.ErrMsg)));
        }
        if (rsp.Result != null && !rsp.Result.Success)
        {
            throw new UserFriendlyException("Sms send fail",
                new Exception(string.Format("to:{0},result.errCode:{1},result.errMsg:{2}",
                    sms.To,
                    rsp.Result.ErrCode,
                    rsp.Result.Msg)));
        }
    }

    protected override Task SendSmsAsync(SmsMessage sms)
    {
        var req = new AlibabaAliqinFcSmsNumSendRequest();
        req.SmsType = "normal";
        req.SmsFreeSignName = sms.FreeSignName;
        req.SmsParam = sms.TemplateParams;
        req.RecNum = sms.To;
        req.SmsTemplateCode = string.IsNullOrEmpty(sms.TemplateCode)
            ? _configuration.GetDefaultSmsTemplateCode()
            : sms.TemplateCode;
        var task = new Task(()=> {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
            if (rsp.IsError)
            {
                throw new UserFriendlyException("Sms send fail",
                    new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}",
                        sms.To,
                        rsp.ErrCode,
                        rsp.ErrMsg)));
            }
            if (rsp.Result != null && !rsp.Result.Success)
            {
                throw new UserFriendlyException("Sms send fail",
                    new Exception(string.Format("to:{0},result.errCode:{1},result.errMsg:{2}",
                        sms.To,
                        rsp.Result.ErrCode,
                        rsp.Result.Msg)));
            }
        });
        task.Start();
        return task;
    }
}
  • c. Write Setting Provider
using System.Collections.Generic;
using System.Configuration;
using Abp.Configuration;
using Abp.Net.Sms;

public class AppSettingProvider : SettingProvider
{
    public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context)
    {
        return new[]
            {
                // Sms config
                new SettingDefinition(SmsSettingNames.ServiceUrl,
                    ConfigurationManager.AppSettings[SmsSettingNames.ServiceUrl] ?? ""),
                new SettingDefinition(SmsSettingNames.AppKey,
                    ConfigurationManager.AppSettings[SmsSettingNames.AppKey] ?? ""),
                new SettingDefinition(SmsSettingNames.AppSecret,
                    ConfigurationManager.AppSettings[SmsSettingNames.AppSecret] ?? ""),
                new SettingDefinition(SmsSettingNames.DefaultFreeSignName,
                    ConfigurationManager.AppSettings[SmsSettingNames.DefaultFreeSignName] ?? ""),
                new SettingDefinition(SmsSettingNames.DefaultSmsTemplateCode,
                    ConfigurationManager.AppSettings[SmsSettingNames.DefaultSmsTemplateCode] ?? ""),  
        };
    }
}
  • d. Configurate default setting in Web.config
    <!--Production-->
    <add key="Abp.Net.Sms.ServiceUrl" value="http://gw.api.taobao.com/router/rest" />
    <!--<add key="Abp.Net.Sms.ServiceUrl" value="https://eco.taobao.com/router/rest" />-->
    <!--Sandbox-->
    <!--<add key="Abp.Net.Sms.ServiceUrl" value="http://gw.api.tbsandbox.com/router/rest" />-->
    <!--<add key="Abp.Net.Sms.ServiceUrl" value="https://gw.api.tbsandbox.com/router/rest" />-->
    <add key="Abp.Net.Sms.AppKey" value="XXXXX" />
    <add key="Abp.Net.Sms.AppSecret" value="XXXXX" />
    <add key="Abp.Net.Sms.DefaultSmsTemplateCode" value="SMS_XXXXX" />
    <add key="Abp.Net.Sms.DefaultFreeSignName" value="大鱼测试" />

2. If you want to use it in Asp.Net Identity or AbpZero, otherwise you can skip it.

You should implement Microsoft.AspNet.Identity.IIdentityMessageService. Then you can send sms in userManager class.

using Abp.Dependency;
using Abp.Net.Sms;
using Microsoft.AspNet.Identity;
using System.Threading.Tasks;

public class IdentitySmsMessageService : IIdentityMessageService, ITransientDependency
{
    private readonly ISmsSender _smsSender;

    public IdentitySmsMessageService(ISmsSender smsSender)
    {
        _smsSender = smsSender;
    }

    public virtual async Task SendAsync(IdentityMessage message)
    {
        if (message.Body != null)
        {
            var splitIndex = message.Body.IndexOf('|');// Split TemplateCode and TemplateParams by '|'.
            if (splitIndex >= 0 && splitIndex < message.Body.Length - 1)
            {
                if (splitIndex == 0)
                {
                    await _smsSender.SendAsync(message.Destination, "", message.Body.Substring(splitIndex + 1));
                }
                else
                {
                    await _smsSender.SendAsync(message.Destination, message.Body.Substring(0, splitIndex), message.Body.Substring(splitIndex + 1));
                }
            }
            else
            {
                await _smsSender.SendAsync(message.Destination, message.Body.Substring(0, splitIndex), "");
            }
        }
    }
}

3. Set NullSmsSender if in debug mode

Write it in abp module file in project XXX.Core.

if (DebugHelper.IsDebug)
{
    //Disabling sms sending in debug mode
    IocManager.Register<ISmsSender, NullSmsSender>(DependencyLifeStyle.Transient);
}

4. Use it in domain or application layer.

You just inject ISmsSender into construction, like other DI object. Congratulation! You finished.

abp.net.sms's People

Contributors

berkaroad avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.