极光推送REST API 实例(分等级推送,使用别名推送)

在一个推送功能中,给不同等级的用户推送不同的消息


    /// <summary>
    /// 取得发送人员名单
    /// </summary>
    /// <param name="guid"></param>
    protected void SendMessage(string guid)
    {
        try
        {
            if (!string.IsNullOrEmpty(guid))
            {
                string strSendObj = "";//推送对象
                #region 查询推送信息
                guid = ("'" + guid + "'").Trim();
                DataTable dataTable = data.Search(guid, "", "");
                if (dataTable != null && dataTable.Rows.Count > 0)
                {
                    strPushGuid = dataTable.Rows[0]["Push_Guid"].ToString();
                    strMessage = dataTable.Rows[0]["Push_Content"].ToString();//发送内容
                    strPushType = dataTable.Rows[0]["Push_Type"].ToString();//发送形式
                    strPushLink = dataTable.Rows[0]["Push_Link"].ToString();//推送链接
                    strSendObj = dataTable.Rows[0]["Push_Rank"].ToString();//发送对象
                    strPush_MessageGuid = dataTable.Rows[0]["Push_MessageGuid"].ToString();//发送标识符
                    if (strPushType == "1" && strPushLink != "")//发送形式为新闻中心
                    {
                        DataTable dtModiflyTime = data.SearchModiflyTime("'" + strPushLink + "'");
                        if (dtModiflyTime != null && dtModiflyTime.Rows.Count > 0)
                            strModiflyTime = dtModiflyTime.Rows[0]["ModifyTime"].ToString();//修改时间
                    }
                    strIsShowHotel = dataTable.Rows[0]["Push_IsShowHotel"].ToString();//订单类型
                    strOrderType = dataTable.Rows[0]["Push_OrderType"].ToString();//我的订单
                }
                #endregion
               
                if (!string.IsNullOrEmpty(strSendObj))
                {
                    #region 根据推送得到推送人员
                    strSendObj = strSendObj.Substring(1);
                    strSendObj = strSendObj.Substring(0, strSendObj.Length - 1);
                    string strRank1 = "";
                    string strRank2 = "";
                    if (strSendObj.IndexOf("-1") != -1)//发送对象包括普通用户
                    {
                        if (strSendObj.Length == 2)//只有普通用户,其他人不包括
                        {
                            strRank2 = "2";//普通用户
                            strRank2 = this.GetRank(strRank2);
                            dtAccountInfo = data.SearchMemLoginID(strRank2, "0");//查询普通用户
                        }
                        else
                        {
                            //分别查询出所需要的资料,再把两张表的资料
                            strRank1 = strSendObj.Substring(0, strSendObj.Length - 3);//截取‘-1’前面的字符串,即总代理、区代理、分销商中的一个或者多个
                            strRank2 = "2";//普通用户
                            strRank1 = this.GetRank(strRank1);
                            strRank2 = this.GetRank(strRank2);
                            DataTable dtAccountInfo1 = data.SearchMemLoginID(strRank1, "1");
                            DataTable dtAccountInfo2 = data.SearchMemLoginID(strRank2, "0");
                            dtAccountInfo = dtAccountInfo1.Clone();
                            dtAccountInfo.Merge(dtAccountInfo1);
                            dtAccountInfo.Merge(dtAccountInfo2);
                        }
                    }
                    else//发送对象不包括普通用户
                    {
                        strSendObj = this.GetRank(strSendObj);
                        dtAccountInfo = data.SearchMemLoginID(strSendObj, "1");
                    }
                  #endregion


                    #region  线程池
                    int remainCount = 0;
                    count = dtAccountInfo.Rows.Count;
                    if (dtAccountInfo != null && dtAccountInfo.Rows.Count > 0)
                    {
                        int seed = Convert.ToInt32(dtAccountInfo.Rows.Count) % 1000 == 0 ? Convert.ToInt32(dtAccountInfo.Rows.Count) / 1000 : Convert.ToInt32(dtAccountInfo.Rows.Count) / 1000 + 1;
                        remainCount = seed;
                        for (int i = 1; i <= seed; i++)
                        {
                            remainCount = remainCount - 1;
                            object numCode = i.ToString();//i代表seed个里面的第几个
                            ThreadPool.QueueUserWorkItem(ResultRun, numCode);//执行线程池
                        }
                        Thread.Sleep(500);
                        if (remainCount < 0 || remainCount==0)
                        {
                            int isUpdatePushStauts = data.UpdatePushStauts(("'" + strPushGuid + "'").Trim());
                            if (isUpdatePushStauts == 1)
                            {
                                //DataBind();
                                Response.Redirect("Mobile_Push_List.aspx");
                            }
                            else
                            {
                                System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"发送失败!\");", true);
                            }
                        }
                    }
                    else
                    {
                        System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"用户不存在!\");", true);
                    }
                    #endregion
                }
                else
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"发送对象不能为空!\");", true);
                }
            }
            else
            {
                System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"该笔资料不存在!\");", true);
            }
        }
        catch (Exception ex)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"发送失败!'" + ex + "'\");", true);
        }
    }
    /// <summary>
    /// 取得发送对象
    /// </summary>
    /// <param name="strRank"></param>
    /// <returns></returns>
    public string GetRank(string strRank)
    {
        string strSendObj = "";
        string[] arySendObj = strRank.Split(',');
        if (arySendObj.Length > 0)
        {
            string _str = "','";
            for (int a = 0, b = arySendObj.Length; a < b; a++)
            {
                strSendObj = strSendObj + _str + arySendObj[a];
            }
            if (strSendObj.Trim().StartsWith("'"))
            {
                strSendObj = strSendObj.Substring(2) + "'"; //去掉"',"
            }
        }
        return strSendObj;
    }
    /// <summary>
    /// 使用正则表达式过滤人员名单
    /// </summary>
    /// <param name="inputStr"></param>
    /// <returns></returns>
    public static bool IsMatchStr(string inputStr)
    {
        string patternStr = @"^[\u4E00-\u9FA5A-Za-z0-9_@!#$&*+=.|¥]+$";
        return Regex.IsMatch(inputStr, patternStr);
    }
    /// <summary>
    /// 组装推送参数进行推送
    /// </summary>
    /// <param name="numCode"></param>
    public void ResultRun(object numCode)
    {
        lock (numCode)
        {
            #region 验证推送人员昵称是否符合规则
            ArrayList arrAlias = new ArrayList();
            int runCount = 0;
            string strAccountCode = "";
            int tmpCount = Convert.ToInt32(numCode) * 1000 <= count ? Convert.ToInt32(numCode) * 1000 : count;
            int tmp = tmpCount >= 1000 ? tmpCount - 1000 : 0;
            if (dtAccountInfo != null && dtAccountInfo.Rows.Count > 0)
            {
                for (int i = tmp, j = tmpCount; i < j; i++)
                {
                    bool blIsMatch = false;
                    blIsMatch = IsMatchStr(dtAccountInfo.Rows[i]["MemLoginID"].ToString());
                    if (blIsMatch)
                    {
                        arrAlias.Add(dtAccountInfo.Rows[i]["MemLoginID"].ToString());
                    }
                }
            }
            #endregion


            #region 推送参数
            Dictionary<string, object> dataSend = new Dictionary<string, object>();
            //推送平台
            ArrayList arrPlatform = new ArrayList();
            arrPlatform.Add("android");
            arrPlatform.Add("ios");
            dataSend.Add("platform", arrPlatform);
            //推送别名
            Dictionary<string, object> alias = new Dictionary<string, object>();
            alias.Add("alias", arrAlias);
            dataSend.Add("audience", alias);
            //扩展字段(额外信息)
            Dictionary<string, object> androidNotificationParam = new Dictionary<string, object>();
            Dictionary<string, object> iosNotificationParam = new Dictionary<string, object>();
            Dictionary<string, object> androidNotificationExtras = new Dictionary<string, object>();
            Dictionary<string, object> iosNotificationExtras = new Dictionary<string, object>();
            string paramTemp = "";
            if (strPushType != "")
            {
                switch (strPushType)
                {
                    case "1"://新闻资讯
                        string strPageName = "AnnouncementDetail.htm";
                        androidNotificationParam.Add("url", strPageName);
                        androidNotificationParam.Add("id", strPush_MessageGuid);
                        androidNotificationParam.Add("messageTitle", strMessage);
                        androidNotificationParam.Add("ModiflyTime", strModiflyTime);
                        iosNotificationParam.Add("url", strPageName);
                        iosNotificationParam.Add("id", strPush_MessageGuid);
                        iosNotificationParam.Add("messageTitle", strMessage);
                        iosNotificationParam.Add("ModiflyTime", strModiflyTime);
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", androidNotificationParam);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", iosNotificationParam);
                        break;
                    case "2"://活动链接
                        androidNotificationParam.Add("url", strPushLink);
                        androidNotificationParam.Add("guid", strPush_MessageGuid);
                        iosNotificationParam.Add("url", strPushLink);
                        iosNotificationParam.Add("guid", strPush_MessageGuid);
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", androidNotificationParam);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", iosNotificationParam);
                        break;
                    case "3"://打开商品详情
                        string strCanBuy = "2";
                        androidNotificationParam.Add("guid", strPush_MessageGuid);
                        iosNotificationParam.Add("guid", strPush_MessageGuid);
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", androidNotificationParam);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", iosNotificationParam);
                        break;
                    case "4"://打开订单页面(全部、未付款、已付款..)
                        androidNotificationParam.Add("isShowHotel", strIsShowHotel);
                        androidNotificationParam.Add("orderType", strOrderType);
                        iosNotificationParam.Add("isShowHotel", strIsShowHotel);
                        iosNotificationParam.Add("orderType", strOrderType);
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", androidNotificationParam);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", iosNotificationParam);
                        break;
                    case "5"://打开后台拿货页面
                        string strWebTitle = "后台拿货";
                        string strUrl = "seller_take.html";
                        androidNotificationParam.Add("url", strUrl);
                        androidNotificationParam.Add("webTitle", strWebTitle);
                        iosNotificationParam.Add("url", strUrl);
                        iosNotificationParam.Add("webTitle", strWebTitle);
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", androidNotificationParam);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", iosNotificationParam);
                        break;
                    case "6"://打开店铺订单页面
                        paramTemp = "{}";
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", paramTemp);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", paramTemp);
                        break;
                    default://打开app
                        paramTemp = "{}";
                        androidNotificationExtras.Add("option", strPushType);
                        androidNotificationExtras.Add("param", paramTemp);
                        iosNotificationExtras.Add("option", strPushType);
                        iosNotificationExtras.Add("param", paramTemp);
                        break;
                }
            }
            //推送消息
            Dictionary<string, object> androidNotificationVal = new Dictionary<string, object>();
            androidNotificationVal.Add("val", androidNotificationExtras);
            Dictionary<string, object> androidNotification = new Dictionary<string, object>();
            androidNotification.Add("extras", androidNotificationVal);
            Dictionary<string, object> iosNotificationVal = new Dictionary<string, object>();
            iosNotificationVal.Add("val", iosNotificationExtras);
            Dictionary<string, object> iosNotification = new Dictionary<string, object>();
            iosNotification.Add("extras", iosNotificationVal);
            Dictionary<string, object> notification = new Dictionary<string, object>();
            notification.Add("alert", strMessage);
            notification.Add("android", androidNotification);
            notification.Add("ios", iosNotification);
            dataSend.Add("notification", notification);
            //设置IOS的环境,false为开发环境,true为生产环境
            Dictionary<string, object> options = new Dictionary<string, object>();
            options.Add("apns_production", false);
            dataSend.Add("options", options);
            //转化为Json格式
            JavaScriptSerializer js = new JavaScriptSerializer();
            string JsonStr = js.Serialize(dataSend);
            #endregion


            try
            {
                string JPush_Uri = "https://api.jpush.cn/v3/push";
                string App_Key = "808a3e149a54f82dbdb06f47";
                string Master_Secret = "ced2ca08b8b789585dfa9222";
                string result = result = RequestWebClient(JPush_Uri , JsonStr , null, App_Key , Master_Secret );;
                if (result == null && result == "")
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "alert(\"发送失败!\");", true);
                }
            }
            catch (APIRequestException ex)
            {
                System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), ".msg", "alert(\"发送失败!'" + ex + "'\");", true);
            }
        }

    }


 public static string RequestWebClient(string uri, string paramStr, Encoding encoding, string username, string password)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;
            string result = string.Empty;
            WebClient wc = new WebClient();
            // 采取POST方式必须加的Header
            wc.Headers.Add("Content-Type", "application/json");
            byte[] postData = encoding.GetBytes(paramStr);
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                wc.Credentials = GetCredentialCache(uri, username, password);
                wc.Headers.Add("Authorization", GetAuthorization(username, password));
            }


            byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
            return encoding.GetString(responseData);// 解码                  
        }
        public static CredentialCache GetCredentialCache(string uri, string username, string password)
        {
            string authorization = string.Format("{0}:{1}", username, password);
            CredentialCache credCache = new CredentialCache();
            credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
            return credCache;
        }
        public static string GetAuthorization(string username, string password)
        {
            string authorization = string.Format("{0}:{1}", username, password);
            return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值