示例#1
0
        public void Template(string messageId, string appId, string openId, string templateId, string url, Dictionary <string, WxWebSendTemplateRequest.DataItem> data, string formId, PerformContext context)
        {
            var messageStatus = new MessageStatus(_redis, messageId);

            messageStatus.Sended(openId);
            context.WriteLine("向用户「{0}」@「{1}」发送模版消息「{2}」...", openId, appId, templateId);
            var accessToken = _redis.StringGet(CacheKey.UserAccessTokenPrefix + appId);

            if (accessToken.HasValue)
            {
                if (string.IsNullOrEmpty(formId))

                {
                    var resp = WxWebApi.SendTemplate(accessToken, openId, templateId, url, data);
                    if (resp.ErrCode == 0)
                    {
                        messageStatus.SetTemplateMap(resp.MsgId.ToString());
                        context.WriteLine("消息发送成功...[MsgId: {0}]", resp.MsgId);
                    }
                    else
                    {
                        messageStatus.SendError(openId);
                        context.WriteLine("消息发送失败:{0}...", resp.ErrMsg);
                        throw new ServiceException(resp.ErrCode, resp.ErrMsg);
                    }
                }
                else
                {
                    var tmpData = new Dictionary <string, WxAppSendTemplateRequest.DataItem>();
                    foreach (var item in data)
                    {
                        tmpData.Add(item.Key, new WxAppSendTemplateRequest.DataItem {
                            Value = item.Value.Value
                        });
                    }
                    var resp = WxAppApi.SendTemplate(accessToken, openId, templateId, url, formId, tmpData);
                    if (resp.ErrCode == 0)
                    {
                        messageStatus.Success(openId);
                        context.WriteLine("消息发送成功...");
                    }
                    else
                    {
                        messageStatus.SendError(openId);
                        context.WriteLine("消息发送失败:{0}...", resp.ErrMsg);
                        throw new ServiceException(resp.ErrCode, resp.ErrMsg);
                    }
                }
            }
            else
            {
                messageStatus.SendError(openId);
                context.WriteLine("消息发送失败:无法获取AccessToken...");
                throw new ServiceException(-1, "消息发送失败:无法获取AccessToken...");
            }
        }