/// <summary> /// 菜单事件 /// </summary> /// <param nickname="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage) { IResponseMessageBase reponseMessage = null; //菜单点击,需要跟创建菜单时的Key匹配 //JULONG.CAFTS.Weixin.Models.WeixinDBContext db = new Models.WeixinDBContext(); //WeixinArtcle wa = db.WeixinArtcle.FirstOrDefault(d => d.Name == requestMessage.EventKey); //var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); using (DBContext db = new DBContext()) { var msg = db.WxArtcle.FirstOrDefault(d => d.Name == requestMessage.EventKey); if (msg != null) { var accessToken = AccessTokenContainer.TryGetAccessToken(Config.WX_AppId, Config.WX_AppSecret); List <Article> arts = new List <Article>(); arts.Add(ArticleHelper.StringToArticle(msg.Description)); Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendNews(accessToken, requestMessage.FromUserName, arts, 5000); } } return(reponseMessage); }
/// <summary> /// 扫码推事件,并且弹出“消息获取中”提示框 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnEvent_ScancodeWaitmsgRequest(RequestMessageEvent_Scancode_Waitmsg requestMessage) { string AppId = "wx739b4a998d710f0b";//与微信公众账号后台的AppId设置保持一致,区分大小写。 string AppSecret = "96c92d012934a873820d97084c18d93d"; string pwd = "jwysoft20122012,"; string msg = requestMessage.ScanCodeInfo.ScanResult; WebReference.Service1 method = new WebReference.Service1(); string result = method.QueryContract(pwd, msg); var responseMessage = base.CreateResponseMessage <ResponseMessageText>(); var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); string UserName = UserApi.Info(accessToken, responseMessage.ToUserName).nickname; responseMessage.Content = "您好" + UserName + "\r\n查询结果是:\r\n" + result; //将用户查询日志添加进数据库 UserLog model = new UserLog(); model.AccountName = requestMessage.FromUserName; model.QueryCode = requestMessage.ScanCodeInfo.ScanResult; model.QueryContent = result; model.CreateDate = requestMessage.CreateTime; model.NickName = UserName; UserLogService.AddUserLog(model); return(responseMessage); }
private WxMpServiceInstance() { AccessToken = AccessTokenContainer.TryGetAccessToken(ConfigHelper.AppConfig["appId"], ConfigHelper.AppConfig["appSecret"]); //AddTestRouter(); BuildMenu(); }
public ActionResult DeleteCustomMenu(string menuId) { try { if (string.IsNullOrEmpty(_wxAccount.AppId) || string.IsNullOrEmpty(_wxAccount.Secret)) { return(Json(new { error = true, message = "AppId或AppSecret为空" }, JsonRequestBehavior.AllowGet)); } var token = AccessTokenContainer.TryGetAccessToken(_wxAccount.AppId, _wxAccount.Secret); var result = string.IsNullOrEmpty(menuId) ? CommonApi.DeleteMenu(token) : CommonApi.DeleteMenuConditional(token, menuId); var json = new { error = result.errmsg != "ok", message = result.errmsg }; return(Json(json, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { var json = new { error = true, message = ex.Message }; return(Json(json, JsonRequestBehavior.AllowGet)); } }
public ActionResult CreateMenuForMerchant() { ButtonGroup bg = new ButtonGroup(); // 添加注册菜单 bg.button.Add(new SingleViewButton() { name = "客户注册", url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", AppId, Url.Encode("http://hightch.shareparking.net/User_CustomerInfo/Create")), type = MenuButtonType.view.ToString(), }); bg.button.Add(new SingleViewButton() { name = "商家注册", url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", AppId, Url.Encode("http://hightch.shareparking.net/User_MerchantInfo/Create")), type = MenuButtonType.view.ToString(), }); bg.button.Add(new SingleViewButton() { name = "我的订单", url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", AppId, Url.Encode("http://hightch.shareparking.net/CustomerOrders/Index")), type = MenuButtonType.view.ToString(), }); var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); var result = CommonApi.CreateMenu(accessToken, bg); return(Json(new { Success = result.errmsg == "ok", Message = "菜单更新成功。" }, JsonRequestBehavior.AllowGet)); }
public void ContainerTest() { //注册 AccessTokenContainer.Register(base._appId, base._appSecret); //获取Token完整结果(包括当前过期秒数) var tokenResult = AccessTokenContainer.GetAccessTokenResult(base._appId); Assert.IsNotNull(tokenResult); Console.WriteLine(tokenResult.access_token); //只获取Token字符串 var token = AccessTokenContainer.GetAccessToken(base._appId); Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); //getNewToken { token = AccessTokenContainer.TryGetAccessToken(base._appId, base._appSecret, false); Assert.AreEqual(tokenResult.access_token, token); Console.WriteLine(tokenResult.access_token); token = AccessTokenContainer.TryGetAccessToken(base._appId, base._appSecret, true); Assert.AreNotEqual(tokenResult.access_token, token);//如果微信服务器缓存,此处会相同 Console.WriteLine(tokenResult.access_token); } }
// GET: WeChat public ActionResult Get(PostModel postModel, string echostr) { var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); ButtonGroup bg = new ButtonGroup(); //单击 bg.button.Add(new SingleClickButton() { type = "scancode_waitmsg", name = "扫防护码", key = "FANGHU", }); bg.button.Add(new SingleClickButton() { type = "scancode_push", name = "扫防化码", key = "OneClick", }); bg.button.Add(new SingleViewButton() { url = "http://1p623v6690.iok.la/Home", name = "离线存储" }); var result = CommonApi.CreateMenu(accessToken, bg); if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content(echostr)); } else { return(Content("连接失败!")); } }
public void SendTemplateMessageTestForBook() { var _appId = "wx03ea2f7f93b7cf96"; var _appSecret = "609bd314b63811293cec1d9adb84e699"; //Senparc.Weixin.MP.Containers.AccessTokenContainer.Register(_appId, _appSecret); var accessToken = AccessTokenContainer.TryGetAccessToken(_appId, _appSecret); var openId = "ozLW4wHYTcApj55HIUT0o8Qdet6U"; //消息目标用户的OpenId var templateId = "7VMaAiEXaI9WabE8z5_oRTtUjimclgeLc6XuwgIw__o"; //7VMaAiEXaI9WabE8z5_oRTtUjimclgeLc6XuwgIw__o templateId = "jGWhXy1FpVQP2GaEki1ReAQAcbE6KyWEp5PmiNlnvhk"; var data = new { first = new TemplateDataItem("您的订单已经支付"), keyword1 = new TemplateDataItem("飞翔的企鹅"), keyword2 = new TemplateDataItem("123456789"), keyword3 = new TemplateDataItem("1000", "#ff0000"),//显示为红色 keyword4 = new TemplateDataItem("购买课时"), remark = new TemplateDataItem("更详细信息,官方网站(http://www.baidu.com)查看!") }; var result = TemplateApi.SendTemplateMessage(_appId, openId, templateId, "http://www.cnblogs.com", data); Assert.AreEqual(Senparc.Weixin.ReturnCode.请求成功, result.errcode); }
public object PostWithdraw(DistributionApplyWithdraw post) { CheckUserLogin(); var sitesettings = SiteSettingApplication.SiteSettings; post.MemberId = CurrentUser.Id; if (post.Type == DistributionWithdrawType.WeChat) //获取用户微信账户 { var mo = MemberApplication.GetMemberOpenIdInfoByuserId(CurrentUser.Id, Entities.MemberOpenIdInfo.AppIdTypeEnum.Payment, "Mall.Plugin.OAuth.WeiXin"); if (mo == null) { return(Json(ErrorResult <bool>("无法获取微信账号,请先在微信端绑定账号!"))); } var openid = mo.OpenId; post.WithdrawAccount = openid; if (!(string.IsNullOrWhiteSpace(sitesettings.WeixinAppId) || string.IsNullOrWhiteSpace(sitesettings.WeixinAppSecret))) { string token = AccessTokenContainer.TryGetAccessToken(sitesettings.WeixinAppId, sitesettings.WeixinAppSecret); var user = CommonApi.GetUserInfo(token, openid); post.WithdrawName = user?.nickname ?? string.Empty; } } DistributionApplication.ApplyWithdraw(post); return(Json(true)); }
public ActionResult GetToken(string appId, string appSecret) { try { var result = AccessTokenContainer.TryGetAccessToken(appId, appSecret); return(Json(result, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); } catch (ErrorJsonResultException ex) { return(Json(new { error = "API 调用发生错误:{0}".FormatWith(ex.JsonResult.ToJson()) }, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); } catch (Exception ex) { return(Json(new { error = "执行过程发生错误:{0}".FormatWith(ex.Message) }, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); } }
public object GetWxacode(string pagePath, int width) { var sitesetting = SiteSettingApplication.SiteSettings; var accessToken = AccessTokenContainer.TryGetAccessToken(sitesetting.WeixinAppletId, sitesetting.WeixinAppletSecret); var data = "{\"path\":\"" + HttpUtility.UrlDecode(pagePath) + "\",\"width\":" + width + "}"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken); //创建url request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; byte[] load = Encoding.UTF8.GetBytes(data); request.ContentLength = load.Length; Stream writer = request.GetRequestStream(); writer.Write(load, 0, load.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); byte[] mg = StreamToBytes(s); MemoryStream ms = new MemoryStream(mg); string qrCodeImagePath = string.Empty; qrCodeImagePath = "data:image/gif;base64," + Convert.ToBase64String(ms.ToArray()); ms.Dispose(); var QrCodeImagePath = qrCodeImagePath; var result = SuccessResult <dynamic>(data: QrCodeImagePath); return(Json(result)); }
private bool SavePicture(string name) { try { MemoryStream img = new MemoryStream(); var accessToken = AccessTokenContainer.TryGetAccessToken(MvcApplication.WeiXinAppId, MvcApplication.WeiXinSecret); Senparc.Weixin.MP.AdvancedAPIs.MediaApi.Get(accessToken, name, img); string fileName = name + ".jpg"; string savePath = Server.MapPath("~/Upload/") + DateTime.Now.ToString("yyyyMMdd"); if (System.IO.Directory.Exists(savePath) == false)//如果不存在就创建file文件夹 { System.IO.Directory.CreateDirectory(savePath); } FileStream writer = new FileStream(savePath + "/" + fileName, FileMode.OpenOrCreate, FileAccess.Write); img.WriteTo(writer); writer.Close(); writer.Dispose(); return(true); } catch (Exception e) { throw new Exception(e.Message); return(false); } }
/// <summary> /// 订阅(关注)事件 /// </summary> /// <returns></returns> public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage) { var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); var responseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageText>(requestMessage); string result = string.Format("欢迎关注唐门年华公众号!"); // string redirectUrl = AgentUrl + "/WeiXin/OAuth"; // string oAuthUrl = OAuthApi.GetAuthorizeUrl(AppId, // redirectUrl, // "123", OAuthScope.snsapi_base); UserInfoJson userInfo = UserApi.Info(accessToken, requestMessage.FromUserName); int isOk = SaveUser(userInfo); Log.Debug("订阅事件,保存用户", isOk > 0 ? requestMessage.FromUserName + "保存成功" : "保存失败", null); responseMessage.Content = result; if (!string.IsNullOrEmpty(requestMessage.EventKey)) { responseMessage.Content += "\r\n============\r\n场景值:" + requestMessage.EventKey; } return(responseMessage); }
public async Task <ActionResult> Test() { //注册 await AccessTokenContainer.RegisterAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret); var accessToken = AccessTokenContainer.TryGetAccessToken("wx4b58f9e96371d9ff", "43c5c4d9b8207634eb293a72ddad5bb1", true); var token = await AccessTokenContainer.TryGetAccessTokenAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false); //获取Ticket完整结果(包括当前过期秒数) var ticketResult = JsApiTicketContainer.GetJsApiTicketResult(TenPayV3Info.AppId); // //只获取Ticket字符串 var ticket = JsApiTicketContainer.GetJsApiTicket(TenPayV3Info.AppId); //getNewTicket { ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false); ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, true); //Assert.AreNotEqual(ticketResult.ticket, ticket);//如果微信服务器缓存,此处会相同 } return(Content(token)); }
/// <summary> /// 访问微信接口查看是否关注 /// </summary> private bool IsAttentionByRPC(string openId) { var siteSetting = SiteSettingApplication.SiteSettings; string accessToken = ""; if (!string.IsNullOrEmpty(siteSetting.WeixinAppId) || !string.IsNullOrEmpty(siteSetting.WeixinAppSecret)) { accessToken = AccessTokenContainer.TryGetAccessToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret); } else { throw new MallException("未配置微信相关信息"); } var result = UserApi.Info(accessToken, openId); if (result.errcode == Senparc.Weixin.ReturnCode.合法的OpenID || result.subscribe == 0) { return(false); } else if (result.errcode != 0) { throw new Exception(result.errmsg); } return(result.subscribe == 1); }
internal static string tryGetAccessToken() { string appId = WxConfigFile.config().AppID; string appSecret = WxConfigFile.config().AppSecret; return(AccessTokenContainer.TryGetAccessToken(appId, appSecret)); }
public ActionResult MenusList() { var token = AccessTokenContainer.TryGetAccessToken(AppConfig.Instance.AppId, AppConfig.Instance.AppSecret); var menus = CommonApi.GetMenu(AppConfig.Instance.AppId); return(Json(menus, JsonRequestBehavior.AllowGet)); }
//创建菜单 protected void PublishMenu() { if (Request["menu"] == null) { Json(new { state = false }); return; } string publishJson = EConvert.ConvertEmojiHtml(HttpContext.Current.Server.UrlDecode(Request["menu"])); publishJson = publishJson.Replace("&", "&"); var menu = JsonConvert.DeserializeObject <YchButtonGroup>(publishJson); MpEventBll.SaveAllButtonEvent(menu); var tmp = AccessTokenContainer.TryGetAccessToken(BaseClass.AppId, BaseClass.Secret); //tmp = "weiphp"; var result = MenuWeChatApi.CreateMenu(tmp, publishJson); //var result = new WxJsonResult(); if (result.errcode == 0) { //记录菜单保存记录 MpMenuLogBll.WriteLog(Request["menu"], "cs"); Json(new { state = true }); return; } Json(new { state = false }); }
/// <summary> /// 获取访问令牌 /// </summary> /// <param name="appid"></param> /// <param name="secret"></param> /// <returns></returns> public string GetAccessToken(string appid, string secret, bool IsGetNew = false) { string result = ""; if (!string.IsNullOrWhiteSpace(appid) && !string.IsNullOrWhiteSpace(secret)) { try { if (IsGetNew) { result = AccessTokenContainer.TryGetAccessToken(appid, secret, true); } else { result = AccessTokenContainer.TryGetAccessToken(appid, secret); } } catch (Exception ex) { Log.Error("[WXACT]appId=" + appid + ";appSecret=" + secret + ";" + ex.Message); } } else { throw new MallException("未配置微信公众信息"); } return(result); }
public ActionResult Media(int voteid, string key = "") { var vote = SqlFactory.GetSqlhelper().CreateWhere <VoteInfos>() .Where(o => o.ID == voteid).SingleOrDefault(); var accessToken = AccessTokenContainer.TryGetAccessToken(vote.CorpID, vote.Secret); var items = new List <MediaList_News_Item>(); for (var i = 0; i < 5; i++) { var result = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.GetNewsMediaList(accessToken, 20 * i, 20); items.AddRange(result.item); } if (!string.IsNullOrEmpty(key)) { items = items.Where(o => { var valid = false; foreach (var news_item in o.content.news_item) { if (news_item.title.Contains(key)) { valid = true; break; } } return(valid); }).ToList(); } return(Json(items.Select(o => new { o.media_id, list = o.content.news_item.Select(n => n.title) }), JsonRequestBehavior.AllowGet)); }
/// <summary> /// 订阅(关注)事件 /// </summary> /// <returns></returns> public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage) { var responseMessage = CreateResponseMessage <ResponseMessageNews>(); string name = string.Empty; try { var accessToken = AccessTokenContainer.TryGetAccessToken("wxd4d7bd7f8fdc8156", "0482ace1cf1b9dcf702ba4366be65db8"); var _userInfo = UserApi.Info(accessToken, requestMessage.FromUserName); name = _userInfo.nickname; } catch (Exception err) { name = err.Message; } responseMessage.Articles.Add(new Article() { Title = name + ",算算连云港装修多少钱", Description = name + ",算算连云港装修多少钱", PicUrl = "http://jx.51czb.com/Images/bg.png", Url = "http://m.to8to.com/yezhu/zxbj.php?to8to_from=wechat_price&utm_pos=wbcdl" }); return(responseMessage); }
public JsonResult ResetWXIndustry() { if (!string.IsNullOrWhiteSpace(SiteSettings.WeixinAppId) && !string.IsNullOrWhiteSpace(SiteSettings.WeixinAppSecret)) { var accessToken = AccessTokenContainer.TryGetAccessToken(SiteSettings.WeixinAppId, SiteSettings.WeixinAppSecret); var rdata = ApiHandlerWapper.TryCommonApi(actoken => { const string urlFormat = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={0}"; var msgData = new { industry_id1 = "1", industry_id2 = "4" }; return(CommonJsonSend.Send <Senparc.Weixin.Entities.WxJsonResult>(accessToken, urlFormat, msgData, timeOut: 10000)); }, accessToken); if (rdata.errcode == Senparc.Weixin.ReturnCode.请求成功) { return(Json(new { success = true })); } else { return(Json(new { success = false, msg = rdata.errcode.ToString() + ":" + rdata.errmsg })); } } else { return(Json(new { success = false, msg = "未配置微信公众信息!" })); } }
public ActionResult ApplyWithDraw() { var siteSetting = SiteSettingApplication.SiteSettings; if (string.IsNullOrWhiteSpace(siteSetting.WeixinAppId) || string.IsNullOrWhiteSpace(siteSetting.WeixinAppSecret)) { throw new MallException("未配置公众号参数"); } var token = AccessTokenContainer.TryGetAccessToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret); SceneModel scene = new SceneModel(QR_SCENE_Type.WithDraw) { Object = CurrentUser.Id.ToString() }; SceneHelper helper = new SceneHelper(); var sceneid = helper.SetModel(scene); var ticket = QrCodeApi.Create(token, 300, sceneid, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_SCENE, null); ViewBag.ticket = ticket.ticket; ViewBag.Sceneid = sceneid; var balance = MemberCapitalApplication.GetBalanceByUserId(CurrentUser.Id); ViewBag.ApplyWithMoney = balance; var member = _iMemberService.GetMember(CurrentUser.Id);//CurrentUser对象有缓存,取不到最新数据 ViewBag.IsSetPwd = string.IsNullOrWhiteSpace(member.PayPwd) ? false : true; ViewBag.WithDrawMinimum = siteSetting.WithDrawMinimum; ViewBag.WithDrawMaximum = siteSetting.WithDrawMaximum; ViewBag.Keyword = string.IsNullOrWhiteSpace(SiteSettings.SearchKeyword) ? SiteSettings.Keyword : SiteSettings.SearchKeyword; ViewBag.Keywords = SiteSettings.HotKeyWords; return(View()); }
/// <summary> /// 上传永久素材 主要用到MediaApi这个接口 /// </summary> /// <returns></returns> public UploadImgResult UploadImg() { var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); string imgFilePath = Server.MapPath("~/logo.png"); return(MediaApi.UploadImg(accessToken, imgFilePath)); }
/// <summary> /// 获取菜单 /// </summary> /// <returns></returns> public ActionResult GetMenu() { var accessToken = AccessTokenContainer.TryGetAccessToken(appId, appSecret); //查询菜单 var result02 = CommonApi.GetMenu(accessToken); return(View()); }
// /// <summary> // /// 取得用户组 // /// </summary> // /// <returns></returns> // public JsonResult GetGroupList() // { // Log.Info("≤============", null, null); // string accessToken = string.Empty; // try // { // accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); // Log.Info("取得用户组", accessToken, null); // } // catch (Exception ex) // { // Log.Info("Execute:执行微信处理过程", ex.Message, "Exception"); // } // finally // { // Log.Info("============≥", null, null); // } // GroupsJson groupJson = GroupsApi.Get(accessToken); // return Json(groupJson.groups, JsonRequestBehavior.AllowGet); // } #endregion #region MyRegion 取得所有微信关注的粉丝 // /// <summary> // /// 取得所有微信关注的粉丝 // /// </summary> // /// <returns></returns> // public JsonResult GetUserList() // { // // var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); // OpenIdResultJson openIdResultJson = null; // string nextOpenid = string.Empty; // List<UserInfoJson> list = new List<UserInfoJson>(); // // do // { // openIdResultJson = UserApi.Get(accessToken, nextOpenid); // // nextOpenid = openIdResultJson.next_openid; // // if (openIdResultJson.data != null) // { // foreach (string openid in openIdResultJson.data.openid) // { // UserInfoJson userJson = UserApi.Info(accessToken, openid); // list.Add(userJson); // } // } // // } while (openIdResultJson != null && !string.IsNullOrEmpty(openIdResultJson.next_openid)); // // return Json(list, JsonRequestBehavior.AllowGet); // } #endregion #region 材 /// <summary> /// 上传临时素材-上传一张图片为例 /// </summary> /// <returns></returns> public UploadTemporaryMediaResult UploadTemporaryMedia() { var accessToken = AccessTokenContainer.TryGetAccessToken(AppId, AppSecret); string imgUrl = Server.MapPath("~/logo.png"); UploadTemporaryMediaResult mediaResult = MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image, imgUrl); return(mediaResult); }
public ActionResult Index() { var accessToken = AccessTokenContainer.TryGetAccessToken(appId, secret); TempData["AccessToken"] = accessToken; var jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(appId, secret, Request.AbsoluteUri()); return(View(jssdkUiPackage)); }
public static string GetUserOpenId() { string openid = string.Empty; openid = WechatHttpClientUtil.dooGet( string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid=", AccessTokenContainer.TryGetAccessToken(appid, secret))); return(openid); }
public ActionResult Register(Vip vip, string verifyCode) { ViewBag.Title = "注册"; if (string.IsNullOrEmpty(vip.MobileNo) || string.IsNullOrEmpty(vip.Password) || string.IsNullOrEmpty(vip.VipName)) { ViewBag.Error = "请完善资料"; return(View()); } //验证手机号是否存在 var isCheck = _dal.GetByMobile(vip.MobileNo); if (isCheck != null) { ViewBag.Error = "手机号已存在"; return(View()); } //验证身份证 var user = _dal.GetByCardNo(vip.CardNo); if (user != null) { ViewBag.Error = "身份证号已存在"; return(View()); } //验证码 if (Session["VerCode"] == null || Session["PhoneNo"] == null || Session["VerCode"].ToString() != verifyCode || Session["PhoneNo"].ToString() != vip.MobileNo) { ViewBag.Error = "验证码不正确"; return(View()); } var token = AccessTokenContainer.TryGetAccessToken(AppConfig.Instance.AppId, AppConfig.Instance.AppSecret); if (!string.IsNullOrEmpty(vip.CardImg)) { var fileName = $"/upload/cardimg/{Guid.NewGuid().ToString("N")}.jpg"; Senparc.Weixin.MP.AdvancedAPIs.MediaApi.Get(token, vip.CardImg, Server.MapPath("~" + fileName)); vip.CardImg = fileName; } //添加用户 vip.CreatedBy = "system"; vip.CreatedTime = DateTime.Now; vip.UpdatedBy = "system"; vip.UpdatedTime = DateTime.Now; vip.ImgPath = "/assets/web/images/i_03.png"; _dal.Insert(vip); OAuthHelper.DoOAuth(HttpContext, vip.MobileNo); return(new EmptyResult()); }
/// <summary> /// 测试未经注册的TryGetAccessToken同步方法 /// </summary> /// <returns></returns> public ActionResult TryGetAccessTokenTest() { Senparc.Weixin.Config.ThrownWhenJsonResultFaild = false;//如果错误,不抛出异常 var result = AccessTokenContainer.TryGetAccessToken("YourAppId", "YourSecret", true); Senparc.Weixin.Config.ThrownWhenJsonResultFaild = true; return(Content($"AccessToken: {result?.Substring(0, 10) }...")); }