//public static TokenHelper TokenHelper { private set; get; } public static void Register() { Token = System.Configuration.ConfigurationManager.AppSettings["Token"]; EncodingAESKey = System.Configuration.ConfigurationManager.AppSettings["EncodingAESKey"]; AppID = System.Configuration.ConfigurationManager.AppSettings["AppID"]; AppSecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"]; PartnerKey = System.Configuration.ConfigurationManager.AppSettings["PartnerKey"]; Domain = System.Configuration.ConfigurationManager.AppSettings["Domain"]; mch_id = System.Configuration.ConfigurationManager.AppSettings["mch_id"]; device_info = System.Configuration.ConfigurationManager.AppSettings["device_info"]; spbill_create_ip = System.Configuration.ConfigurationManager.AppSettings["spbill_create_ip"]; var openJSSDK = int.Parse(System.Configuration.ConfigurationManager.AppSettings["OpenJSSDK"]) > 0; OauthScope = System.Configuration.ConfigurationManager.AppSettings["OauthScope"]; WeixinDomain = ""; AccessToken = BasicAPI.GetAccessToken(AppID, AppSecret).access_token; WeixinSDK.GlobalContext.AppID = AppID; WeixinSDK.GlobalContext.AppSecret = AppSecret; WeixinSDK.GlobalContext.AccessToken = AccessToken; WeixinSDK.GlobalContext.WebAccessToken = WebAccessToken; WeixinSDK.GlobalContext.Domain = Domain; //TokenHelper = new TokenHelper(6000, AppID, AppSecret, openJSSDK); //TokenHelper.Run(); }
static void Main(string[] args) { BasicAPI api = new BasicAPI(); login : Console.Write("Mail: "); string mail = System.Net.WebUtility.UrlEncode(Console.ReadLine()); Console.Write("Password: "******"ログインに失敗しました。"); goto login; } LobiAPI.Json.Me me = api.GetMe(); /*LobiAPI.Json.PublicGroups[] PublicGroups = api.GetPublicGroupList(); * LobiAPI.Json.PrivateGroups[] PrivateGroups = api.GetPrivateGroupList(); * LobiAPI.Json.Notifications Notifications = api.GetNotifications(); * LobiAPI.Json.Followers Followers = api.GetFollowers(me.uid); * LobiAPI.Json.Contacts Contacts = api.GetContacts(me.uid); * LobiAPI.Json.Group Group = api.GetGroup(PublicGroups[0].items[0].uid); * LobiAPI.Json.User[] users = api.GetGroupMembers(PublicGroups[0].items[0].uid); * LobiAPI.Json.Chat[] chats = api.GetThreads(PublicGroups[0].items[0].uid);*/ Console.ReadLine(); }
public ActionResult MiniPost(PostModel postModel) { var ent = ""; if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent)) { //return Content("参数错误!");//v0.7- return(new WeixinResult("参数错误!"));//v0.8+ } var encryptMsg = string.Empty; WeixinMessage message = null; using (var streamReader = new StreamReader(Request.InputStream)) { var decryptMsg = streamReader.ReadToEnd(); message = AcceptMessageAPI.Parse(decryptMsg); } encryptMsg = new WeixinExecutor().Execute(message); return(new WeixinResult(encryptMsg) { ContentType = "text/xml", ContentEncoding = System.Text.UTF8Encoding.UTF8 }); }
private static void ReqWeixinToken() { var access_token = BasicAPI.GetAccessToken(AppID, AppSecret).access_token; var js = JSAPI.GetTickect(access_token); var jssdk_ticket = js.ticket; var json = DynamicJson.Serialize(new weixin_token { access_token = access_token, jssdk_ticket = jssdk_ticket }); cache.Insert(AppID, json, null, DateTime.Now.AddSeconds(ACCESS_TOKEN_EXPIRE_SECONDS), System.Web.Caching.Cache.NoSlidingExpiration); }
private void Initialize() { //construct and authenticate streaming/basic APIs m_bAPI = new BasicAPI(m_oaCredentials); m_sAPI = new StreamingAPI(m_oaCredentials); m_slStatuses = new StatusList(); m_ldmDirectMessages = new List <DirectMessage>(); m_usUserStream = m_sAPI.GetUserStream(); }
public TimelineStatus(Status stFrom, BasicAPI bAPI) { InitializeComponent(); m_bAPI = bAPI; m_bDisplayConversationButton = false; m_fntScreenNameFont = new Font("Arial", 10); m_fntRetweetedFont = new Font("Arial", 8); m_fntFromUser = new Font("Arial", 10, FontStyle.Bold); m_sbFromUser = new SolidBrush(Color.Black); m_sbRetweet = new SolidBrush(Color.FromArgb(70, 70, 70)); m_pnBorderPen = new Pen(Color.FromArgb(220, 220, 220)); m_stStatusObj = stFrom; ttfTextField.UpdateFromStatus(m_stStatusObj); Favorite = Boolean.Parse(m_stStatusObj["favorited"].ToString()); if (m_stStatusObj.IsRetweet) { if (m_stStatusObj.RetweetedStatus == null) { if ((m_stStatusObj.StatusText.Words.Count > 1) && (m_stStatusObj.StatusText.Words[1].Type == StatusTextElement.StatusTextElementType.ScreenName)) { m_sFromUser = m_stStatusObj.StatusText.Words[1].Text.Substring(1); new Thread(new ThreadStart(UserLookup)).Start(); } } else { m_sFromUser = m_stStatusObj.RetweetedStatus.User["screen_name"].ToString(); AsyncContentManager.GetManager().RequestImage(m_stStatusObj.RetweetedStatus.User["profile_image_url"].ToString(), AvatarCallback); } } else { m_sFromUser = m_stStatusObj.User["screen_name"].ToString(); AsyncContentManager.GetManager().RequestImage(m_stStatusObj.User["profile_image_url"].ToString(), AvatarCallback); } User uActiveUser = TwitterController.GetController().ActiveAccount.UserObject; if (uActiveUser != null) { Retweet = m_stStatusObj.IsRetweet && (m_sFromUser == TwitterController.GetController().ActiveAccount.UserObject["screen_name"].ToString()); } ttfTextField.TextElementClicked += new TweetTextField.TextElementClickHandler(ttfTextField_TextElementClicked); abRetweet.Click += new EventHandler(abRetweet_Click); abFavorite.Click += new EventHandler(abFavorite_Click); abReply.Click += new EventHandler(abReply_Click); abConversation.Click += new EventHandler(abConversation_Click); }
public ActionResult Get(PostModel postModel, string echostr) { if (string.IsNullOrEmpty(WeixinConfig.Token)) { return(Content("请先设置Token!")); } var ent = ""; if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent)) { return(Content("参数错误!")); } return(Content(echostr)); //返回随机字符串则表示验证通过 }
static void Main(string[] args) { var api = new BasicAPI(); Login(api); var me = api.GetMe().Result; var me_contacts = api.GetContacts().Result; var me_followers = api.GetFollowers().Result; var user = api.GetUser("402aeea6d30bfbce06f79b61f5776991e5c82e02").Result; var user_contacts = api.GetContacts("402aeea6d30bfbce06f79b61f5776991e5c82e02").Result; var user_followers = api.GetFollowers("402aeea6d30bfbce06f79b61f5776991e5c82e02").Result; Console.ReadLine(); }
public ActionResult Get(string signature, string timestamp, string nonce, string echostr) { var token = XiaoWeiXinSdkTask.Token;//微信公众平台后台设置的Token if (string.IsNullOrEmpty(token)) { return(Content("请先设置Token!")); } var ent = ""; if (!BasicAPI.CheckSignature(signature, timestamp, nonce, token, out ent)) { return(Content("参数错误!")); } return(Content(echostr)); //返回随机字符串则表示验证通过 }
public UserStream(OAuthCredentials oaCredentials) { m_oaCredentials = oaCredentials; m_bscAPI = new BasicAPI(m_oaCredentials); m_rcClient = new RestClient { Authority = C_BASE_URL, VersionPath = C_VERSION_PATH, Credentials = m_oaCredentials, Method = WebMethod.Get, StreamOptions = new StreamOptions { ResultsPerCallback = 1 } }; }
static void Login(BasicAPI api) { while (true) { Console.Clear(); Console.Write("Mail: "); string mail = Console.ReadLine(); Console.Write("Password: "******"ログイン失敗...."); } Console.WriteLine("ログインしました。"); Console.WriteLine(); }
/// <summary> /// 获取accountToken并缓存1小时 /// </summary> /// <returns></returns> public string AccountToken() { var token = ""; try { token = CacheHelper.Get("XiaoAccountToken") as string; if (string.IsNullOrEmpty(token)) { token = BasicAPI.GetAccessToken(appID, appsecret).access_token; CacheHelper.Set("XiaoAccountToken", token, 60 * 60);//缓存一个小时 } } catch (Exception e) { SysExceptionTask.AddException(e, "获取XiaoAccountToken"); } return(token); }
public void Push(Status stToAdd, BasicAPI bAPI) { TimelineStatus tsNewStatus = new TimelineStatus(stToAdd, bAPI); TimelineStatus tsOldTop = null; DisableLoadingAnimation(); if (m_stsControls.Count > 0) { tsOldTop = m_stsControls.Peek(); } this.Controls.Add(tsNewStatus); m_stsControls.Push(tsNewStatus); tsNewStatus.UpdateLayout(); tsNewStatus.BackColor = this.BackColor; HookupStatusEvents(tsNewStatus); m_iTotalControlHeight += tsNewStatus.Height; OnResize(EventArgs.Empty); if (m_bScrolledToTop) { if (tsOldTop != null) { tsNewStatus.Top = tsOldTop.Top - tsNewStatus.Height; } else { tsNewStatus.Top = -(tsNewStatus.Height); } } else { tsNewStatus.Top = 0; this.Top -= tsNewStatus.Height; } tsNewStatus.Visible = true; UpdateLayout(); }
// GET: api/WxConfig/5 public WxConfig Get(int id) { string _appid = "wx6aae9a42791c0cdf"; string _appsecret = "71201c6d9ca47d1375ca2de8dbdf1c93"; long _timestamp = Util.CreateTimestamp(); string _nonceStr = Util.CreateNonce_str(); string _signature = ""; string string1 = ""; var ic = Redis.Create("127.0.0.1", 7); ic.Log = XTrace.Log; var access_token = ic.Get <string>("access_token"); var jsapi_ticket = ic.Get <string>("jsapi_ticket"); if (access_token != null && jsapi_ticket != null) { _signature = JSAPI.GetSignature(jsapi_ticket, _nonceStr, _timestamp, "", out string1); } else { var access_token_json = BasicAPI.GetAccessToken(_appid, _appsecret); ic.Set("access_token", access_token_json.access_token, 7200); var jsapi_ticket_json = JSAPI.GetTickect(access_token_json.access_token); ic.Set("jsapi_ticket", jsapi_ticket_json.ticket, 7200); _signature = JSAPI.GetSignature(jsapi_ticket_json.ticket, _nonceStr, _timestamp, "", out string1); } return(new WxConfig { appId = _appid, timestamp = _timestamp, nonceStr = _nonceStr, signature = _signature }); }
public string GetJsTicket(string appid, string appSecret, bool force) { try { var access_token = ""; var jssdk_ticket = ""; if (force && cache.Contains(appid)) { cache.Remove(appid); } if (!cache.Contains(appid)) { access_token = BasicAPI.GetAccessToken(appid, appSecret).access_token; var js = JSAPI.GetTicket(access_token); jssdk_ticket = js.ticket; var json = DynamicJson.Serialize(new weixin_token { access_token = access_token, jssdk_ticket = jssdk_ticket }); var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds(ACCESS_TOKEN_EXPIRE_SECONDS) }; cache.Set(appid, json, policy); } else { var weixin_token = DynamicJson.Parse(cache.Get(appid).ToString()); access_token = weixin_token.access_token; jssdk_ticket = weixin_token.jssdk_ticket; } AppLogManager.Write(string.Format("appid:{0}, access_token: {1}, jssdk_ticket: {2}", appid, access_token, jssdk_ticket)); return(jssdk_ticket); } catch (Exception ex) { LogWriter.Default.WriteError(ex); return(string.Empty); } }
private void refreshToken() { if (!Status) { return; } LastRunDateTime = DateTime.Now; try { string newToken = BasicAPI.GetAccessToken(AppId, AppSecrect).access_token; _token = newToken; if (TokenChangedEvent != null) { TokenChangedEvent(this, EventArgs.Empty); } } catch (Exception ex) { if (ErrorEvent != null) { ErrorEvent(this, new ThreadExceptionEventArgs(ex)); } } }
public void Execute(IJobExecutionContext context) { var msg = ""; var _log = new LogTask(); var _wxconfig = new WeiXinConfigTask(); var configList = _wxconfig.GetListConfig(); foreach (var item in configList) { var config = _wxconfig.GetConfig(item.WeiXinId); if (config != null) { try { item.AccessToken = BasicAPI.GetAccessToken(item.AppId, item.Appsecret).access_token; item.JsApiToken = JSAPI.GetTickect(item.AccessToken).ticket; item.TokenUpdateTime = DateTime.Now; msg = _wxconfig.UpdateToken(item).Msg; } catch (Exception e) { var log = new Log() { CreateTime = DateTime.Now, Msg = "公众号token更新错误:" + e.Message + ";时间:" + DateTime.Now, Ret = 0 }; _log.AddLog(log); } } var log1 = new Log() { CreateTime = DateTime.Now, Msg = "公众号token更新:" + item.WeiXinId + "执行:" + msg + ";时间:" + DateTime.Now, Ret = 0 }; _log.AddLog(log1); } }
public static void Register() { Token = System.Configuration.ConfigurationManager.AppSettings["Token"]; EncodingAESKey = System.Configuration.ConfigurationManager.AppSettings["EncodingAESKey"]; AppID = System.Configuration.ConfigurationManager.AppSettings["AppID"]; AppSecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"]; PartnerKey = System.Configuration.ConfigurationManager.AppSettings["PartnerKey"]; Domain = System.Configuration.ConfigurationManager.AppSettings["Domain"]; APIDomain = System.Configuration.ConfigurationManager.AppSettings["APIDomain"]; mch_id = System.Configuration.ConfigurationManager.AppSettings["mch_id"]; DeviceInfo = System.Configuration.ConfigurationManager.AppSettings["device_info"]; SpbillCreateIp = System.Configuration.ConfigurationManager.AppSettings["spbill_create_ip"]; var openJSSDK = int.Parse(System.Configuration.ConfigurationManager.AppSettings["OpenJSSDK"]) > 0; OauthScope = System.Configuration.ConfigurationManager.AppSettings["OauthScope"]; Report_Levenl = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Report_Levenl"]); PayNotifyUrl = System.Configuration.ConfigurationManager.AppSettings["PayNotifyUrl"]; WeixinDomain = ""; AccessToken = BasicAPI.GetAccessToken(AppID, AppSecret).access_token; WeixinSDK.GlobalContext.AppID = AppID; WeixinSDK.GlobalContext.AppSecret = AppSecret; WeixinSDK.GlobalContext.AccessToken = AccessToken; WeixinSDK.GlobalContext.WebAccessToken = WebAccessToken; WeixinSDK.GlobalContext.Domain = Domain; WeixinSDK.GlobalContext.APIDomain = APIDomain; WeixinSDK.GlobalContext.MCHId = mch_id; WeixinSDK.GlobalContext.PartnerKey = PartnerKey; WeixinSDK.GlobalContext.DeviceInfo = DeviceInfo; WeixinSDK.GlobalContext.SpbillCreateIp = SpbillCreateIp; WeixinSDK.GlobalContext.Report_Levenl = Report_Levenl; WeixinSDK.GlobalContext.PayNotifyUrl = PayNotifyUrl; AccessTokenHelper = new AccessTokenHelper(6000, AppID, AppSecret, openJSSDK); AccessTokenHelper.Run(); }
public void GetCallbackIP() { BasicAPI.GetCallbackIP(WeixinConfig.AccessToken); }
/// <summary> /// 说明:带TODO字眼的代码段,需要开发者自行按照自己的业务逻辑实现 /// </summary> /// <param name="message"></param> /// <returns>已经打包成xml的用于回复用户的消息包</returns> public async Task <string> Execute(WeixinMessage message) { var result = ""; var domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];//请更改成你的域名 var openId = message.Body.FromUserName.Value; var myUserName = message.Body.ToUserName.Value; //这里需要调用TokenHelper获取Token的,省略了。 switch (message.Type) { case WeixinMessageType.Text: //文字消息 { var msgId = message.Body.MsgId.Value.ToString(); string userMessage = message.Body.Content.Value; if (MvcApplication.GetCache(msgId) != null) { result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, MvcApplication.GetCache(msgId)); } else { string BotMessage = await MSBot.PostMessage(userMessage); result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, BotMessage); //result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,您输入了:" + userMessage +" 要不你发个图片试试?"); } } break; case WeixinMessageType.Image: //图片消息 string imageUrl = message.Body.PicUrl.Value; //图片地址 string mediaId = message.Body.MediaId.Value; //mediaId string meg = ""; try { //meg = await ComputerVisionHelper.MakeAnalyzeImageRequest(message.Body.PicUrl.Value); meg = await ComputerVisionHelper.MakeOCRRequest(message.Body.PicUrl.Value); } catch (Exception ex) { meg = ex.Message; } result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, meg); //result = ReplayPassiveMessageAPI.ReplayImage(openId, myUserName, mediaId); break; case WeixinMessageType.Video: //视频消息 #region 视频消息 { var media_id = message.Body.MediaId.Value.ToString(); var thumb_media_id = message.Body.ThumbMediaId.Value.ToString(); var msgId = message.Body.MsgId.Value.ToString(); //TODO result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("视频消息:openid:{0},media_id:{1},thumb_media_id:{2},msgId:{3}", openId, media_id, thumb_media_id, msgId)); } #endregion break; case WeixinMessageType.Voice: //语音消息 #region 语音消息 { /* * var media_id = message.Body.MediaId.Value.ToString(); * var format = message.Body.Format.Value.ToString(); * var msgId = message.Body.MsgId.Value.ToString(); * var messageRec = message.Body.Recognition.Value.ToString(); */ var media_id = message.Body.MediaId.Value.ToString(); var format = message.Body.Format.Value.ToString(); var msgId = message.Body.MsgId.Value.ToString(); //var messageRec = message.Body.Recognition.Value.ToString(); var token = BasicAPI.GetAccessToken("wxb1275f7967642487", "d4624c36b6795d1d99dcf0547af5443d"); var url = string.Format("https://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", token, media_id); string content = new BaiduSpeechRecognition().getStrText("en", url, "amr", "8000"); result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, content); if (MvcApplication.GetCache(content) == null) { result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "語音識別錯誤!"); } string BotMessage = await MSBot.PostMessage(content); //result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, BotMessage); } #endregion break; case WeixinMessageType.Location: //地理位置消息 #region 地理位置消息 { var location_X = message.Body.Location_X.Value.ToString(); var location_Y = message.Body.Location_Y.Value.ToString(); var scale = message.Body.Scale.Value.ToString(); var Label = message.Body.Label.Value.ToString(); //TODO result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("地理位置消息: openid:{0},Location_X:{1},Location_Y:{2},Scale:{3},label:{4}", openId, location_X, location_Y, scale, Label)); } #endregion break; case WeixinMessageType.Link: //链接消息 #region 链接消息 { var title = message.Body.Title.Value.ToString(); var description = message.Body.Description.Value.ToString(); var url = message.Body.Url.Value.ToString(); var msgId = message.Body.MsgId.Value.ToString(); //TODO result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("openid:{0},title:{1},description:{2},url:{3},msgId:{4}", openId, title, description, url, msgId)); } #endregion break; case WeixinMessageType.Event: string eventType = message.Body.Event.Value.ToLower(); string eventKey = string.Empty; try { eventKey = message.Body.EventKey.Value; } catch { } switch (eventType) { case "subscribe": //用户未关注时,进行关注后的事件推送 #region 首次关注 var token = WeixinConfig.TokenHelper.GetToken(); //TODO: 获取用户基本信息后,将用户信息存储在本地。 //var weixinInfo = UserAdminAPI.GetInfo(token, openId);//注意:订阅号没有此权限 if (!string.IsNullOrEmpty(eventKey)) { var qrscene = eventKey.Replace("qrscene_", ""); //此为场景二维码的场景值 result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews { title = "欢迎订阅,场景值:" + qrscene, description = "欢迎订阅,场景值:" + qrscene, picurl = string.Format("{0}/ad.jpg", domain), url = domain }); } else { result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews { title = "欢迎订阅", description = "欢迎订阅,点击此消息查看在线demo", picurl = string.Format("{0}/ad.jpg", domain), url = domain }); } #endregion break; case "unsubscribe": //取消关注 #region 取消关注 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来"); #endregion break; case "scan": // 用户已关注时的事件推送 #region 已关注扫码事件 if (!string.IsNullOrEmpty(eventKey)) { var qrscene = eventKey.Replace("qrscene_", ""); //此为场景二维码的场景值 result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews { title = "欢迎使用,场景值:" + qrscene, description = "欢迎使用,场景值:" + qrscene, picurl = string.Format("{0}/ad.jpg", domain), url = domain }); } else { result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews { title = "欢迎使用", description = "欢迎订阅,点击此消息查看在线demo", picurl = string.Format("{0}/ad.jpg", domain), url = domain }); } #endregion break; case "masssendjobfinish": //事件推送群发结果, #region 事件推送群发结果 { var msgId = message.Body.MsgID.Value; var msgStatus = message.Body.Status.Value; //“send success”或“send fail”或“err(num)” //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。 //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪, //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他 var totalCount = message.Body.TotalCount.Value; //group_id下粉丝数;或者openid_list中的粉丝数 var filterCount = message.Body.FilterCount.Value; //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount var sentCount = message.Body.SentCount.Value; //发送成功的粉丝数 var errorCount = message.Body.FilterCount.Value; //发送失败的粉丝数 //TODO:开发者自己的处理逻辑,这里用log4net记录日志 LogWriter.Default.WriteInfo(string.Format("mass send job finishe,msgId:{0},msgStatus:{1},totalCount:{2},filterCount:{3},sentCount:{4},errorCount:{5}", msgId, msgStatus, totalCount, filterCount, sentCount, errorCount)); } #endregion break; case "templatesendjobfinish": //模版消息结果, #region 模版消息结果 { var msgId = message.Body.MsgID.Value; var msgStatus = message.Body.Status.Value; //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed //TODO:开发者自己的处理逻辑,这里用log4net记录日志 LogWriter.Default.WriteInfo(string.Format("template send job finish,msgId:{0},msgStatus:{1}", msgId, msgStatus)); } #endregion break; case "location": //上报地理位置事件 #region 报地理位置事件 var lat = message.Body.Latitude.Value.ToString(); var lng = message.Body.Longitude.Value.ToString(); var pcn = message.Body.Precision.Value.ToString(); //TODO:在此处将经纬度记录在数据库,这里用log4net记录日志 LogWriter.Default.WriteInfo(string.Format("openid:{0} ,location,lat:{1},lng:{2},pcn:{3}", openId, lat, lng, pcn)); #endregion break; case "voice": //语音消息 #region 语音消息 //A:已开通语音识别权限的公众号 var userVoice = message.Body.Recognition.Value; //用户语音消息文字 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "您说:" + userVoice); //B:未开通语音识别权限的公众号 var userVoiceMediaId = message.Body.MediaId.Value; //media_id //TODO:调用自定义的语音识别程序识别用户语义 #endregion break; case "image": //图片消息 #region 图片消息 var userImage = message.Body.PicUrl.Value; //用户语音消息文字 result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews { title = "您刚才发送了图片消息", picurl = string.Format("{0}/Images/ad.jpg", domain), description = "点击查看图片", url = userImage }); #endregion break; case "click": //自定义菜单事件 #region 自定义菜单事件 { switch (eventKey) { case "myaccount": //CLICK类型事件举例 #region 我的账户 result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>() { new WeixinNews { title = "我的帐户", url = string.Format("{0}/user?openId={1}", domain, openId), description = "点击查看帐户详情", picurl = string.Format("{0}/Images/ad.jpg", domain) }, }); #endregion break; case "www.weixinsdk.net": //VIEW类型事件举例,注意:点击菜单弹出子菜单,不会产生上报。 //TODO:后台处理逻辑 break; default: result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件"); break; } } #endregion break; case "view": //点击菜单跳转链接时的事件推送 #region 点击菜单跳转链接时的事件推送 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey)); #endregion break; case "scancode_push": //扫码推事件的事件推送 { var scanType = message.Body.ScanCodeInfo.ScanType.Value; //扫描类型,一般是qrcode var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey)); } break; case "scancode_waitmsg": //扫码推事件且弹出“消息接收中”提示框的事件推送 { var scanType = message.Body.ScanCodeInfo.ScanType.Value; //扫描类型,一般是qrcode var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey)); } break; case "pic_sysphoto": //弹出系统拍照发图的事件推送 { var count = message.Body.SendPicsInfo.Count; //发送的图片数量 var picList = message.Body.PicList; //发送的图片信息 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出系统拍照发图,count:{0},EventKey:{1}", count, eventKey)); } break; case "pic_photo_or_album": //弹出拍照或者相册发图的事件推送 { var count = message.Body.SendPicsInfo.Count.Value; //发送的图片数量 var picList = message.Body.PicList.Value; //发送的图片信息 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出拍照或者相册发图,count:{0},EventKey:{1}", count, eventKey)); } break; case "pic_weixin": //弹出微信相册发图器的事件推送 { var count = message.Body.SendPicsInfo.Count.Value; //发送的图片数量 var picList = message.Body.PicList.Value; //发送的图片信息 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出微信相册发图器,count:{0},EventKey:{1}", count, eventKey)); } break; case "location_select": //弹出地理位置选择器的事件推送 { var location_X = message.Body.SendLocationInfo.Location_X.Value; //X坐标信息 var location_Y = message.Body.SendLocationInfo.Location_Y.Value; //Y坐标信息 var scale = message.Body.SendLocationInfo.Scale.Value; //精度,可理解为精度或者比例尺、越精细的话 scale越高 var label = message.Body.SendLocationInfo.Label.Value; //地理位置的字符串信息 var poiname = message.Body.SendLocationInfo.Poiname.Value; //朋友圈POI的名字,可能为空 result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出地理位置选择器,location_X:{0},location_Y:{1},scale:{2},label:{3},poiname:{4},eventKey:{5}", location_X, location_Y, scale, label, poiname, eventKey)); } break; case "card_pass_check": //生成的卡券通过审核时,微信会把这个事件推送到开发者填写的URL。 { var cardid = message.Body.CardId.Value; //CardId result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您的卡券已经通过审核")); } break; case "card_not_pass_check": //生成的卡券未通过审核时,微信会把这个事件推送到开发者填写的URL。 { var cardid = message.Body.CardId.Value; //CardId } break; case "user_get_card": //用户在领取卡券时,微信会把这个事件推送到开发者填写的URL。 { var cardid = message.Body.CardId.Value; //CardId var isGiveByFriend = message.Body.IsGiveByFriend.Value; //是否为转赠,1代表是,0代表否。 var fromUserName = message.Body.FromUserName.Value; //领券方帐号(一个OpenID) var friendUserName = message.Body.FriendUserName.Value; //赠送方账号(一个OpenID),"IsGiveByFriend”为1时填写该参数。 var userCardCode = message.Body.UserCardCode.Value; //code序列号。自定义code及非自定义code的卡券被领取后都支持事件推送。 var outerId = message.Body.OuterId.Value; //领取场景值,用于领取渠道数据统计。可在生成二维码接口及添加JSAPI接口中自定义该字段的整型值。 } break; case "user_del_card": //用户在删除卡券时,微信会把这个事件推送到开发者填写的URL { var cardid = message.Body.CardId.Value; //CardId var userCardCode = message.Body.UserCardCode.Value; //商户自定义code值。非自定code推送为空 } break; case "merchant_order": //微信小店:订单付款通知:在用户在微信中付款成功后,微信服务器会将订单付款通知推送到开发者在公众平台网站中设置的回调URL(在开发模式中设置)中,如未设置回调URL,则获取不到该事件推送。 { var orderId = message.Body.OrderId.Value; //CardId var orderStatus = message.Body.OrderStatus.Value; //OrderStatus var productId = message.Body.ProductId.Value; //ProductId var skuInfo = message.Body.SkuInfo.Value; //SkuInfo } break; } break; default: result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type)); break; } return(result); }
public void GetCallbackIP() { BasicAPI.GetCallbackIP(WeixinConfig.AccessTokenHelper.GetToken()); }
public void GetAccessToken() { WeixinConfig.AccessToken = BasicAPI.GetAccessToken(WeixinConfig.AppID, WeixinConfig.AppSecret).access_token; }
public ActionResult Post(PostModel postModel) { postModel.Token = WeixinConfig.Token; //postModel.EncodingAESKey = WeixinConfig.EncodingAESKey; postModel.AppId = WeixinConfig.AppID; var ent = ""; if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent)) { return(Content("参数错误!")); } var encryptMsg = string.Empty; WeixinMessage message = null; var safeMode = Request.QueryString.Get("encrypt_type") == "aes"; using (var streamReader = new StreamReader(Request.InputStream)) { var decryptMsg = string.Empty; var msg = streamReader.ReadToEnd(); #region 解密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, postModel.Timestamp, postModel.Nonce, msg, ref decryptMsg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 Log.Instence.LogWriteLine(string.Format("decrypt message return {0}, request body {1}", ret, msg)); } } else { decryptMsg = msg; } #endregion message = AcceptMessageAPI.Parse(decryptMsg); } var response = new WeixinExecutor().Execute(message); #region 加密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.EncryptMsg(response, postModel.Timestamp, postModel.Nonce, ref encryptMsg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 Log.Instence.LogWriteLine(string.Format("encrypt message return {0}, response body {1}", ret, response)); } } else { encryptMsg = response; } #endregion return(new ContentResult { Content = encryptMsg, ContentType = "text/xml", ContentEncoding = System.Text.UTF8Encoding.UTF8 }); }