标签:
前段时间做了网页版微信支付,遇到很多问题,不过最终还是解决了,现在在这里记录下开发流程以及说明,给其他人一些参考。
一、准备工作
//判断是否网页授权,获取授权code,没有代表没有授权,构造网页授权获取code,并重新请求 if (string.IsNullOrEmpty(Request.QueryString["code"])) { string redirectUrl = _weChatPaySerivce.GetAuthorizeUrl(account.AppId, account.RedquestUrl, "STATE" + "#wechat_redirect", "snsapi_base"); return Redirect(redirectUrl); }
public string GetAuthorizeUrl(string appId, string redirectUrl, string state, string scope) { string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}", appId, HttpUtility.UrlEncode(redirectUrl), scope, state); /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。 * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用) * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE */ AppLog.Write("获取到授权url:", AppLog.LogMessageType.Debug); return url; }
public Tuple<string, string> GetOpenidAndAccessTokenFromCode(string appId, string code, string appSecret) { Tuple<string, string> tuple = null; try { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, appSecret, code); string result = WeChatPayHelper.Get(url); AppLog.Write("微信支付-获取openid和access_token 请求Url:" + url + "result:" + result, AppLog.LogMessageType.Debug); if (!string.IsNullOrEmpty(result)) { var jd=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(result); tuple = new Tuple<string, string>(jd["openid"],jd["access_token"]); AppLog.Write("微信支付-获取openid和access_token成功", AppLog.LogMessageType.Debug); } } catch (Exception ex) { AppLog.Write("微信支付:获取openid和access_tokenu异常", AppLog.LogMessageType.Debug,ex); } return tuple; }
//创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); //时间戳 string timeStamp = TenPayUtil.GetTimestamp(); //随机字符串 string nonceStr = TenPayUtil.GetNoncestr(); //设置package订单参数 生成prepayId预支付Id packageReqHandler.SetParameter("appid", account.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", account.PartnertId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", account.Body); packageReqHandler.SetParameter("out_trade_no", account.OrderSerialId); //商家订单号 packageReqHandler.SetParameter("total_fee", account.TotalAmount); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", account.RequestIp); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", account.NotifyUrl); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易类型 packageReqHandler.SetParameter("openid", account.OpenId); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", account.PaySignKey); packageReqHandler.SetParameter("sign", sign); //签名 string prepayId = string.Empty; try { string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); MailHelp.SendMail("调用统一下单接口,下单结果:--"+result+"请求参数:"+data); var res = XDocument.Parse(result); prepayId = res.Element("xml").Element("prepay_id").Value; AppLog.Write("调用统一下单接口获取预支付prepayId成功", AppLog.LogMessageType.Debug); } catch (Exception ex) { AppLog.Write("获取到openid和access_tokenu异常", AppLog.LogMessageType.Debug, ex); MailHelp.SendMail("调用统一下单接口获取预支付prepayid异常:", ex); return null; }
//生成JsAPI支付参数 RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", account.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); string paySign = paySignReqHandler.CreateMd5Sign("key", account.PaySignKey); WeChatJsPayRequestModel resultModel = new WeChatJsPayRequestModel { AppId = account.AppId, NonceStr = nonceStr, TimeStamp = timeStamp, Package = string.Format("prepay_id={0}", prepayId), PaySign = paySign, SignType = "MD5" };
private string CreateWeixinJs(WeChatJsPayRequestModel model) { string js = @"<script type=‘text/javascript‘> callpay(); function jsApiCall(){ WeixinJSBridge.invoke( ‘getBrandWCPayRequest‘, { requestParam }, function (res) { if(res.err_msg == ‘get_brand_wcpay_request:ok‘ ){ window.location.href = ‘successUrl‘; }else{ window.location.href = ‘failUrl‘; } } ); } function callpay() { if (typeof WeixinJSBridge == ‘undefined‘){ if( document.addEventListener ){ document.addEventListener(‘WeixinJSBridgeReady‘, jsApiCall, false); }else if (document.attachEvent){ document.attachEvent(‘WeixinJSBridgeReady‘, jsApiCall); document.attachEvent(‘onWeixinJSBridgeReady‘, jsApiCall); } }else{ jsApiCall(); } } </script>"; string requestParam = string.Format(@"‘appId‘: ‘{0}‘,‘timeStamp‘: ‘{1}‘,‘nonceStr‘: ‘{2}‘,‘package‘: ‘{3}‘,‘signType‘: ‘{4}‘,‘paySign‘: ‘{5}‘", model.AppId, model.TimeStamp, model.NonceStr, model.Package, model.SignType, model.PaySign); js = js.Replace("requestParam", requestParam) .Replace("successUrl", model.JumpUrl + "&result=1") .Replace("failUrl", model.JumpUrl + "&result=0"); AppLog.Write("生成可执行脚本成功", AppLog.LogMessageType.Debug); return js; }
ResponseHandler resHandler = new ResponseHandler(System.Web.HttpContext.Current); bool isSuccess = _weChatPaySerivce.ProcessNotify(resHandler); if (isSuccess) { string result = @"<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[支付成功]]></return_msg> </xml>"; HttpContext.Response.Write(result); HttpContext.Response.End(); } return new EmptyResult();
标签:
原文地址:http://www.cnblogs.com/minesnil-forfaith/p/4976006.html