public ActionResult OnGetMyInfo(string kindergartenName, string sessionId) { StatusReport sr = new StatusReport(); if (string.IsNullOrEmpty(kindergartenName)) { sr.status = "Fail"; sr.result = "未指定幼儿园"; return(Json(sr)); } if (string.IsNullOrEmpty(sessionId)) { sr.status = "Fail"; sr.result = "sessionId不存在"; sr.parameters = sessionId; return(Json(sr)); } SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; sr = WXUserDal.GetMyInfo(kindergartenName, openId); return(Json(sr)); }
public ActionResult DecodeEncryptedData(string type, string sessionId, string encryptedData, string iv) { DecodeEntityBase decodedEntity = null; string openid = SessionContainer.GetSession("ApartmentRent").OpenId; switch (type.ToUpper()) { case "USERINFO": //wx.getUserInfo() decodedEntity = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeUserInfoBySessionId( sessionId, encryptedData, iv); break; default: break; } //检验水印 var checkWartmark = false; if (decodedEntity != null) { checkWartmark = decodedEntity.CheckWatermark(SenparcClass.Service.Config.WxOpenAppId); } //注意:此处仅为演示,敏感信息请勿传递到客户端! return(Json(new { success = checkWartmark, //decodedEntity = decodedEntity, msg = string.Format("水印验证:{0}", checkWartmark ? "通过" : "不通过") })); }
public async Task <IActionResult> UpdatePhone(string sessionId, string tell) { CommonResult result = new CommonResult(); var sessionBag = SessionContainer.GetSession(sessionId); try { User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", sessionBag.OpenId); user.MobilePhone = tell; if (user.NickName == "游客" || string.IsNullOrEmpty(user.NickName)) { user.NickName = tell; } result.Success = await userService.UpdateAsync(user, user.Id); if (result.Success) { result.ErrCode = ErrCode.successCode; } } catch (Exception ex) { result.ErrMsg = ex.Message; Log4NetHelper.Error("更新用户电话号码 UpdatePhone", ex); } return(ToJsonContent(result)); }
public ActionResult OnSetWXInfo(string sessionId, string nickName, int gender, string kindergartenName) { StatusReport sr = new StatusReport(); if (string.IsNullOrEmpty(sessionId)) { sr.status = "Fail"; sr.result = "sessionId不存在"; sr.parameters = sessionId; return(Json(sr)); } SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; sr = WXUserDal.SetWXInfo(openId, nickName, gender, kindergartenName); return(Json(sr)); }
public ActionResult OnGetUserInfo(string sessionId) { StatusReport sr = new StatusReport(); if (string.IsNullOrEmpty(sessionId))//如果sessionId为空,则返回错误信息 { sr.status = "Fail"; sr.result = "sessionId不存在"; sr.parameters = sessionId; return(Json(sr)); } SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; sr = ProprietorDal.CheckOpenIdExist(openId); //if (sr.data != null) //{ // var o = JsonConvert.DeserializeObject(sr.data); // return Json(new { status = "Success", result = "成功", data = o }); //} //else //{ return(Json(sr)); //} }
public ActionResult OnBindUser(string userName, string password, string sessionId) { StatusReport sr = new StatusReport(); SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; //string openId = "oTTDy0KN71B2XLMXobrapvhqlHcY"; int id = EmployeeDal.CheckEmployeeExist(userName, password); string temp = id > 0 ? "存在" : "不存在"; if (id > 0) { sr = EmployeeDal.BindEmployee(id, openId); return(Json(sr)); } else { var data = new { msg = "hello world", username = userName, password = password, isExist = temp }; return(Json(data)); } }
private string GetOpenid(string sessionKey) { SessionBag sessionBag = SessionContainer.GetSession(sessionKey); string opeinId = sessionBag.OpenId; return(opeinId); }
public override async Task OnMessageReceiced(WebSocketHelper webSocketHandler, ReceivedMessage receivedMessage, string originalData) { if (receivedMessage == null || string.IsNullOrEmpty(receivedMessage.Message)) { return; } var message = receivedMessage.Message; await webSocketHandler.SendMessage("您发送了文字:" + message); await webSocketHandler.SendMessage("正在处理中..."); await Task.Delay(1000); //处理文字 var result = string.Concat(message.Reverse()); await webSocketHandler.SendMessage(result); try { //发送模板消息 var formId = receivedMessage.FormId;//发送模板消息使用,需要在wxml中设置<form report-submit="true"> var sessionBag = SessionContainer.GetSession(receivedMessage.SessionId); var openId = sessionBag != null ? sessionBag.OpenId : "用户未正确登陆"; await webSocketHandler.SendMessage("OpenId:" + openId); if (sessionBag == null) { openId = "onh7q0DGM1dctSDbdByIHvX4imxA";//临时测试 } //var data = new WxOpenTemplateMessage_PaySuccessNotice( // "在线购买", DateTime.Now, "图书众筹", "1234567890", // 100, "400-9939-858", "http://sdk.senparc.weixin.com"); var data = new { keyword1 = new TemplateDataItem("ADD"), keyword2 = new TemplateDataItem(DateTime.Now.ToString()), keyword3 = new TemplateDataItem("Name"), keyword4 = new TemplateDataItem("Number"), keyword5 = new TemplateDataItem(100.ToString("C")), keyword6 = new TemplateDataItem("400-9939-858"), }; var appId = WebConfigurationManager.AppSettings["WxOpenAppId"];//与微信小程序账号后台的AppId设置保持一致,区分大小写。 var tmResult = Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(appId, openId, "Oc7R_U_23T8DtVgWn3d__-WkIctx_yDWTg8_4Mx8wgY", data, receivedMessage.FormId, null, null); } catch (Exception ex) { await webSocketHandler.SendMessage(ex.Message + "\r\n\r\n" + originalData + "\r\n\r\nAPPID:" + WebConfigurationManager.AppSettings["WxOpenAppId"]); } }
public object Do_Payment(object param) { PaymentParam paymentParam = JsonConvert.DeserializeObject <PaymentParam>(param.ToString()); if (paymentParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } try { SessionBag sessionBag = SessionContainer.GetSession(paymentParam.token); var openId = sessionBag.OpenId; var billId = this.createBill(openId, paymentParam); var totalPrice = this.getBillPrice(paymentParam); if (totalPrice == 0) { throw new ApiException(CodeMessage.PaymentTotalPriceZero, "PaymentTotalPriceZero"); } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var product = paymentParam.product; var xmlDataInfo = new TenPayV3UnifiedorderRequestData( tenPayV3Info.AppId, tenPayV3Info.MchId, product, billId, totalPrice, "127.0.0.1", tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, tenPayV3Info.Key, nonceStr); var result = TenPayV3.Html5Order(xmlDataInfo); pDao.writePrePayId(billId, result.prepay_id); var package = string.Format("prepay_id={0}", result.prepay_id); var paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); PaymentResults paymentResults = new PaymentResults(); paymentResults.appId = tenPayV3Info.AppId; paymentResults.nonceStr = nonceStr; paymentResults.package = package; paymentResults.paySign = paySign; paymentResults.timeStamp = timeStamp; paymentResults.product = product; paymentResults.billId = billId; return(paymentResults); } catch (Exception ex) { throw new ApiException(CodeMessage.PaymentError, "PaymentError"); } }
public ActionResult TemplateTest(string sessionId, string formId) { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag != null ? sessionBag.OpenId : "用户未正确登陆"; string title = null; decimal price = 100; string productName = null; string orderNumber = null; if (formId.StartsWith("prepay_id=")) { formId = formId.Replace("prepay_id=", ""); title = "这是来自小程序支付的模板消息"; var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance(); var unifiedorderRequestData = cacheStrategy.Get <TenPayV3UnifiedorderRequestData>($"WxOpenUnifiedorderRequestData-{openId}"); //获取订单请求信息缓存 var unifedorderResult = cacheStrategy.Get <UnifiedorderResult>($"WxOpenUnifiedorderResultData-{openId}"); //获取订单信息缓存 if (unifedorderResult != null && formId == unifedorderResult.prepay_id) { price = unifiedorderRequestData.TotalFee; productName = unifiedorderRequestData.Body + "/缓存获取 prepay_id 成功"; orderNumber = unifiedorderRequestData.OutTradeNo; } else { productName = "缓存获取 prepay_id 失败"; orderNumber = "1234567890"; } productName += " | 注意:这条消息是从小程序发起的!仅作为UI上支付成功的演示!不能确定支付真实成功! | prepay_id:" + unifedorderResult.prepay_id; } else { title = "在线购买(小程序Demo测试)"; productName = "商品名称-模板消息测试"; orderNumber = "9876543210"; } var data = new WxOpenTemplateMessage_PaySuccessNotice(title, DateTime.Now, productName, orderNumber, price, "400-031-8816", "https://sdk.senparc.weixin.com"); try { Senparc.Weixin.WxOpen.AdvancedAPIs .Template.TemplateApi .SendTemplateMessage( WxOpenAppId, openId, data.TemplateId, data, formId, "pages/index/index", "图书", "#fff00"); return(Json(new { success = true, msg = "发送成功,请返回消息列表中的【服务通知】查看模板消息。\r\n点击模板消息还可重新回到小程序内。" })); } catch (Exception ex) { return(Json(new { success = false, openId = openId, formId = formId, msg = ex.Message })); } }
public static string GetOpenID(string token) { SessionBag sessionBag = SessionContainer.GetSession(token); if (sessionBag == null) { return(null); } return(sessionBag.OpenId); }
public ActionResult GetPrepayid(string sessionId) { try { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag.OpenId; //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 var sp_billno = string.Format("{0}{1}{2}", Config.SenparcWeixinSetting.TenPayV3_MchId /*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6)); var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = "小程序微信支付Demo"; var price = 1;//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, Config.SenparcWeixinSetting.TenPayV3_MchId, body, sp_billno, price, Request.UserHostAddress, Config.SenparcWeixinSetting.TenPayV3_WxOpenTenpayNotify, TenPay.TenPayV3Type.JSAPI, openId, Config.SenparcWeixinSetting.TenPayV3_Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求:" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果:" + result.ToJson()); var packageStr = "prepay_id=" + result.prepay_id; //记录到缓存 var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance(); cacheStrategy.Set($"WxOpenUnifiedorderRequestData-{openId}", xmlDataInfo, TimeSpan.FromDays(4));//3天内可以发送模板消息 cacheStrategy.Set($"WxOpenUnifiedorderResultData-{openId}", result, TimeSpan.FromDays(4));//3天内可以发送模板消息 return Json(new { success = true, prepay_id = result.prepay_id, appId = Config.SenparcWeixinSetting.WxOpenAppId, timeStamp, nonceStr, package = packageStr, //signType = "MD5", paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, Config.SenparcWeixinSetting.TenPayV3_Key) }); } catch (Exception ex) { return Json(new { success = false, msg = ex.Message }); } }
/// <summary> /// 登陆 /// </summary> /// <param name="baseApi"></param> /// <returns></returns> public object Do_GetToken(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } if (loginParam.code == Global.XCSECRET) { SessionBag sessionBagX = SessionContainer.GetSession(Global.XCOPENID); if (sessionBagX != null) { if (sessionBagX.Name != "") { SessionContainer.RemoveFromCache(sessionBagX.OpenId); } } AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, Global.XCOPENID, Global.XCOPENID); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); Member member = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member == null) { throw new ApiException(CodeMessage.SenparcCode, CodeMessage.SenparcCode.ToString()); } else { sessionUser.userType = "MEMBER"; sessionUser.openid = sessionBag.OpenId; sessionUser.memberId = member.memberId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag); SessionBag bag = new SessionBag(); bag.Name = sessionBag.Key; SessionContainer.UpdateSession(Global.XCOPENID, sessionBag.Key, sessionBag.Key); return(new { token = sessionBag.Key }); } } else { throw new ApiException(CodeMessage.SenparcCode, CodeMessage.SenparcCode.ToString()); } }
public ActionResult OnBindUser(string userName, string phoneNumber, string sessionId) { StatusReport sr = new StatusReport(); SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); //string sessionCode = (string)sessionBag.Name; //string sessionCode =(string)HttpContext.Session[phoneNumber]; if (sessionBag == null)//如果sessionId失效,返回失败信息 { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr, JsonRequestBehavior.AllowGet)); } //if (string.IsNullOrEmpty(sessionCode))//如果sessionCode失效,返回失败信息 //{ // sr.status = "Fail"; // sr.result = "codeSession已失效"; // sr.parameters = phoneNumber; // return Json(sr,JsonRequestBehavior.AllowGet); //} //if (code != sessionCode)//如果验证码与用户收到的验证码不一致,返回失败信息 //{ // sr.status = "Fail"; // sr.result = "code错误"; // return Json(sr, JsonRequestBehavior.AllowGet); //} string openId = sessionBag.OpenId; int id = ProprietorDal.CheckProprietorExist(userName, phoneNumber); string temp = id != 0 ? "存在" : "不存在"; if (id != 0) { sr = ProprietorDal.BindProprietor(Math.Abs(id), userName, phoneNumber, openId, id > 0 ? true : false); return(Json(sr, JsonRequestBehavior.AllowGet)); } else { var data = new { msg = "hello world", username = userName, phoneNumber = phoneNumber, isExist = temp }; return(Json(data, JsonRequestBehavior.AllowGet)); } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string token = Request.Headers["wechat_token"]; if (token.HasValue() && SessionContainer.GetSession(token) != null) { // check right for later. var ticket = Membership.AuthenticationTicket(token, "", "", true, Scheme.Name); return(await Task.FromResult(AuthenticateResult.Success(ticket))); } return(await Task.FromResult(AuthenticateResult.NoResult())); }
public ActionResult OnSetKanyuanData(string kindergartenName, string name, string gender, string birth, string relateName, string relation, string phoneNumber, string address, string isYoueryuan, string desire, string joinLottery, string ruyuanDate, string isAppointment, string appointmentDate, string relateGender, string haveReceiver, string receiverName, string needSchoolBus, string sessionId) { StatusReport sr = new StatusReport(); //如果未指定幼儿园,返回错误信息 if (string.IsNullOrEmpty(kindergartenName)) { sr.status = "Fail"; sr.result = "未指定幼儿园"; return(Json(sr)); } //如果姓名或联系方式为空,返回错误信息 if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(phoneNumber)) { sr.status = "Fail"; sr.result = "姓名和联系电话不能为空"; return(Json(sr)); } if (string.IsNullOrEmpty(sessionId)) { sr.status = "Fail"; sr.result = "sessionId不存在"; sr.parameters = sessionId; return(Json(sr)); } SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; sr = WXUserDal.SetUserInfo(openId, relateName, phoneNumber, kindergartenName, name, relation); //如果提交的数据满足条件,调用KanyuanDataDal.SetKanyuanData方法,将数据存入数据库中 sr = KanyuanDataDal.SetKanyuanData(kindergartenName, name, gender, birth, relateName, relation, phoneNumber, address, isYoueryuan, desire, joinLottery, ruyuanDate, isAppointment, appointmentDate, relateGender, haveReceiver, receiverName, needSchoolBus, openId); return(Json(sr)); }
public ActionResult DecryptPhoneNumberLogin([FromBody] DecryptModel decrypt) { var sessionBag = SessionContainer.GetSession(decrypt.sessionId); DecodedPhoneNumber phoneNumber = null; try { phoneNumber = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptPhoneNumber(decrypt.sessionId, decrypt.encryptedData, decrypt.iv); //throw new WeixinException("解密PhoneNumber异常测试");//启用这一句,查看客户端返回的异常信息 if (phoneNumber == null) { throw new WeixinException("解密PhoneNumber异常测试,PhoneNumber为空."); } } catch (Exception ex) { //return Json(new { success = false, msg = ex.Message }); return(Json(HttpResult.WeChatError(ex.Message, null))); } //注册并登录 string errorMessage = string.Empty; try { User user = new User(); var userInfo = decrypt.userInfo; user.Name = userInfo.nickName; user.NickName = userInfo.nickName; user.HeadImgUrl = userInfo.avatarUrl; user.Sex = (Enums.Sex)userInfo.gender; user.UnionId = string.IsNullOrWhiteSpace(sessionBag.UnionId) ? userInfo.unionId : sessionBag.UnionId; user.Mobile = phoneNumber.purePhoneNumber; user.Area = string.Join('-', new List <string>() { userInfo.country, userInfo.province, userInfo.city }); var userToken = UserBussiness.Init.WXOpenRLogin(user, (string.IsNullOrWhiteSpace(sessionBag.OpenId) ? userInfo.openId : sessionBag.OpenId), out errorMessage); if (string.IsNullOrWhiteSpace(userToken) || !string.IsNullOrWhiteSpace(errorMessage)) { return(Json(HttpResult.Success(HttpResultCode.Fail, errorMessage, new { userToken }))); } return(Json(HttpResult.Success(new { userToken }))); } catch (Exception ex) { return(Json(HttpResult.Success(HttpResultCode.Fail, ex.Message, null))); } }
public SessionBag RunTemplateTest(string wxOpenAppId, string sessionId, string formId) { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag != null ? sessionBag.OpenId : "用户未正确登陆"; string title = null; decimal price = 1;//单位:分,实际使用过程中,通过数据库获取订单并读取 string productName = null; string orderNumber = null; if (formId.StartsWith("prepay_id=")) { formId = formId.Replace("prepay_id=", ""); title = "这是来自小程序支付的模板消息(仅测试接收,数据不一定真实)"; var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance(); var unifiedorderRequestData = cacheStrategy.Get <TenPayV3UnifiedorderRequestData>($"WxOpenUnifiedorderRequestData-{openId}"); //获取订单请求信息缓存 var unifedorderResult = cacheStrategy.Get <UnifiedorderResult>($"WxOpenUnifiedorderResultData-{openId}"); //获取订单信息缓存 if (unifedorderResult != null && formId == unifedorderResult.prepay_id) { price = unifiedorderRequestData.TotalFee; productName = unifiedorderRequestData.Body + "/缓存获取 prepay_id 成功"; orderNumber = unifiedorderRequestData.OutTradeNo; } else { productName = "缓存获取 prepay_id 失败"; orderNumber = "1234567890"; } productName += " | 注意:这条消息是从小程序发起的!仅作为UI上支付成功的演示!不能确定支付真实成功! | prepay_id:" + unifedorderResult.prepay_id; } else { title = "在线购买(仅测试小程序接收模板消息,数据不一定真实)"; productName = "商品名称-模板消息测试"; orderNumber = "9876543210"; } var data = new WxOpenTemplateMessage_PaySuccessNotice(title, SystemTime.Now, productName, orderNumber, price, "400-031-8816", "https://sdk.senparc.weixin.com"); Senparc.Weixin.WxOpen.AdvancedAPIs .Template.TemplateApi .SendTemplateMessage( wxOpenAppId, openId, data.TemplateId, data, formId, "pages/index/index", "图书", "#fff00"); return(sessionBag); }
public static string GetMemberID(string token) { SessionBag sessionBag = SessionContainer.GetSession(token); if (sessionBag == null) { return(null); } SessionUser sessionUser = JsonConvert.DeserializeObject <SessionUser>(sessionBag.Name); if (sessionUser == null) { return(null); } return(sessionUser.memberId); }
public object Do_GetOrder(object param) { OrderListParam orderListParam = JsonConvert.DeserializeObject <OrderListParam>(param.ToString()); if (orderListParam == null || orderListParam.orderId == "" || orderListParam.orderId == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } SessionBag sessionBag = SessionContainer.GetSession(orderListParam.token); var openId = sessionBag.OpenId; OrderDao orderDao = new OrderDao(); OrderListItem orderListItem = orderDao.getOrder(openId, orderListParam.orderId); return(orderListItem); }
/// <summary> /// 检查token判断执行权限 /// </summary> /// <param name="apiType"></param> /// <param name="token"></param> /// <returns></returns> private bool CheckToken(ApiType apiType, string token) { bool b = true; #if !DEBUG if (apiType != ApiType.UserApi) { SessionBag sessionBag = SessionContainer.GetSession(token); if (sessionBag == null) { b = false; } } #endif return(b); }
public JsonResponse DecryptPhoneNumber([FromBody] PhoneView phoneView) { var sessionBag = SessionContainer.GetSession(phoneView.SessionId); try { var ret = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptPhoneNumber(phoneView.SessionId, phoneView.EncryptedData, phoneView.Iv); HttpRuntime.Cache.Insert($"{phoneView.OpenId}_phone", ret.phoneNumber, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); HttpRuntime.Cache.Insert($"{phoneView.OpenId}_openid", phoneView.OpenId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); return(FastResponse(new { IsSuccess = true, Message = ret })); } catch (Exception ex) { return(FastResponse(new { IsSuccess = false, Message = ex.Message })); } }
/// <summary> /// 解密电话号码 /// </summary> /// <param name="sessionId">The session identifier.</param> /// <param name="encryptedData">The encrypted data.</param> /// <param name="iv">The iv.</param> /// <param name="openId">The open identifier.</param> /// <returns>ActionResult.</returns> public ActionResult DecryptPhoneNumber(string sessionId, string encryptedData, string iv, string openId) { var sessionBag = SessionContainer.GetSession(sessionId); try { var ret = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptPhoneNumber(sessionId, encryptedData, iv); HttpRuntime.Cache.Insert($"{openId}_phone", ret.phoneNumber, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); HttpRuntime.Cache.Insert($"{openId}_openid", openId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); return(Json(new { IsSuccess = true, Message = ret })); } catch (Exception ex) { return(Json(new { IsSuccess = false, Message = ex.Message })); } }
public object Do_ShopUserReg(BaseApi baseApi) { StoreUserRegParam storeUserRegParam = JsonConvert.DeserializeObject <StoreUserRegParam>(baseApi.param.ToString()); if (storeUserRegParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } SessionBag sessionBag = SessionContainer.GetSession(baseApi.token); if (sessionBag == null) { throw new ApiException(CodeMessage.InvalidToken, "InvalidToken"); } OpenDao openDao = new OpenDao(); string openID = Utils.GetOpenID(baseApi.token); StoreUser storeUser = openDao.GetStoreUser(openID); if (storeUser != null) { throw new ApiException(CodeMessage.StoreUserExist, "StoreUserExist"); } string storeId = openDao.GetStoreId(storeUserRegParam.storeCode); if (storeId == "") { throw new ApiException(CodeMessage.InvalidStoreCode, "InvalidStoreCode"); } if (!openDao.StoreUserReg(storeUserRegParam, openID, storeId)) { throw new ApiException(CodeMessage.StoreUserRegError, "StoreUserRegError"); } storeUser = openDao.GetStoreUser(openID); SessionUser sessionUser = JsonConvert.DeserializeObject <SessionUser>(sessionBag.Name); sessionUser.openid = sessionBag.OpenId; sessionUser.storeUserId = storeUser.storeUserId; sessionUser.userType = "STORE"; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); return(""); }
public ActionResult GetPrepayid(string sessionId) { try { var sessionBag = SessionContainer.GetSession(sessionId); var openId = sessionBag.OpenId; //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 var sp_billno = string.Format("{0}{1}{2}", Service.Config.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"), Guid.NewGuid().ToString("n").Substring(0, 6)); //生成订单信息并保存到数据库 var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = "小程序微信支付Demo"; var price = 1;//单位:分 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(Service.Config.WxOpenAppId, Service.Config.MchId, body, sp_billno, price, Request.UserHostAddress, Service.Config.TenPayV3Notify, TenPayV3Type.JSAPI, openId, Service.Config.TenPayV3_Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口 var packageStr = "prepay_id=" + result.prepay_id; return(Json(new { success = true, prepay_id = result.prepay_id, appId = Service.Config.WxOpenAppId, timeStamp, nonceStr, package = packageStr, //signType = "MD5", paySign = TenPayV3.GetJsPaySign(Service.Config.WxOpenAppId, timeStamp, nonceStr, packageStr, Service.Config.TenPayV3_Key) })); } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } }
/// <summary> /// 解密运动步数 /// </summary> /// <param name="sessionId"></param> /// <param name="encryptedData"></param> /// <param name="iv"></param> /// <returns></returns> public ActionResult DecryptRunData(string sessionId, string encryptedData, string iv) { var sessionBag = SessionContainer.GetSession(sessionId); try { var runData = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptRunData(sessionId, encryptedData, iv); //throw new WeixinException("解密PhoneNumber异常测试");//启用这一句,查看客户端返回的异常信息 return(Json(new { success = true, runData = runData })); } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } }
public void UpdateSessionTest() { var openId = "openid"; var sessionKey = "sessionKey"; var bag = SessionContainer.UpdateSession(null, openId, sessionKey); Console.WriteLine("bag.Key:{0}", bag.Key); Console.WriteLine("bag.ExpireTime:{0}", bag.ExpireTime); var key = bag.Key; Thread.Sleep(1000); var bag2 = SessionContainer.GetSession(key); Assert.IsNotNull(bag2); Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime); }
public IActionResult DecryptPhoneNumber(string sessionId, string encryptedData, string iv) { CommonResult result = new CommonResult(); var sessionBag = SessionContainer.GetSession(sessionId); try { var phoneNumber = EncryptHelper.DecryptPhoneNumber(sessionId, encryptedData, iv); result.ResData = phoneNumber; result.ErrCode = ErrCode.successCode; } catch (Exception ex) { result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }
public static string TryWeappAutoLogin(this IAccessControl ac, JObject data, out string errMsg) { errMsg = null; var app = ac.Context.RequestServices.GetService <IWeChatContainer>().GetApp(); var session = data.GetValue("sessionid", key => SessionContainer.GetSession(key)); if (session == null) { // session未建立,通过code登录换取session var result = WeChatApi.WxLogin(app, data.GetValue("code", "")); if (result.ErrorCodeValue == 0) { // success,成功时更新session session = SessionContainer.UpdateSession(null, result.openid, result.session_key, result.unionid); } else { errMsg = result.errmsg; } } if (session != null) { // 根据OpenID自动登录 var service = ac.Context.RequestServices.GetService <IUserService>(); var user = service.GetByAuth(app.Id, session.OpenId); if (user == null) { // OpenID对应的用户不存在,解密客户端数据 var cryptedData = data.GetValue("encryptedData", ""); var iv = data.GetValue("iv", ""); var userInfo = EncryptHelper.DecodeUserInfoBySessionId(session.Key, cryptedData, iv); // 自动创建用户 var mobile = data.GetValue <string>("mobile"); var wechatService = ac.Context.RequestServices.GetService <IWechatService>(); user = wechatService.WeappRegist(app, userInfo, mobile); } return($"{user.HashId}-{session.SessionKey}"); } return(null); }
public ActionResult OnUnifiedOrder(string sessionId, double totalCharge, string dataBag) { StatusReport sr = new StatusReport(); SessionBag sessionBag = null; sessionBag = SessionContainer.GetSession(sessionId); if (sessionBag == null) { sr.status = "Fail"; sr.result = "session已失效"; return(Json(sr)); } string openId = sessionBag.OpenId; sr = WXPayDal.UnifiedOrder(openId, totalCharge, dataBag); return(Json(sr)); }