欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net接入支付宝的支付接口

程序员文章站 2023-11-22 10:43:10
h5手机网站接入支付宝的支付接口,推荐使用支付宝提供的sdk来快速开发 我使用的是sdk开发 引用命名空间 using aop.api; using aop...

h5手机网站接入支付宝的支付接口,推荐使用支付宝提供的sdk来快速开发

我使用的是sdk开发

引用命名空间

using aop.api;
using aop.api.request;
using aop.api.response;
using aop.api.util;

首页需要定义一些常量

 static string serverurl = "https://openapi.alipaydev.com/gateway.do";
    static string app_id = "**";  //开发者的应用id
    static string format = "json";
    static string charset = "utf-8";
    static string sign_type = "rsa2"; //签名格式
    static string version = "1.0";
    string uid = "2088102169707816";//卖家支付宝账户号
    //商户私钥
    static string merchant_private_key = "***";
    //支付宝公钥
    static string alipay_public_key = "***";

这里的app_id,merchant_private_key,alipay_public_key 我就没有列出来了,获取的方法需要自己去支付宝平台完成一些操作进行获取

在用户点击网站付款时,我们需要唤醒支付宝,来进行支付

public string h5requestpayway(orderpo order)
    {
      iaopclient client = new defaultaopclient(serverurl, app_id, merchant_private_key, format, version, sign_type, alipay_public_key, charset, false);
      alipaytradewappayrequest request = new alipaytradewappayrequest();
      string address= "http://m." + pathlogic1.rootdomain;
      request.setreturnurl(address+ "/webpay/alipaypayresult");//同步请求
      request.setnotifyurl(address + "/webpay/asyncpay");//异步请求
      var lstdetail = context.data.orderdetail.where(x => x.orderno == order.orderno).toselectlist(x=>new { x.skuname});
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < lstdetail.count(); i++)
      {
        sb.append(lstdetail[i].skuname + ",");
      }
      request.bizcontent = "{" +
  "\"body\":\""+sb.tostring().substring(0,sb.length-1)+"\"," +
  "\"subject\":\"袋鼠巴巴商品支付\"," +
  "\"out_trade_no\":\""+order.orderno+"\"," +
  "\"timeout_express\":\"90m\"," +
  "\"total_amount\":"+(order.totalamount.value+order.totalfreight.value)+"," +
  "\"product_code\":\"quick_wap_pay\"" +
  " }";

      alipaytradewappayresponse response = client.pageexecute(request);
       return response.body;
    }

具体发送给支付宝的参数,自行去查看

执行方法后,买家输入自己的支付宝账号密码进行支付,支付成功的结果,支付宝会以post的方式异步请求你的setnotifyurl的地址

这个setnotifyurl的地址必须要外网可以访问,支付宝的请求才能进来

买家支付成功,商家修改订单状态和数据库的操作,都在异步请求中执行

同步请求

public actionresult alipaypayresult()
    {
      viewbag.result = "success";
      return view("payresult");
    }

     /// <summary>
    /// 验证通知数据的正确性
    /// </summary>
    /// <param name="out_trade_no"></param>
    /// <param name="total_amount"></param>
    /// <param name="seller_id"></param>
    /// <returns></returns> 
private sorteddictionary<string, string> getrequestpost()
    {
      int i = 0;
      sorteddictionary<string, string> sarray = new sorteddictionary<string, string>();
      namevaluecollection coll;
      //load form variables into namevaluecollection variable.
      coll = request.form;

      // get names of all forms into a string array.
      string[] requestitem = coll.allkeys;

      for (i = 0; i < requestitem.length; i++)
      {
        sarray.add(requestitem[i], request.form[requestitem[i]]);
      }

      return sarray;
    }
 /// <summary>
    /// 验签
    /// </summary>
    /// <param name="inputpara"></param>
    /// <returns></returns>
    public boolean verify(sorteddictionary<string, string> inputpara)
    {
      dictionary<string, string> spara = new dictionary<string, string>();    
      boolean verifyresult = alipaysignature.rsacheckv1(inputpara, alipay_public_key, charset,sign_type,false);
      return verifyresult;
    }

异步请求:

 [httppost]
    public void asyncpay()
    {
      sorteddictionary<string, string> spara = getrequestpost();//将post请求过来的参数传化为sorteddictionary
      if (spara.count > 0)
      {
        alipaytradewaypayserver pay = new alipaytradewaypayserver();
        boolean verifyresult = pay.verify(spara);//验签if (verifyresult)
        {
          try
          {
             //商户订单号
            string out_trade_no = request.form["out_trade_no"];
            //支付宝交易号
            string trade_no = request.form["trade_no"];
            //支付金额
            decimal total_amount = request.form["total_amount"].converttype(decimal.zero);
            //实收金额
            //decimal receipt_amount = request.form["receipt_amount"].converttype(decimal.zero);
            //交易状态
            string trade_status = request.form["trade_status"];
            //卖家支付宝账号
            string seller_id = request.form["seller_id"];

            //商品描述
            string body = request.form["body"];
            //交易创建时间
            datetime gmt_create = datetime.parse(request.form["gmt_create"]);
            //交易付款时间
            datetime gmt_payment = datetime.parse(request.form["gmt_payment"]);
            string appid = request.form["app_id"];
            writeerror("验证参数开始");
            boolean datavalidity = pay.checkinform(out_trade_no, total_amount, seller_id, appid);//商家判断参数时候是否匹配if (datavalidity)
            {
              if (request.form["trade_status"] == "trade_finished")
              {
                alipaywaypaypo model = createalipaywaypay(out_trade_no, trade_no, trade_status, gmt_create, gmt_payment);
                pay.paysuccess(out_trade_no, model, server.mappath("~/" + datetime.today.tostring("yymmdd") + ".txt"));//修改订单
                //注意:
                //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
              }
              else if (request.form["trade_status"] == "trade_success")
              {
                alipaywaypaypo model = createalipaywaypay(out_trade_no, trade_no, trade_status, gmt_create, gmt_payment);
                pay.paysuccess(out_trade_no, model, server.mappath("~/" + datetime.today.tostring("yymmdd") + ".txt"));//修改订单
                //注意:
                //付款完成后,支付宝系统发送该交易状态通知
              }
              else
              {

              }

              //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

              response.write("success"); //请不要修改或删除

              /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
          }
          catch (exception ex)
          {
            
          }
        }
        else//验证失败
        {
          response.write("fail");
        }
      }
      else
      {
        response.write("无通知参数");
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。