/** * * 获取收货地址js函数入口参数,详情请参考收货地址共享接口:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_9 * @return string 共享收货地址js函数需要的参数,json格式可以直接做参数使用 */ public string GetEditAddressParameters() { string parameter = ""; try { string host = page.Request.Url.Host; string path = page.Request.Path; string queryString = page.Request.Url.Query; //这个地方要注意,参与签名的是网页授权获取用户信息时微信后台回传的完整url string url = "http://" + host + path + queryString; //构造需要用SHA1算法加密的数据 WxPayData signData = new WxPayData(); signData.SetValue("appid", WxPayConfig.GetConfig().GetAppID()); signData.SetValue("url", url); signData.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); signData.SetValue("noncestr", WxPayApi.GenerateNonceStr()); signData.SetValue("accesstoken", access_token); string param = signData.ToUrl(); Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param); //SHA1加密 string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1"); Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign); //获取收货地址js函数入口参数 WxPayData afterData = new WxPayData(); afterData.SetValue("appId", WxPayConfig.GetConfig().GetAppID()); afterData.SetValue("scope", "jsapi_address"); afterData.SetValue("signType", "sha1"); afterData.SetValue("addrSign", addrSign); afterData.SetValue("timeStamp", signData.GetValue("timestamp")); afterData.SetValue("nonceStr", signData.GetValue("noncestr")); //转为json格式 parameter = afterData.ToJson(); Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter); } catch (Exception ex) { Log.Error(this.GetType().ToString(), ex.ToString()); throw new WxPayException(ex.ToString()); } return(parameter); }
/// <summary> /// 上传图片或文件 不能大于2M /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static string Upfile(string filePath) { FileStream file = new FileStream(filePath, FileMode.Open); byte[] bb = new byte[file.Length]; file.Read(bb, 0, (int)file.Length); file.Close(); string fileName = Path.GetFileName(filePath); MsMultiPartFormData form = new MsMultiPartFormData(); string decodeName = HttpUtility.UrlDecode(Path.GetFileName(fileName));//最终服务器会按原文件名保存文件,所以需要将文件名编码下,防止中文乱码 string fileKeyName = "media"; form.AddStreamFile(fileKeyName, fileName, bb); String hashMd5 = Lib.HashHelper.ComputeMD5(filePath); WxPayData inputObj = new WxPayData(); inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); inputObj.SetValue("media_hash", hashMd5); inputObj.SetValue("sign_type", "HMAC-SHA256"); //inputObj.SetValue("sign", inputObj.MakeSign());//签名 form.AddFormField("mch_id", WxPayConfig.GetConfig().GetMchID()); form.AddFormField("media_hash", hashMd5); form.AddFormField("sign_type", "HMAC-SHA256"); form.AddFormField("sign", inputObj.MakeSign()); //签名 string SERVICE_URL = "https://api.mch.weixin.qq.com/secapi/mch/uploadmedia"; //最终接收文件上传的服务接口 string rst = Lib.HttpService.Post(inputObj.ToXml(), SERVICE_URL, form, true, 10); inputObj = new WxPayData(); inputObj.FromXml(rst); if (inputObj.GetValue("return_code").ToString() == "SUCCESS") { return(inputObj.GetValue("media_id").ToString()); } return(inputObj.GetValue("return_msg").ToString()); }
/// <summary> /// 获取小程序openId /// </summary> /// <param name="code"></param> /// <returns></returns> public AuthCode2Session authCode2Session(string code) { try { #region 获取小程序授权信息 WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.GetConfig().GetAppIDmini()); data.SetValue("secret", WxPayConfig.GetConfig().GetAppSecretmini()); data.SetValue("code", code); data.SetValue("grant_type", "authorization_code"); string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl(); AuthCode2Session auth = wxPageApi.authCode2Session(data.GetValue("appid").ToString(), data.GetValue("secret").ToString(), data.GetValue("code").ToString(), data.GetValue("grant_type").ToString()); #endregion return(auth); } catch (Exception ex) { Log.Error(this.GetType().ToString(), ex.ToString()); throw new WxPayException(ex.ToString()); } }
/** * * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下: * { * "access_token":"ACCESS_TOKEN", * "expires_in":7200, * "refresh_token":"REFRESH_TOKEN", * "openid":"OPENID", * "scope":"SCOPE", * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" * } * 其中access_token可用于获取共享收货地址 * openid是微信支付jsapi支付接口统一下单时必须的参数 * 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html * @失败时抛异常WxPayException */ public UserInfo GetOpenidAndAccessTokenFromCode(string code) { try { #region 构造获取openid及access_token的url WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.GetConfig().GetAppID()); data.SetValue("secret", WxPayConfig.GetConfig().GetAppSecret()); data.SetValue("code", code); data.SetValue("grant_type", "authorization_code"); string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl(); //请求url以获取数据 string result = HttpService.Get(url); Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result); //保存access_token,用于收货地址获取 JsonData jd = JsonMapper.ToObject(result); #endregion string access_token = (string)jd["access_token"]; string openid = (string)jd["openid"]; #region 记录用户授权授,模式必须为snsapi_userinfo,保存用户基本信息 UserInfo info = wxPageApi.GetUserInfo(access_token, openid, WxPayConfig.GetConfig().GetLang()); info.accesstoken = access_token; Log.UserAuthorizeInfo("GetUserInfo", "UserInfo : " + Newtonsoft.Json.JsonConvert.SerializeObject(info)); //记录用户授权后的用户信息 Log.UserAuthorizeInfo("GetUserInfo", "oauthrizeInfo : " + result); //记录用户授权后的用户信息 Log.UserAuthorizeInfo("GetUserInfo", "end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ : " + result); //记录用户授权后的用户信息 #endregion return(info); } catch (Exception ex) { Log.Error(this.GetType().ToString(), ex.ToString()); throw new WxPayException(ex.ToString()); } }
/// <summary> /// 获取审核结果 /// </summary> /// <param name="business_code"></param> /// <returns></returns> public static string Getstate(string business_code) { WxPayData inputObj = new WxPayData(); inputObj.SetValue("version", "1.0"); //接口版本号 inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); //商户号 inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 inputObj.SetValue("business_code", business_code); // inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256); //签名类型 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); string url = "https://api.mch.weixin.qq.com/applyment/micro/getstate"; int timeOut = 10; Log.Debug("申请入驻", "request : " + xml); string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("申请入驻", "response : " + response); return(response); }
//CommonApiTest ca = new CommonApiTest(); protected void Page_Load(object sender, EventArgs e) { Log.Info(this.GetType().ToString(), "page load"); if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["code"])) { string openId; OAuthAccessTokenResult result = null; code = Request.QueryString["code"].ToString(); try { //通过,用code换取access_token var isSecondRequest = false; lock (OAuthCodeCollectionLock) { Log.Info(this.GetType().ToString(), "code:" + code.ToString()); isSecondRequest = OAuthCodeCollection.ContainsKey(code); } if (!isSecondRequest) { //第一次请求 //LogUtility.Weixin.DebugFormat("第一次微信OAuth到达,code:{0}", code); Log.Info(this.GetType().ToString(), "第一次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = null; } } else { //第二次请求 //LogUtility.Weixin.DebugFormat("第二次微信OAuth到达,code:{0}", code); Log.Info(this.GetType().ToString(), "第二次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } try { try { result = result ?? OAuthApi.GetAccessToken(WxPayConfig.GetConfig().GetAppID(), WxPayConfig.GetConfig().GetAppSecret(), code); } catch (Exception ex) { //return Content("OAuth AccessToken错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "OAuth AccessToken错误:" + ex.Message); } if (result != null) { lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = result; } } } catch (ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code) { //code已经被使用过 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } } openId = result != null ? result.openid : null; } catch (Exception ex) { //return Content("授权过程发生错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "\r\n授权过程发生错误:" + ex.Message); } ViewState["openid"] = result.openid; Log.Info(this.GetType().ToString(), result.openid); //使用result继续操作 } else { string url = OAuthApi.GetAuthorizeUrl(WxPayConfig.GetConfig().GetAppID(), "http://www.59online.com/mobile/pay_test.aspx", "state", Senparc.Weixin.MP.OAuthScope.snsapi_base); Response.Redirect(url); } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["code"])) { string openId; OAuthAccessTokenResult result = null; code = Request.QueryString["code"].ToString(); try { //通过,用code换取access_token var isSecondRequest = false; lock (OAuthCodeCollectionLock) { Log.Info(this.GetType().ToString(), "code:" + code.ToString()); isSecondRequest = OAuthCodeCollection.ContainsKey(code); } if (!isSecondRequest) { //第一次请求 Log.Info(this.GetType().ToString(), "第一次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = null; } } else { //第二次请求 Log.Info(this.GetType().ToString(), "第二次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } try { try { result = result ?? OAuthApi.GetAccessToken(WxPayConfig.GetConfig().GetAppID(), WxPayConfig.GetConfig().GetAppSecret(), code); } catch (Exception ex) { //return Content("OAuth AccessToken错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "OAuth AccessToken错误:" + ex.Message); } if (result != null) { lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = result; } } } catch (ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code) { //code已经被使用过 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } } openId = result != null ? result.openid : null; } catch (Exception ex) { //return Content("授权过程发生错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "\r\n授权过程发生错误:" + ex.Message); } ViewState["openid"] = result.openid; ViewState["accesstoken"] = result.access_token; OAuthUserInfo user = OAuthApi.GetUserInfo(result.access_token, result.openid); ViewState["faceurl"] = user.headimgurl.ToString(); ViewState["nickname"] = user.nickname.ToString(); Log.Info(this.GetType().ToString(), result.openid); //使用result继续操作 //检验是否openid已报名 string sql = "select * from action_join_people where people_openid = '" + result.openid + "'"; DataTable dt = DBUtility.DbHelperSQL.Query(sql).Tables[0]; if (dt != null && dt.Rows.Count > 0) { btnBaoming.Text = "已报名"; btnBaoming.Enabled = false; } } else { string pid = Request.QueryString["pid"].ToString(); string _str = "http://" + Request.Url.Host + "/mobile/baoming.aspx?pid=" + pid; string url = OAuthApi.GetAuthorizeUrl(WxPayConfig.GetConfig().GetAppID(), _str, "state", Senparc.Weixin.MP.OAuthScope.snsapi_userinfo); Response.Redirect(url); } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { OAuthAccessTokenResult result = null; if (!string.IsNullOrEmpty(Request.QueryString["code"])) { string openId = ""; code = Request.QueryString["code"].ToString(); try { //通过,用code换取access_token var isSecondRequest = false; lock (OAuthCodeCollectionLock) { isSecondRequest = OAuthCodeCollection.ContainsKey(code); } if (!isSecondRequest) { //第一次请求 lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = null; } } else { //第二次请求 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } try { var accessToken = AccessTokenContainer.GetAccessToken(ca._appId); try { result = result ?? OAuthApi.GetAccessToken(ca._appId, ca._appSecret, code); //txtComeDate.Text = result.errcode.ToString(); } catch (Exception ex) { //txtComeDate.Text = ex.ToString(); //return Content("OAuth AccessToken错误:" + ex.Message); } if (result != null) { lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = result; } openId = result != null ? result.openid : ""; hdfOpenID.Value = openId; } } catch (Senparc.Weixin.Exceptions.ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code) { //code已经被使用过 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } } } catch (Exception ex) { //return Content("授权过程发生错误:" + ex.Message); } } else { string _str = "http://" + Request.Url.Host + "/mobile/curriculum.aspx"; string url = OAuthApi.GetAuthorizeUrl(WxPayConfig.GetConfig().GetAppID(), _str, "state", Senparc.Weixin.MP.OAuthScope.snsapi_userinfo); Response.Redirect(url); } } }
public void SendWeText(string openid, string content) { CustomApi.SendText(WxPayConfig.GetConfig().GetAppID(), openid, content); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["code"])) { string openId; OAuthAccessTokenResult result = null; code = Request.QueryString["code"].ToString(); try { //通过,用code换取access_token var isSecondRequest = false; lock (OAuthCodeCollectionLock) { Log.Info(this.GetType().ToString(), "code:" + code.ToString()); isSecondRequest = OAuthCodeCollection.ContainsKey(code); } if (!isSecondRequest) { //第一次请求 Log.Info(this.GetType().ToString(), "第一次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = null; } } else { //第二次请求 Log.Info(this.GetType().ToString(), "第二次微信OAuth到达,code:" + code); lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } try { try { result = result ?? OAuthApi.GetAccessToken(WxPayConfig.GetConfig().GetAppID(), WxPayConfig.GetConfig().GetAppSecret(), code); } catch (Exception ex) { //return Content("OAuth AccessToken错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "OAuth AccessToken错误:" + ex.Message); } if (result != null) { lock (OAuthCodeCollectionLock) { OAuthCodeCollection[code] = result; } } } catch (ErrorJsonResultException ex) { if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code) { //code已经被使用过 lock (OAuthCodeCollectionLock) { result = OAuthCodeCollection[code]; } } } openId = result != null ? result.openid : null; } catch (Exception ex) { //return Content("授权过程发生错误:" + ex.Message); Log.Error(this.GetType().ToString(), ex.StackTrace.ToString() + "\r\n授权过程发生错误:" + ex.Message); } ViewState["openid"] = result.openid; ViewState["accesstoken"] = result.access_token; OAuthUserInfo user = OAuthApi.GetUserInfo(result.access_token, result.openid); ViewState["faceurl"] = user.headimgurl.ToString(); ViewState["nickname"] = user.nickname.ToString(); Log.Info(this.GetType().ToString(), result.openid); //使用result继续操作 //hfdOpenid.Value = result.openid; hfdCurrentOpenid.Value = result.openid; BindData(); } else { string id = Request.QueryString["id"].ToString(); string _str = "http://" + Request.Url.Host + "/mobile/comment_list.aspx?id=" + id; string url = OAuthApi.GetAuthorizeUrl(WxPayConfig.GetConfig().GetAppID(), _str, "state", Senparc.Weixin.MP.OAuthScope.snsapi_userinfo); Response.Redirect(url); } } }
/// <summary> /// 确认付款操作 /// </summary> /// <returns></returns> public ActionResult DoPay(int addressid, string paytype, string remark, bool isziti, string payPwd) { JsonHelp json = new JsonHelp(true); try { Xml_Site config = DB.XmlConfig.XmlSite; Xml_Shop shopConfig = DB.XmlConfig.XmlShop; Member_Info curUser = User_Shop.GetMember_Info(); //获取订单信息 string orderlist = CookieHelper.GetCookieValue("orderlist"); List <string> orderList = orderlist.JsonDeserializer <List <string> >(); if (orderList == null) { throw new Exception("订单支付异常"); } if (orderList.Count <= 0) { throw new Exception("获取订单信息失败"); } var orderid = orderList.First(); var query = DB.ShopOrder.Where(q => q.GUID == orderid).FirstOrDefault(); if (query.State != 1) { throw new Exception("订单不是待支付订单不可支付"); } DB.ShopOrder.UpdateOrderInfo(orderList, addressid, remark, isziti, paytype); if (paytype == "余额") { //计算处理 DB.ShopOrder.Calcute(curUser, orderList.First(), payPwd); CookieHelper.ClearCookie("orderlist"); } else if (paytype == "支付宝") { json.ReUrl = "/Member_Mall/Pay/Pay?OrderId=" + orderList.First();//http://tjyy.fabeisha.cn //r.ReUrl = "http://tjyy.fabeisha.cn/Member_Mall/Pay/Pay?BillId=" + r.BillId;//http://www.738600.cn } else if (paytype == "微信") { var orderModel = DB.ShopOrder.FindEntity(orderList.First()); H5Pay h5Pay = new H5Pay(); var wxConfig = WxPayConfig.GetConfig(); string clientIP = wxConfig.GetIp(); //获取客户端真实IP var url = h5Pay.GetPayUrl(clientIP, orderModel.OrderCode, (orderModel.RealAmount + orderModel.Postage.Value) * 100M); //通过统一下单接口进行H5支付 //Response.Redirect(url);//跳转到微信支付中间页 json.ReUrl = url; //json.ReUrl = "/Member_Mall/Pay/WXPay?OrderId=" + orderList.First();//http://tjyy.fabeisha.cn //r.ReUrl = "/Member_Mall/Pay/WXPay?BillId=" + r.BillId;//http://tjyy.fabeisha.cn } //3.清空cookie CookieHelper.ClearCookie("cart"); CookieHelper.ClearCookie("total"); CookieHelper.ClearCookie("traceno"); } catch (Exception ex) { StringBuilder str = new StringBuilder(); Exception inner = ex; while (inner != null) { str.AppendLine(inner.Message); inner = inner.InnerException; } json.IsSuccess = false; json.Msg = str.ToString(); str.AppendLine("跟踪:" + ex.StackTrace); LogHelper.Debug(str.ToString()); } return(Json(json)); }