例一:javascript
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; public partial class pay : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Encoding gb2312 = Encoding.GetEncoding("gb2312"); Response.ContentEncoding = gb2312; Request.ContentEncoding = gb2312; } protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { Vlike_DB_read a = new Vlike_DB_read(); string zfb_ddh = a.get_zfb_id(Membership.GetUser().UserName, Convert.ToInt32(DropDownList1.SelectedValue)); Response.Redirect(img("0001", "包月", "影視包月 10元/月", zfb_ddh, "10.00", Membership.GetUser().UserName.ToUpper(), DropDownList1.SelectedValue)); } else { Response.Write("<script type='text/javascript'>alert('請先登錄!');</script>"); } } private string img(string strcmd, string strSub, string strSubinfo, string strid, string strMoney, string strUser, string strNum) { string strsellerEmail = "341081@qq.com"; //賣家支付寶賬號 string strAc = ""; //賣家支付寶安全校驗碼 string INTERFACE_URL = "https://www.alipay.com/payto:"; string strCmd = strcmd; //命令字 string strSubject = strSub; //商品名 string strBody = strSubinfo; //商品描述 string strOrder_no = strid; //商戶訂單號 string strPrice = strMoney; //商品單價 0.01~50000.00 string rurl = "http://"; //商品展現網址 string strType = "2"; //type支付類型 1:商品購買2:服務購買3:網絡拍賣4:捐贈 string strNumber = strNum; //購買數量 string strTransport = "3"; //發貨方式 1:平郵2:快遞3:虛擬物品 string strOrdinary_fee = ""; //平郵運費 string strExpress_fee = ""; //快遞運費 string strReadOnly = "true"; //交易信息是否只讀 string strBuyer_msg = ""; //買家給賣家的留言 string strBuyer = ""; //買家EMAIL string strBuyer_name = strUser; //買家姓名 string strBuyer_address = ""; //買家地址 string strBuyer_zipcode = ""; //買家郵編 string strBuyer_tel = ""; //買家電話號碼 string strBuyer_mobile = ""; //買家手機號碼 string strPartner = ""; //合做夥伴ID 保留字段 return CreatUrl(strsellerEmail, strAc, INTERFACE_URL, strCmd, strSubject, strBody, strOrder_no, strPrice, rurl, strType, strNumber, strTransport, strOrdinary_fee, strExpress_fee, strReadOnly, strBuyer_msg, strBuyer, strBuyer_name, strBuyer_address, strBuyer_zipcode, strBuyer_tel, strBuyer_mobile, strPartner); } private string CreatUrl( string strsellerEmail, string strAc, string INTERFACE_URL, string strCmd, string strSubject, string strBody, string strOrder_no, string strPrice, string rurl, string strType, string strNumber, string strTransport, string strOrdinary_fee, string strExpress_fee, string strReadOnly, string strBuyer_msg, string strBuyer, string strBuyer_name, string strBuyer_address, string strBuyer_zipcode, string strBuyer_tel, string strBuyer_mobile, string strPartner) { //如下參數值不能留空 string str2CreateAc = ""; str2CreateAc += "cmd" + strCmd + "subject" + strSubject; str2CreateAc += "body" + strBody; str2CreateAc += "order_no" + strOrder_no; str2CreateAc += "price" + strPrice; str2CreateAc += "url" + rurl; str2CreateAc += "type" + strType; str2CreateAc += "number" + strNumber; str2CreateAc += "transport" + strTransport; str2CreateAc += "ordinary_fee" + strOrdinary_fee; str2CreateAc += "express_fee" + strExpress_fee; str2CreateAc += "readonly" + strReadOnly; str2CreateAc += "buyer_msg" + strBuyer_msg; str2CreateAc += "seller" + strsellerEmail; str2CreateAc += "buyer" + strBuyer; str2CreateAc += "buyer_name" + strBuyer_name; str2CreateAc += "buyer_address" + strBuyer_address; str2CreateAc += "buyer_zipcode" + strBuyer_zipcode; str2CreateAc += "buyer_tel" + strBuyer_tel; str2CreateAc += "buyer_mobile" + strBuyer_mobile; str2CreateAc += "partner" + strPartner; str2CreateAc += strAc; string acCode = GetMD5(str2CreateAc); string parameter = ""; parameter += INTERFACE_URL + strsellerEmail + "?cmd=" + strCmd; parameter += "&subject=" + Server.UrlEncode(strSubject); parameter += "&body=" + Server.UrlEncode(strBody); parameter += "&order_no=" + strOrder_no; parameter += "&url=" + rurl; parameter += "&price=" + strPrice; parameter += "&type=" + strType; parameter += "&number=" + strNumber; parameter += "&transport=" + strTransport; parameter += "&ordinary_fee=" + strOrdinary_fee; parameter += "&express_fee=" + strExpress_fee; parameter += "&readonly=" + strReadOnly; parameter += "&buyer_msg=" + strBuyer_msg; parameter += "&buyer=" + strBuyer; parameter += "&buyer_name=" + Server.UrlEncode(strBuyer_name); parameter += "&buyer_address=" + strBuyer_address; parameter += "&buyer_zipcode=" + strBuyer_zipcode; parameter += "&buyer_tel=" + strBuyer_tel; parameter += "&buyer_mobile=" + strBuyer_mobile; parameter += "&partner=" + strPartner; parameter += "&ac=" + acCode; return parameter; } private static string GetMD5(string s) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding("gb2312").GetBytes(s)); System.Text.StringBuilder sb = new System.Text.StringBuilder(32); for (int i = 0; i < t.Length; i++) { sb.Append(t[i].ToString("x").PadLeft(2, '0')); } return sb.ToString(); } } 接收支付寶信息並進行相應操做 <%@ Page Language="C#" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.Text" %> <%@ Import Namespace="System.Security.Cryptography" %> <script type="text/C#" runat="server"> private string returnTxt = "N"; //返回給支付寶通知接口的結果 private string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?"; //支付寶查詢接口URL private string myalipayEmail = "341081@qq.com"; //商戶的支付寶Email private string constPaySecurityCode = ""; //碼 private SqlConnection conn = new SqlConnection(); private string GetMD5(string s) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding("gb2312").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(); } private String Get_Http(String a_strUrl, int timeout) { string strResult; try { System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create(a_strUrl); myReq.Timeout = timeout; System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse) myReq.GetResponse(); Stream myStream = HttpWResp.GetResponseStream(); StreamReader sr = new StreamReader(myStream, System.Text.Encoding.Default); System.Text.StringBuilder strBuilder = new System.Text.StringBuilder(); while (-1 != sr.Peek()) { strBuilder.Append(sr.ReadLine() + "\r\n"); } strResult = strBuilder.ToString(); } catch (Exception exp) { strResult = "錯誤:" + exp.Message; } return strResult; } public void send(string sql) { string dbconn = "data source=127.0.0.1;UID=Cm;PWD=fallenangel;database=text"; conn = new SqlConnection(dbconn); conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); int aa = cmd.ExecuteNonQuery(); conn.Close(); } private void Page_Load(object sender, System.EventArgs e) { //檢查支付寶通知接口傳遞過來的參數是否合法 string msg_id = System.Web.HttpContext.Current.Request["msg_id"]; string order_no = System.Web.HttpContext.Current.Request["order_no"]; string gross = System.Web.HttpContext.Current.Request["gross"]; string buyer_email = System.Web.HttpContext.Current.Request["buyer_email"]; string buyer_name = System.Web.HttpContext.Current.Request["buyer_name"]; string buyer_address = System.Web.HttpContext.Current.Request["buyer_address"]; string buyer_zipcode = System.Web.HttpContext.Current.Request["buyer_zipcode"]; string buyer_tel = System.Web.HttpContext.Current.Request["buyer_tel"]; string buyer_mobile = System.Web.HttpContext.Current.Request["buyer_mobile"]; string action = System.Web.HttpContext.Current.Request["action"]; string s_date = System.Web.HttpContext.Current.Request["date"]; string ac = System.Web.HttpContext.Current.Request["ac"]; string notify_type = System.Web.HttpContext.Current.Request["notify_type"]; alipayNotifyURL = alipayNotifyURL + "msg_id=" + msg_id + "&email=" + myalipayEmail + "&order_no=" + order_no; //獲取支付寶ATN返回結果,true和false都是正確的訂單信息,invalid 是無效的 string responseTxt = Get_Http(alipayNotifyURL, 120000); string Str = "msg_id" + msg_id + "order_no" + order_no + "gross" + gross + "buyer_email" + buyer_email + "buyer_name" + buyer_name + "buyer_address" + buyer_address + "buyer_zipcode" + buyer_zipcode + "buyer_tel" + buyer_tel + "buyer_mobile" + buyer_mobile + "action" + action + "date" + s_date + constPaySecurityCode; string ac_code = GetMD5(Str); if (action == "test") //支付寶接口測試是否有效 { returnTxt = "Y"; } if (action == "sendOff") //發貨通知 { if (responseTxt.Substring(0, 4) == "true" || responseTxt.Substring(0, 4) == "fals")//ATN,驗證消息是否支付寶發過來 { if (ac_code == ac)//驗證消息是否被修改 { //數據庫操做 } } } if (action == "checkOut") //交易完成通知 { returnTxt = "N"; if (responseTxt.Substring(0, 4) == "true" || responseTxt.Substring(0, 4) == "fals")//ATN,驗證消息是否支付寶發過來 { if (ac_code == ac)//驗證消息是否被修改 { //數據庫操做 } } } System.Web.HttpContext.Current.Response.Write(returnTxt); } </script>
例二:java
首先當項目中須要支付寶接口的時候,人家會給你一個Demo,裏邊代碼很重要,基本均可以拿來複制黏貼,只需
改下參數而已。
2個接口的類是同樣的,因此須要放在2個文件夾中,你也能夠放在類庫中。我是這樣放的
App中是支付接口的類,外部是登陸接口的類
首先須要把陰影的類中的幾個參數修改下sql
static Config() { //↓↓↓↓↓↓↓↓↓↓請在這裏配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ //合做身份者ID,以2088開頭由16位純數字組成的字符串 partner = "2088601323326437"; //交易安全檢驗碼,由數字和字母組成的32位字符串 key = ""; //簽約支付寶帳號或賣家支付寶賬戶 seller_email = ""; //頁面跳轉同步返回頁面文件路徑 要用 http://格式的完整路徑,不容許加?id=123這類自定義參數 return_url = "http://ozmb.inicp.com/zfbreturn.aspx"; //服務器通知的頁面文件路徑 要用 http://格式的完整路徑,不容許加?id=123這類自定義參數 notify_url = "http://ozmb.inicp.com/zfbreturn.aspx";
說明部分很清楚,我就不解釋了
其餘部分都不須要動!
支付寶快捷登陸
這個接口很簡單,2個頁面,一個Send,一個return頁面數據庫
using Com.Alipay; ///////Send頁面,除了個人判斷,其餘均可以複製黏貼,類的引用要注意,根據你的文件夾所在來引用 public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["Member_Info"] == null && Session["App"]==null) { string anti_phishing_key = ""; //獲取客戶端的IP地址,建議:編寫獲取客戶端IP地址的程序 string exter_invoke_ip = ""; //注意: //請慎重選擇是否開啓防釣魚功能 //exter_invoke_ip、anti_phishing_key一旦被設置過,那麼它們就會成爲必填參數 //建議使用POST方式請求數據 //示例: //exter_invoke_ip = ""; //Service aliQuery_timestamp = new Service(); //anti_phishing_key = aliQuery_timestamp.Query_timestamp(); //獲取防釣魚時間戳函數 //////////////////////////////////////////////////////////////////////////////////////////////// //把請求參數打包成數組 SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>(); sParaTemp.Add("anti_phishing_key", anti_phishing_key); sParaTemp.Add("exter_invoke_ip", exter_invoke_ip); //構造快捷登陸接口表單提交HTML數據,無需修改 Service ali = new Service(); string sHtmlText = ali.Alipay_auth_authorize(sParaTemp); Response.Write(sHtmlText); } else if (Session["Member_Info"] != null) { Response.Write("<script>alert('你已經登陸,請先退出在進行支付寶登陸!');location.href='index.aspx';</script>"); } else if (Session["App"] != null) { Response.Write("<script>alert('你已經登陸過了!');location.href='index.aspx';</script>"); } } } //下邊是返回頁面return。一個泛型方法不要忘記。除了個人判斷其餘能夠直接複製黏貼 using Com.Alipay; public partial class zfblogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { SortedDictionary<string, string> sPara = GetRequestGet(); if (sPara.Count > 0)//判斷是否有帶返回參數 { Notify aliNotify = new Notify(); bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]); if (verifyResult)//驗證成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //請在這裏加上商戶的業務邏輯程序代碼 //——請根據您的業務邏輯來編寫程序(如下代碼僅做參考)—— //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表 string user_id = Request.QueryString["user_id"];//支付寶用戶id string token = Request.QueryString["token"]; //受權令牌 Label4.Text = user_id.ToString(); Session["token"] = token; Session["App"] = user_id; } else { Response.Write("<script>alert('登陸失敗');location.href='index.aspx'</script>"); } } else { Response.Write("<script>alert('登陸失敗');location.href='index.aspx'</script>"); } } } public SortedDictionary<string, string> GetRequestGet() { int i = 0; SortedDictionary<string, string> sPara = new SortedDictionary<string, string>(); NameValueCollection coll; //Load Form variables into NameValueCollection variable. coll = Request.QueryString; // Get names of all forms into a string array. String[] requestItem = coll.AllKeys; for (i = 0; i < requestItem.Length; i++) { sPara.Add(requestItem[i], Request.QueryString[requestItem[i]]); } return sPara; } }
仍是2個頁面,一個是Send,一個仍是return。傳參頁面主要是傳遞須要的:價格,收貨人,電話等等信息,
返回頁面是當用戶支付完畢後,判斷支付是否成功,返回到支付網頁上來express
// 這個是傳參層,具體哪些須要填寫都很清楚 else if (RadioButtonList1.SelectedValue == "支付寶支付") { Session["time2"]= DateTime.Now.ToString("yyyyMMddHHmmss"); ZFB(); string out_trade_no =Session["time2"].ToString(); //請與貴網站訂單系統中的惟一訂單號匹配 string subject = "蔓越莓支付寶支付:" + Session["time2"].ToString(); //訂單名稱,顯示在支付寶收銀臺裏的「商品名稱」裏,顯示在支付寶的交易管理的「商品名稱」的列表裏。 string body = "配送方式:"+RadioButtonList2.SelectedValue+",來自:蔓越莓,訂單號:"+Session["time2"].ToString(); //訂單描述、訂單詳細、訂單備註,顯示在支付寶收銀臺裏的「商品描述」裏 string price = Label8.Text.Trim(); //訂單總金額,顯示在支付寶收銀臺裏的「商品單價」裏 string logistics_fee = double.Parse(Label7.Text)+""; //物流費用,即運費。 string logistics_type = "EXPRESS"; //物流類型,三個值可選:EXPRESS(快遞)、POST(平郵)、EMS(EMS) string logistics_payment = "SELLER_PAY"; //物流支付方式,兩個值可選:SELLER_PAY(賣家承擔運費)、BUYER_PAY(買家承擔運費) string quantity = "1"; //商品數量,建議默認爲1,不改變值,把一次交易當作是一次下訂單而非購買一件商品。 //選填參數// //買家收貨信息(推薦做爲必填) //該功能做用在於買家已經在商戶網站的下單流程中填過一次收貨信息,而不須要買家在支付寶的付款流程中再次填寫收貨信息。 //若要使用該功能,請至少保證receive_name、receive_address有值 //收貨信息格式請嚴格按照姓名、地址、郵編、電話、手機的格式填寫 string receive_name = UserName.Text; //收貨人姓名,如:張三 string receive_address = ddlProvince.SelectedValue + Request.Form["ddlCity"].ToString() + Address.Text; //收貨人地址,如:XX省XXX市XXX區XXX路XXX小區XXX棟XXX單元XXX號 string receive_zip = ""; if (Zip.Text != "") { receive_zip = Zip.Text; //收貨人郵編,如:123456 } else { receive_zip = "未填寫"; } string receive_phone = ""; if (Phone.Text != "") { receive_phone = Phone.Text; //收貨人電話號碼,如:0571-81234567 } else { receive_phone = "未填寫"; } string receive_mobile = Mobile.Text; //收貨人手機號碼,如:13312341234 //網站商品的展現地址,不容許加?id=123這類自定義參數 string show_url = ""; //快捷登陸用令牌受權碼,該參數的值由快捷登陸接口(alipay.auth.authorize)的頁面跳轉同步通知參數中獲取 string token = ""; //注意: //token的有效時間爲30分鐘,過時後需從新執行快捷登陸接口(alipay.auth.authorize)得到新的token //////////////////////////////////////////////////////////////////////////////////////////////// //把請求參數打包成數組 SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>(); sParaTemp.Add("body", body); sParaTemp.Add("logistics_fee", logistics_fee); sParaTemp.Add("logistics_payment", logistics_payment); sParaTemp.Add("logistics_type", logistics_type); sParaTemp.Add("out_trade_no", out_trade_no); sParaTemp.Add("payment_type", "1"); sParaTemp.Add("price", price); sParaTemp.Add("quantity", quantity); sParaTemp.Add("receive_address", receive_address); sParaTemp.Add("receive_mobile", receive_mobile); sParaTemp.Add("receive_name", receive_name); sParaTemp.Add("receive_phone", receive_phone); sParaTemp.Add("receive_zip", receive_zip); sParaTemp.Add("show_url", show_url); sParaTemp.Add("subject", subject); sParaTemp.Add("token", token); //構造標準雙接口表單提交HTML數據,無需修改 Service ali = new Service(); string sHtmlText = ali.Trade_create_by_buyer(sParaTemp); Response.Write(sHtmlText); } //下邊是個返回層,判斷是否支付成功,當成功我須要把訂單加到數據 using Com.Alipay; using System.Collections.Specialized; public partial class zfb_success : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { SortedDictionary<string, string> sPara = GetRequestGet(); if (sPara.Count > 0)//判斷是否有帶返回參數 { Notify aliNotify = new Notify(); bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]); if (verifyResult)//驗證成功 { string order_no = Request.QueryString["out_trade_no"]; string total_fee = Request.QueryString["price"]; if (Session["EOrder"] != null && Session["Cart2"] != null) { PageDataBind(); } else if (Session["COrder"] != null && Session["Cart"] != null) { PageDataBind2(); } else { this.table2.Visible = true; this.table1.Visible = false; } } else { this.table1.Visible = true; this.table2.Visible = false; } } else { this.table1.Visible = true; this.table2.Visible = false; } } } ////這個類不能忘記添加進來 public SortedDictionary<string, string> GetRequestGet() { int i = 0; SortedDictionary<string, string> sPara = new SortedDictionary<string, string>(); NameValueCollection coll; //Load Form variables into NameValueCollection variable. coll = Request.QueryString; // Get names of all forms into a string array. String[] requestItem = coll.AllKeys; for (i = 0; i < requestItem.Length; i++) { sPara.Add(requestItem[i], Request.QueryString[requestItem[i]]); } return sPara; }
其實支付寶的Demo很清晰,示例很詳細,很不錯。網銀接口也同樣,都只是須要修改一些參數,其餘都是直接
複製黏貼罷了。數組