c#版在pc端发起微信扫码支付的实例

2019-12-30 14:45:56于海丽

看我的调用例子:
asp.net,微信扫码支付,c#微信支付,微信支付demo
MakeQRCode.aspx页面照抄:


public partial class Pay_MakeQRCode : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
  if (!string.IsNullOrEmpty(base.Request.QueryString["data"]))
  {
   string str = base.Request.QueryString["data"];
   Bitmap image = new QRCodeEncoder
   {
    QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
    QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M,
    QRCodeVersion = 0,
    QRCodeScale = 4
   }.Encode(str, Encoding.Default);
   MemoryStream ms = new MemoryStream();
   image.Save(ms, ImageFormat.Png);
   base.Response.BinaryWrite(ms.GetBuffer());
   base.Response.End();
  }
 }
}

这个页面是用来生成二维码的,需要引入ThoughtWorks.QRCode.dll组件。

我使用模式二,回调页面是ResultNotifyPage.aspx,就是在配置信息那里填写的那个回调页面。


protected void Page_Load(object sender, EventArgs e)
 {
  ResultNotify resultNotify = new ResultNotify(this);
  WxPayData res = resultNotify.ProcessNotify2();
  if (res.GetValue("return_code") == "SUCCESS")
  {
   //查询微信订单信息
   string paySignKey = ConfigurationManager.AppSettings["paySignKey"].ToString();
   string mch_id = ConfigurationManager.AppSettings["mch_id"].ToString();
   string appId = ConfigurationManager.AppSettings["AppId"].ToString();

   QueryOrder queryorder = new QueryOrder();
   queryorder.appid = appId;
   queryorder.mch_id = mch_id;
   queryorder.transaction_id = res.GetValue("transaction_id").ToString();
   queryorder.out_trade_no = "";
   queryorder.nonce_str = TenpayUtil.getNoncestr();

   TenpayUtil tenpay = new TenpayUtil();
   OrderDetail orderdeatil = tenpay.getOrderDetail(queryorder, paySignKey);
   //写微信记录
   (new vinson()).WriteReturnWXDetail(orderdeatil);
   //写充值记录
   FilliedOnline(orderdeatil.out_trade_no);
  }


  Response.Write(res.ToXml());
  Response.End();
 }

 扫码支付成功后会异步到这个页面执行代码,我们自己的业务逻辑就要写在这里。使用微信官方的ProcessNotify()函数可不行,我们稍微修改下就好了。增加ProcessNotify2函数:
 


public WxPayData ProcessNotify2()
  {
   WxPayData notifyData = GetNotifyData();

   //检查支付结果中transaction_id是否存在
   if (!notifyData.IsSet("transaction_id"))
   {
    //若transaction_id不存在,则立即返回结果给微信支付后台
    WxPayData res = new WxPayData();
    res.SetValue("transaction_id", "");
    res.SetValue("return_code", "FAIL");
    res.SetValue("return_msg", "支付结果中微信订单号不存在");
    return res;
   }

   string transaction_id = notifyData.GetValue("transaction_id").ToString();

   //查询订单,判断订单真实性
   if (!QueryOrder(transaction_id))
   {
    //若订单查询失败,则立即返回结果给微信支付后台
    WxPayData res = new WxPayData();
    res.SetValue("transaction_id", transaction_id);
    res.SetValue("return_code", "FAIL");
    res.SetValue("return_msg", "订单查询失败");
    return res;
   }
   //查询订单成功
   else
   {
    WxPayData res = new WxPayData();
    res.SetValue("transaction_id", transaction_id);
    res.SetValue("return_code", "SUCCESS");
    res.SetValue("return_msg", "OK");
    return res;
   }
  }