服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#支付宝扫码支付代码完整版

C#支付宝扫码支付代码完整版

2022-02-24 14:03牟鹏 C#

这篇文章主要为大家详细介绍了C#支付宝扫码支付代码的完整版本,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C#支付宝扫码支付示的具体代码,供大家参考,具体内容如下

支付宝工具类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
 
namespace ZK_ECommerce.Shop.pay.alipay
{
  public class AliPay
  {
 
    public static string GetMD5(string s, string _input_charset)
    {
 
      /// <summary>
      /// 与ASP兼容的MD5加密算法
      /// </summary>
 
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
      StringBuilder sb = new StringBuilder(32);
      for (int i = 0; i < t.Length; i++)
      {
        sb.Append(t[i].ToString("x").PadLeft(2, '0'));
      }
      return sb.ToString();
    }
 
    public static string[] BubbleSort(string[] r)
    {
      /// <summary>
      /// 冒泡排序法
      /// </summary>
 
      int i, j; //交换标志 
      string temp;
 
      bool exchange;
 
      for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
      {
        exchange = false; //本趟排序开始前,交换标志应为假
 
        for (j = r.Length - 2; j >= i; j--)
        {
          if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0) //交换条件
          {
            temp = r[j + 1];
            r[j + 1] = r[j];
            r[j] = temp;
 
            exchange = true; //发生了交换,故将交换标志置为真 
          }
        }
 
        if (!exchange) //本趟排序未发生交换,提前终止算法 
        {
          break;
        }
 
      }
      return r;
    }
 
    public string CreatUrl(
      string gateway,
      string service,
      string partner,
      string sign_type,
      string out_trade_no,
      string subject,
      string body,
      string payment_type,
      string total_fee,
      string show_url,
      string seller_email,
      string key,
      string return_url,
      string _input_charset,
      string notify_url,
      string extra_common_param = ""
      )
    {
      return CreatUrl(
      gateway,
      service,
      partner,
      sign_type,
      out_trade_no,
      subject,
      body,
      payment_type,
      total_fee,
      show_url,
      seller_email,
      key,
      return_url,
      _input_charset,
      notify_url,
      "",
      extra_common_param);
    }
 
 
 
    public string CreatUrl(
      string gateway,
      string service,
      string partner,
      string sign_type,
      string out_trade_no,
      string subject,
      string body,
      string payment_type,
      string total_fee,
      string show_url,
      string seller_email,
      string key,
      string return_url,
      string _input_charset,
      string notify_url,
      string token,
      string extra_common_param = ""
      )
    {
      /// <summary>
      ///2015年11月17日14:08:00
      /// </summary>
      int i;
      string[] Oristr;
      //构造数组;
      if (!string.IsNullOrEmpty(token))
      {
        if (extra_common_param == "COD2MOTOPAY")
        {
          Oristr = new[]{ 
          "service="+service, 
          "partner=" + partner, 
          "subject=" + subject, 
          "body=" + body, 
          "out_trade_no=" + out_trade_no, 
          "total_fee=" + total_fee, 
          "show_url=" + show_url, 
          "payment_type=" + payment_type, 
          "seller_email=" + seller_email, 
          "notify_url=" + notify_url,
          "_input_charset="+_input_charset,     
          "return_url=" + return_url,
          "token="+token,
          "extra_common_param="+extra_common_param
          };
        }
        else
        {
          Oristr = new[]{ 
          "service="+service, 
          "partner=" + partner, 
          "subject=" + subject, 
          "body=" + body, 
          "out_trade_no=" + out_trade_no, 
          "total_fee=" +total_fee, 
          "show_url=" + show_url, 
          "payment_type=" + payment_type, 
          "seller_email=" + seller_email, 
          "notify_url=" + notify_url,
          "_input_charset="+_input_charset,     
          "return_url=" + return_url,
          "token="+token
          };
        }
 
      }
      else
      {
        if (extra_common_param == "COD2MOTOPAY")
        {
          Oristr = new[]{ 
          "service="+service, 
          "partner=" + partner, 
          "subject=" + subject, 
          "body=" + body, 
          "out_trade_no=" + out_trade_no, 
          "total_fee="+total_fee, 
          "show_url=" + show_url, 
          "payment_type=" + payment_type, 
          "seller_email=" + seller_email, 
          "notify_url=" + notify_url,
          "_input_charset="+_input_charset,     
          "return_url=" + return_url,
          "extra_common_param="+extra_common_param
          };
        }
        else
        {
          Oristr = new[]{ 
          "service="+service, 
          "partner=" + partner, 
          "subject=" + subject, 
          "body=" + body, 
          "out_trade_no=" + out_trade_no, 
          "total_fee=" + total_fee, 
          "show_url=" + show_url, 
          "payment_type=" + payment_type, 
          "seller_email=" + seller_email, 
          "notify_url=" + notify_url,
          "_input_charset="+_input_charset,     
          "return_url=" + return_url
          };
        }
 
 
      }
      //进行排序;
      string[] Sortedstr = BubbleSort(Oristr);
 
 
      //构造待md5摘要字符串 ;
 
      StringBuilder prestr = new StringBuilder();
 
      for (i = 0; i < Sortedstr.Length; i++)
      {
        if (i == Sortedstr.Length - 1)
        {
          prestr.Append(Sortedstr[i]);
 
        }
        else
        {
 
          prestr.Append(Sortedstr[i] + "&");
        }
 
      }
 
      prestr.Append(key);
 
      //生成Md5摘要;
      string sign = GetMD5(prestr.ToString(), _input_charset);
 
      //构造支付Url;
      char[] delimiterChars = { '=' };
      StringBuilder parameter = new StringBuilder();
      parameter.Append(gateway);
      for (i = 0; i < Sortedstr.Length; i++)
      {
 
        parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
      }
 
      parameter.Append("sign=" + sign + "&sign_type=" + sign_type);
 
 
      //返回支付Url;
      return parameter.ToString();
 
    }
 
    public string CreatUrl_MissPayments(
                string gateway,
                string service,
                string partner,
                string sign_type,
                string out_trade_no,
                string key,
                string _input_charset
 
     )
    {
      /// <summary>
      /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
      /// </summary>
      int i;
 
      //构造数组;
      string[] Oristr ={ 
        "service="+service, 
        "partner=" + partner,
        "out_trade_no=" + out_trade_no,   
        "_input_charset="+_input_charset     
 
        };
 
      //进行排序;
      string[] Sortedstr = BubbleSort(Oristr);
 
 
      //构造待md5摘要字符串 ;
 
      StringBuilder prestr = new StringBuilder();
 
      for (i = 0; i < Sortedstr.Length; i++)
      {
        if (i == Sortedstr.Length - 1)
        {
          prestr.Append(Sortedstr[i]);
 
        }
        else
        {
 
          prestr.Append(Sortedstr[i] + "&");
        }
 
      }
 
      prestr.Append(key);
 
      //生成Md5摘要;
      string sign = GetMD5(prestr.ToString(), _input_charset);
 
      //构造支付Url;
      char[] delimiterChars = { '=' };
      StringBuilder parameter = new StringBuilder();
      parameter.Append(gateway);
      for (i = 0; i < Sortedstr.Length; i++)
      {
 
        parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
      }
 
      parameter.Append("sign=" + sign + "&sign_type=" + sign_type);
 
 
      //返回支付Url;
      return parameter.ToString();
 
    }
 
 
    public static string GetTranSign(string TranData)
    {
      if (string.IsNullOrWhiteSpace(TranData))
        return null;
      string sign = GetMD5(TranData + "alskdjfaow;fjel;asdjf", "utf-8");
      return sign;
    }
 
  }
}

页面处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZK_ECommerce.Shop.pay.alipay;
 
namespace Alipay.Controllers
{
  public class ApliayDemoController : Controller
  {
    /// <summary>
    /// 支付页面
    /// </summary>
    /// <param name="ordercode"></param>
    /// <returns></returns>
    public ActionResult Index(string ordercode)
    {
 
 
      string out_trade_no = ordercode;
      string gateway = "https://mapi.alipay.com/gateway.do?"; //支付接口
      string service = "create_direct_pay_by_user";
      string partner = "";    //partner合作伙伴ID保留字段
      string sign_type = "MD5";
      string payment_type = "1";         //支付类型 
      string show_url = "http://www.letao.com";
      string seller_email = "";       //卖家账号
      string key = "";       //partner账户的支付宝安全校验码
      string return_url = "http://localhost:1396/ApliayDemo/ApliyReturn"; //服务器通知返回接口
      string notify_url = "http://localhost:1396/ApliayDemo/AlipayNotify"; //服务器通知返回接口
      string _input_charset = "utf-8";
      string extra_common_param = "COD2MOTOPAY";//表示快捷支付 
      string token = string.Empty;
      if (string.IsNullOrEmpty(token))
        token = "";
      string subject = "康康体检套餐"; // subject商品名称
      string body = "测试商品"; //商品描述  
      string total_fee = "0.01";
      AliPay ap = new AliPay();
      string aliay_url = ap.CreatUrl(gateway, service, partner, sign_type, out_trade_no, subject, body, payment_type,
                      total_fee, show_url, seller_email, key, return_url, _input_charset, notify_url, token, extra_common_param);
 
      return Redirect(aliay_url);
 
 
    }
 
 
    /// <summary>
    /// 返回通知页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ApliyReturn()
    {
 
      string alipayNotifyURL = "https://mapi.alipay.com/gateway.do?";
      string key = ""; //partner 的对应交易安全校验码(必须填写)
      string _input_charset = "utf-8";
      string partner = "";    //partner合作伙伴id(必须填写)
 
      alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "¬ify_id=" + Request.QueryString["notify_id"];
 
      //获取支付宝ATN返回结果,true是正确的订单信息,false 是无效的
      string responseTxt = Get_Http(alipayNotifyURL, 120000);
 
      int i;
      NameValueCollection coll;
      coll = Request.QueryString;
      String[] requestarr = coll.AllKeys;
      //进行排序;
      string[] Sortedstr = BubbleSort(requestarr);
 
      //构造待md5摘要字符串 ;
 
      StringBuilder prestr = new StringBuilder();
 
      for (i = 0; i < Sortedstr.Length; i++)
      {
        if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
        {
          if (i == Sortedstr.Length - 1)
          {
            prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]]);
          }
          else
          {
            prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]] + "&");
 
          }
        }
 
 
      }
 
      prestr.Append(key);
      string mysign = GetMD5(prestr.ToString(), _input_charset);
      string sign = Request.QueryString["sign"];
      string trade_status = Request.QueryString["trade_status"];
 
      if (mysign == sign && responseTxt == "true" && trade_status == "TRADE_SUCCESS"//验证支付发过来的消息,签名是否正确
      {
        string order_amount = Request.QueryString["total_fee"].ToString().Trim();
        string order_code = Request.QueryString["out_trade_no"].ToString().Trim();
 
        
        //updateOrder(order_code);//更新订单状态
        Response.Redirect(""); //跳转到支付成功页面
      }
      else
      {
 
        Response.Write("支付失败。");
        Response.Write("<br>Result:responseTxt=" + responseTxt);
        Response.Write("<br>Result:mysign=" + mysign);
        Response.Write("<br>Result:sign=" + sign);
      }
      return View();
    }
 
 
    /// <summary>
    /// 支付回调页面
    /// </summary>
    /// <returns></returns>
    public ActionResult AlipayNotify()
    {
 
 
      string alipayNotifyURL = "https://mapi.alipay.com/gateway.do?";
      string partner = "";    //partner合作伙伴id(必须填写)
      string key = ""; //partner 的对应交易安全校验码(必须填写)
 
      alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "¬ify_id=" + Request.Form["notify_id"];
 
      //获取支付宝ATN返回结果,true是正确的订单信息,false 是无效的
      string responseTxt = Get_Http(alipayNotifyURL, 120000);
 
      int i;
      NameValueCollection coll;
      //Load Form variables into NameValueCollection variable.
      coll = Request.Form;
 
      // Get names of all forms into a string array.
      String[] requestarr = coll.AllKeys;
      //进行排序;
      string[] Sortedstr = BubbleSort(requestarr);
      //构造待md5摘要字符串 ;
      StringBuilder prestr = new StringBuilder();
 
      for (i = 0; i < Sortedstr.Length; i++)
      {
        if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
        {
          if (i == Sortedstr.Length - 1)
          {
            prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]]);
          }
          else
          {
            prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]] + "&");
 
          }
        }
 
 
      }
 
      prestr.Append(key);
      string mysign = GetMD5(prestr.ToString());
      string sign = Request.QueryString["sign"];
      string trade_status = Request.QueryString["trade_status"];
 
      if (mysign == sign && responseTxt == "true" && trade_status == "TRADE_SUCCESS"//验证支付发过来的消息,签名是否正确
      {
        string order_amount = Request.QueryString["total_fee"].ToString().Trim();
        string order_code = Request.QueryString["out_trade_no"].ToString().Trim();
 
 
        
        // updateOrder(order_code);//更新订单状态
        Response.Redirect(""); //跳转到支付成功页面
      }
      else
      {
 
        Response.Write("支付失败。");
        Response.Write("<br>Result:responseTxt=" + responseTxt);
        Response.Write("<br>Result:mysign=" + mysign);
        Response.Write("<br>Result:sign=" + sign);
      }
      return View();
    }
 
    public static string GetMD5(string s, string _input_charset)
    {
      /// <summary>
      /// 与ASP兼容的MD5加密算法
      /// </summary>
 
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
      StringBuilder sb = new StringBuilder(32);
      for (int i = 0; i < t.Length; i++)
      {
        sb.Append(t[i].ToString("x").PadLeft(2, '0'));
      }
      return sb.ToString();
    }
 
 
 
    public static string GetMD5(string s)
    {
      /// <summary>
      /// 与ASP兼容的MD5加密算法
      /// </summary>
 
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(s));
      StringBuilder sb = new StringBuilder(32);
      for (int i = 0; i < t.Length; i++)
      {
        sb.Append(t[i].ToString("x").PadLeft(2, '0'));
      }
      return sb.ToString();
    }
 
    public static string[] BubbleSort(string[] r)
    {
      /// <summary>
      /// 冒泡排序法
      /// </summary>
 
      int i, j; //交换标志 
      string temp;
 
      bool exchange;
 
      for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
      {
        exchange = false; //本趟排序开始前,交换标志应为假
 
        for (j = r.Length - 2; j >= i; j--)
        {
          if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0) //交换条件
          {
            temp = r[j + 1];
            r[j + 1] = r[j];
            r[j] = temp;
 
            exchange = true; //发生了交换,故将交换标志置为真 
          }
        }
 
        if (!exchange) //本趟排序未发生交换,提前终止算法 
        {
          break;
        }
 
      }
      return r;
    }
    //获取远程服务器ATN结果
    public String Get_Http(String a_strUrl, int timeout)
    {
      string strResult;
      try
      {
 
        HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
        myReq.Timeout = timeout;
        HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
        Stream myStream = HttpWResp.GetResponseStream();
        StreamReader sr = new StreamReader(myStream, Encoding.Default);
        StringBuilder strBuilder = new StringBuilder();
        while (-1 != sr.Peek())
        {
          strBuilder.Append(sr.ReadLine());
        }
 
        strResult = strBuilder.ToString();
      }
      catch (Exception exp)
      {
 
        strResult = "错误:" + exp.Message;
      }
 
      return strResult;
    }
 
  }
}

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

原文链接:https://blog.csdn.net/for12/article/details/50772034

延伸 · 阅读

精彩推荐
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10