欢迎光临

木子屋

标题: 支付宝即时到帐交易接口示例

作者: dnawo

日期: 2011-03-02 10:34 PM

分类: Web编程

内容:
支付类(AlipayHelper.cs)：
复制内容到剪贴板 程序代码using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace MZ.Common
{
/// <summary>
/// 支付宝即时到帐交易
/// </summary>
public class AlipayHelper
{
private string _partner;
private string _key;
private string _seller_email;
private string _httpurl;
private string __input_charset;
private string _sign_type;
private string _payment_type;
/// <summary>
/// 构造函数
/// </summary>
public AlipayHelper()
{
_partner = "2088000000000000";
_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
_seller_email = "dnawo@alipay.com";
_httpurl = "https://www.alipay.com/cooperate/gateway.do?";
__input_charset = "utf-8";
_sign_type = "MD5";
_payment_type = "1";
}
/// <summary>
/// 合作者身份ID(PID),支付宝网站获取
/// </summary>
public string Partner
{
get { return _partner; }
set { _partner = value; }
}
/// <summary>
/// MD5私钥(Key),支付宝网站获取
/// </summary>
public string Key
{
get { return _key; }
set { _key = value; }
}
/// <summary>
/// 卖家支付宝帐号
/// </summary>
public string SellerEmail
{
get { return _seller_email; }
set { _seller_email = value; }
}
/// <summary>
/// 支付请求、验证请求接口
/// </summary>
public string HttpUrl
{
get { return _httpurl; }
set { _httpurl = value; }
}
/// <summary>
/// 参数编码字符集：utf-8、gb2312、gbk
/// </summary>
public string InputCharset
{
get { return __input_charset; }
set { __input_charset = value; }
}
/// <summary>
/// 签名方式：DSA、RSA、MD5
/// </summary>
public string SignType
{
get { return _sign_type; }
set { _sign_type = value; }
}
/// <summary>
/// 收款类型：1商品购买、4捐赠
/// </summary>
public string PaymentType
{
get { return _payment_type; }
set { _payment_type = value; }
}
/// <summary>
/// 生成签名
/// </summary>
/// <param name="parameters"></param>
private string Signature(SortedList<string, string> parameters)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> item in parameters)
{
if (item.Key != "sign" && item.Key != "sign_type")
{
sb.Append(string.Format("{0}={1}&", item.Key.ToLower(), item.Value));
}
}
string str = sb.ToString().TrimEnd('&') + Key;
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
return BitConverter.ToString(MD5.ComputeHash(Encoding.GetEncoding(InputCharset).GetBytes(str))).Replace("-", "").ToLower();
}
/// <summary>
/// 生成请求URL
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
private string CreateURL(SortedList<string, string> parameters)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> item in parameters)
{
sb.Append(string.Format("{0}={1}&", item.Key.ToLower(), HttpUtility.UrlEncode(item.Value, Encoding.GetEncoding(InputCharset))));
}
return HttpUrl + sb.ToString().TrimEnd('&');
}
/// <summary>
/// HTPP请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string HttpGet(string url)
{
try
{
Encoding encoding = Encoding.GetEncoding(InputCharset);
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "GET";
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch
{
return "";
}
}
/// <summary>
/// 支付
/// </summary>
/// <param name="subject">商品名称</param>
/// <param name="total_fee">交易金额,精确到两位小数</param>
/// <param name="out_trade_no">商户网站订单号</param>
/// <param name="return_url">同步通知页面</param>
/// <returns></returns>
public string Pay(string subject, string total_fee, string out_trade_no, string return_url)
{
SortedList<string, string> parameters = new SortedList<string, string>();
parameters.Add("service", "create_direct_pay_by_user"); //接口名称
parameters.Add("partner", Partner);
parameters.Add("_input_charset", InputCharset);
parameters.Add("seller_email", SellerEmail);
parameters.Add("payment_type", PaymentType);
parameters.Add("sign_type", SignType);
parameters.Add("subject", subject);
parameters.Add("total_fee", total_fee);
parameters.Add("out_trade_no", out_trade_no);
parameters.Add("return_url", return_url);
parameters.Add("sign", Signature(parameters));
return CreateURL(parameters);
}
/// <summary>
/// 验证交易状态
/// </summary>
/// <param name="trade_status">交易状态</param>
/// <param name="notify_id">通知校验ID</param>
/// <returns></returns>
public bool NotifyVerify(string trade_status, string notify_id)
{
bool result = false;

if (trade_status.ToUpper() == "TRADE_FINISHED" || trade_status.ToUpper() == "TRADE_SUCCESS")
{
SortedList<string, string> parameters = new SortedList<string, string>();
parameters.Add("service", "notify_verify"); //接口名称
parameters.Add("partner", Partner);
parameters.Add("notify_id", notify_id);
//判断是否来源来支付宝,务必在支付宝同步1分钟内验证,否则结果都为false
if (HttpGet(CreateURL(parameters)).ToLower().IndexOf("true") != -1)
result = true;
}
return result;
}
}
}
调用示例
Default.aspx：
复制内容到剪贴板 程序代码<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>支付宝即时到帐交易接口示例-Mzwu.Com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnPay" runat="server" onclick="btnPay_Click" Text="开始支付" />
<br />
<asp:Label ID="lblReturnMsg" runat="server" Text="lblReturnMsg"></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs：
复制内容到剪贴板 程序代码using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using MZ.Common;
public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// 页面加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
//支付宝同步状态
if (!Page.IsPostBack && Request.QueryString["trade_status"] != null)
{
Verify();
}
}
/// <summary>
/// 1.开始支付
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnPay_Click(object sender, EventArgs e)
{
AlipayHelper alipay = new AlipayHelper();
string url = alipay.Pay("竹炭颈椎枕", "0.01", DateTime.Now.ToString("yyyyMMddHHmmss"), "http://127.0.0.1/");
Response.Redirect(url);
}
/// <summary>
/// 2.支付结果
/// </summary>
protected void Verify()
{
AlipayHelper alipay = new AlipayHelper();
bool status = alipay.NotifyVerify(Request.QueryString["trade_status"], Request.QueryString["notify_id"]);
if (status)
lblReturnMsg.Text = "订单(" + Request.QueryString["out_trade_no"] + ")支付成功！";
else
lblReturnMsg.Text = "订单(" + Request.QueryString["out_trade_no"] + ")支付失败！";
}
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.051 ms

返回

标题: 支付宝即时到帐交易接口示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.051 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.098 ms

返回