微信支付,服务端代码

//1.移动端下订单
//2.调用此服务,参数为订单Id,此该服务会返回预付单Id和签名,以用移动端调取微信支付SDK
//3.异步通知页面,异步通知页面根据状态,做相应操作,改变支付状态
//该方法,返回预支付单Id,和签名,用于移动端调取微信支付sdk

 //  <a target=_blank target="_blank" href="http://download.csdn.net/detail/modun_n/9332917">助手类</a> 
public  ResponseRaw<WxPrePayDto>  WxPay(int orderinfoId) 
{   
 try
            {
                //获取微信支付配置信息
                var payOnlineConfigure= locator.QueryOver<PayOnlineConfigure>().Where(a => a.PayType == 2).SingleOrDefault();
                //1.检验数据库中的订单信息
                var orderInfoNumer = locator.QueryOver<OrderInfo>().Where(a => a.Id== orderInfoId).SingleOrDefault();
                WxPayHelper wxhelper = new WxPayHelper();
                if (orderInfoNumer != null&&payOnlineConfigure!=null)
                {
                    wxhelper.SetParameter("appid",payOnlineConfigure.Partner);//公众账号Id
                    wxhelper.SetParameter("mch_id",payOnlineConfigure.Seller);//商户号id
                    wxhelper.SetParameter("notify_url",payOnlineConfigure.NotifyUrl);//异步通知的URL
                    wxhelper.SetAppSecret(payOnlineConfigure.RsaPublic);//密匙
                    wxhelper.SetPartnerKey(payOnlineConfigure.RsaPrivate);//应用Key
                    wxhelper.SetParameter("nonce_str", WxPayData.getNoncestr());//随机字符 
                    wxhelper.SetParameter("body",orderInfoNumer.Product.Remark);//商品描述
                    wxhelper.SetParameter("out_trade_no", orderInfoNumer.Number);//商家订单号
                    wxhelper.SetParameter("total_fee", Convert.ToInt32(orderInfoNumer.Total * 100).ToString());//商品金额,以分为单位,不能带小数点(money * 100).ToString()
                    wxhelper.SetParameter("trade_type", "APP");
                    wxhelper.SetParameter("spbill_create_ip", "123.12.12.123");订单生成的机器IP
                    //2.获取交易预支付id
                    string prepayId = wxhelper.GetPrepayId();
                    if (!string.IsNullOrEmpty(prepayId))
                    {
                        wxhelper.SetReturnParameter("return_code", "SUCCESS");//状态码
                        wxhelper.SetReturnParameter("result_code", "SUCCESS");//业务结果
                        wxhelper.SetReturnParameter("prepay_id", prepayId);//预支付订单id
                        string wxSign = wxhelper.GetSign(wxhelper.GetParameter());//获得签名
                        //3.将微信预付单信息添加到数据库中
                         ...........................
                    }
                    else
                    {
                        wxhelper.SetReturnParameter("return_code", "SUCCESS");//返回状态码
                        wxhelper.SetReturnParameter("result_code", "FAIL");//业务结果,处理失败
                        wxhelper.SetReturnParameter("err_code_des", "预订单生产失败");//错误代码描述
                        return "错误信息";
                    }
                }
                else
                {
                    //下单失败
                    var exceptionResult = new ResponseRaw<WxPrePayDto>();
                    exceptionResult.Response.AddBusinessException(
                        new BusinessException(BusinessExceptionEnum.Default, "下单失败!"));
                    return exceptionResult;
                }

            }
            catch (Exception ex)
            {

                throw new BusinessException(BusinessExceptionEnum.Default, ex.Message);
            }
}


///异步通知页面 
//其中回去验证签名是有一致
       protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary<string, string> sPara = GetRequestPost();
            WxPayResponseHandler resHandler = new WxPayResponseHandler(Context);
            //判断签名
            try
            {
                string error = "";
                if (resHandler.IsWXsign(out error))
                {
                    #region 协议参数=====================================
                    //--------------协议参数--------------------------------------------------------
                    //SUCCESS/FAIL此字段是通信标识,非交易标识,交易是否成功需要查
                    string returnCode = resHandler.getParameter("return_code");
                    //返回信息,如非空,为错误原因签名失败参数格式校验错误
                    string returnMsg = resHandler.getParameter("return_msg");
                    //微信分配的公众账号 ID
                    string appid = resHandler.getParameter("appid");
                    //以下字段在 return_code 为 SUCCESS 的时候有返回--------------------------------
                    //微信支付分配的商户号
                    string mchId = resHandler.getParameter("mch_id");
                    //微信支付分配的终端设备号
                    string deviceInfo = resHandler.getParameter("device_info");
                    string nonceStr = resHandler.getParameter("nonce_str");
                    //业务结果 SUCCESS/FAIL
                    string resultCode = resHandler.getParameter("result_code");
                    //错误代码 
                    string errCode = resHandler.getParameter("err_code");
                    //结果信息描述
                    string errCodeDes = resHandler.getParameter("err_code_des");

                    //以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回---------------
                    //-------------业务参数---------------------------------------------------------
                    //用户在商户 appid 下的唯一标识
                    string openId = resHandler.getParameter("openid");
                    //用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
                    string isSubscribe = resHandler.getParameter("is_subscribe");
                    //JSAPI、NATIVE、MICROPAY、APP
                    string tradeType = resHandler.getParameter("trade_type");
                    //银行类型,采用字符串类型的银行标识
                    string bankType = resHandler.getParameter("bank_type");
                    //订单总金额,单位为分
                    decimal totalFee =Decimal.Parse((Convert.ToInt32(resHandler.getParameter("total_fee"))*0.01).ToString());
                    //货币类型,符合 ISO 4217 标准的三位字母代码,默认人民币:CNY
                    string feeType = resHandler.getParameter("fee_type");
                    //微信支付订单号
                    string transactionId = resHandler.getParameter("transaction_id");
                    //商户系统的订单号,与请求一致。
                    string outTradeNo = resHandler.getParameter("out_trade_no");
                    //商家数据包,原样返回
                    string attach = resHandler.getParameter("attach");
                    //支 付 完 成 时 间 , 格 式 为yyyyMMddhhmmss,如 2009 年12 月27日 9点 10分 10 秒表示为 20091227091010。时区为 GMT+8 beijing。该时间取自微信支付服务器
                    string timeEnd = resHandler.getParameter("time_end");

                    #endregion
                    //支付成功
                    if (!outTradeNo.Equals("") && returnCode.Equals("SUCCESS") && resultCode.Equals("SUCCESS"))
                    {
                        //验证订单是否存在
                        var orderInfo = GetOrderInfo(outTradeNo);
                        if (orderInfo != null)
                        {
                            //判断请求的total_fee、seller_id 与通知时获取的total_fee、seller_id为一致的,并且判断此记录没有被处理过
                            if (orderInfo.Total == totalFee&& orderInfo.Effect == false)
                            {
                                //修改订单中的支付信息,并计算有效期
                                orderInfo.PaymentOrder = outTradeNo;
                                orderInfo.PayStatus = 3;  //交易成功,且可操作
                                orderInfo.Status = 4;  //已下单
                                //Core.LogResult(" TRADE_SUCCESS :商户订单号:" + out_trade_no + ";支付宝交易号:" + trade_no + " ;交易状态:" + trade_status + " ;接受时间:" + notifyTime);
                                UpdatePayInfo(orderInfo);
                                Response.Write("success");

                            }
                        }
                        else
                        {
                         //订单不存在
                            Response.Write("fail");
                            return;
                        }
  
                    }
                }
                else
                {
                   // LogUtil.WriteLog("Notify 页面  isWXsign= false ,错误信息:" + error);
                }


            }
            catch (Exception ee)
            {
               
            }

            Response.End();

        } 
、、、、、、、、、、、、、、、
             /** 
    '============================================================================
    'api说明:
    'getKey()/setKey(),获取/设置密钥
    'getParameter()/setParameter(),获取/设置参数值
    'getAllParameters(),获取所有参数
    'isTenpaySign(),是否正确的签名,true:是 false:否
    'isWXsign(),是否正确的签名,true:是 false:否
    ' * isWXsignfeedback判断微信维权签名
    ' *getDebugInfo(),获取debug信息
    '============================================================================
    */
    public class WxPayResponseHandler
    {
        // 参与签名的参数列表
        private static string SignField = "appid,appkey,timestamp,openid,noncestr,issubscribe";
        // 微信服务器编码方式
        private string charset = "gb2312";
        //参与签名的参数列表
        protected HttpContext httpContext;
        //protected Hashtable parameters;
        private Hashtable xmlMap;
        private string key = ConfigurationManager.AppSettings.Get("WxKey");//商户支付key,后台设置的API密钥
        //获取页面提交的get和post参数
        public WxPayResponseHandler(HttpContext httpContext)
        {
            //parameters = new Hashtable();
            xmlMap = new Hashtable();

            this.httpContext = httpContext;
            if (this.httpContext.Request.InputStream.Length > 0)
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(this.httpContext.Request.InputStream);
                XmlNode root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    xmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
        }

        #region 参数=======================================
        /// <summary>
        /// 初始化加载
        /// </summary>
        public virtual void init()
        {
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <returns></returns>
        public string getKey()
        {
            return key;
        }

        /// <summary>
        /// 设置密钥
        /// </summary>
        /// <param name="key"></param>
        public void setKey(string key)
        {
            this.key = key;
        }

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public string getParameter(string parameter)
        {
            var s = (string)xmlMap[parameter];
            return (null == s) ? "" : s;
        }

        /// <summary>
        /// 设置参数值
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="parameterValue"></param>
        public void setParameter(string parameter, string parameterValue)
        {
            //if (parameter != null && parameter != "")
            //{
            //    if (parameters.Contains(parameter))
            //    {
            //        parameters.Remove(parameter);
            //    }

            //    parameters.Add(parameter, parameterValue);
            //}
        }
        #endregion

        #region 辅助方法===================================
        /// <summary>
        /// 判断微信签名
        /// </summary>
        /// <returns></returns>
        public virtual bool IsWXsign(out string error)
        {
            StringBuilder sb = new StringBuilder();
            Hashtable signMap = new Hashtable();
            foreach (string k in xmlMap.Keys)
            {
                if (k != "sign")
                {
                    signMap.Add(k.ToLower(), xmlMap[k]);
                }
            }
            ArrayList akeys = new ArrayList(signMap.Keys);
            akeys.Sort();

            foreach (string k in akeys)
            {
                string v = (string)signMap[k];
                sb.Append(k + "=" + v + "&");
            }
            sb.Append("key=" + this.key);
            string sign =GetMD5(sb.ToString(), charset).ToString().ToUpper();
            error = "sign = " + sign + "\r\n xmlMap[sign]=" + xmlMap["sign"].ToString();
            return sign.Equals(xmlMap["sign"]);

        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="encypStr">加密字符串</param>
        /// <param name="charset">编码方式</param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, string charset)
        {
            string retStr="";
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组.
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);
            for (int i = 0; i < outputBye.Length; i++)
            {
                retStr += outputBye[i].ToString("x").PadLeft(2, '0');
            }
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }
  

        /// <summary>
        /// 获取编码方式
        /// </summary>
        /// <returns></returns>
        protected virtual string GetCharset()
        {
            return httpContext.Request.ContentEncoding.BodyName;
        }
        #endregion
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用微信支付服务的示例代码: 1. 引入SDK ```java // 引入微信支付SDK import com.github.wxpay.sdk.WXPay; import com.github.wxpay.sdk.WXPayConstants; import com.github.wxpay.sdk.WXPayUtil; import java.util.HashMap; import java.util.Map; ``` 2. 初始化配置 ```java // 配置微信支付参数 Map<String, String> config = new HashMap<>(); config.put("appid", "微信开放平台审核通过的应用APPID"); config.put("mch_id", "商户号"); config.put("key", "API密钥"); config.put("notify_url", "支付结果通知的回调地址"); config.put("trade_type", "APP"); WXPay wxPay = new WXPay(config, WXPayConstants.SignType.MD5); ``` 3. 统一下单 ```java // 统一下单 Map<String, String> data = new HashMap<>(); data.put("body", "商品描述"); data.put("out_trade_no", "商户订单号"); data.put("total_fee", "支付金额"); data.put("spbill_create_ip", "用户IP地址"); Map<String, String> resp = wxPay.unifiedOrder(data); ``` 4. 处理支付结果 ```java // 处理支付结果 if ("SUCCESS".equals(resp.get("return_code")) && "SUCCESS".equals(resp.get("result_code"))) { // 获取预支付交易会话标识 String prepayId = resp.get("prepay_id"); // 签名参数 Map<String, String> signData = new HashMap<>(); signData.put("appid", config.get("appid")); signData.put("partnerid", config.get("mch_id")); signData.put("prepayid", prepayId); signData.put("package", "Sign=WXPay"); signData.put("noncestr", WXPayUtil.generateNonceStr()); signData.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000)); // 生成签名 String sign = WXPayUtil.generateSignature(signData, config.get("key")); // 返回APP端需要的参数 Map<String, String> payParams = new HashMap<>(); payParams.put("appid", config.get("appid")); payParams.put("partnerid", config.get("mch_id")); payParams.put("prepayid", prepayId); payParams.put("package", "Sign=WXPay"); payParams.put("noncestr", signData.get("noncestr")); payParams.put("timestamp", signData.get("timestamp")); payParams.put("sign", sign); } else { // 支付失败 String errorCode = resp.get("err_code"); String errorMsg = resp.get("err_code_des"); } ``` 以上就是使用微信支付服务的示例代码,你可以根据自己的具体需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值