【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付_第1頁
【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付_第2頁
【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付_第3頁
【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付_第4頁
【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付_第5頁
已閱讀5頁,還剩94頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

【移動應(yīng)用開發(fā)技術(shù)】如何使用ASP.NET實現(xiàn)微信JS-SDK支付

在下給大家分享一下如何使用ASP.NET實現(xiàn)微信JS-SDK支付,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!模型層實體類:

public

class

JsEntities

{

///

<summary>

///

公眾號id

///

</summary>

public

string

appId

{

get;

set;

}

///

<summary>

///

時間戳

///

</summary>

public

string

timeStamp

{

get;

set;

}

///

<summary>

///

隨機字符串

///

</summary>

public

string

nonceStr

{

get;

set;

}

///

<summary>

///

訂單詳情擴展字符串

///

</summary>

public

string

package

{

get;

set;

}

///

<summary>

///

簽名類型

///

</summary>

public

string

signType

{

get;

set;

}

///

<summary>

///

簽名

///

</summary>

public

string

paySign

{

get;

set;

}

}

public

class

UnifyEntities

{

///

<summary>

///

公眾賬號ID

///

</summary>

public

string

appid

{

get;

set;

}

///

<summary>

///

微信支付分配的商戶號

///

</summary>

public

string

mch_id

{

get;

set;

}

///

<summary>

///

微信支付分配的終端設(shè)備號

///

</summary>

public

string

device_info

{

get;

set;

}

///

<summary>

///

隨機字符串,不長于32位

///

</summary>

public

string

nonce_str

{

get;

set;

}

///

<summary>

///

簽名

///

</summary>

public

string

sign

{

get;

set;

}

///

<summary>

///

商品描述最大長度127

///

</summary>

public

string

body

{

get;

set;

}

///

<summary>

///

附加數(shù)據(jù),原樣返回

///

</summary>

public

string

attach

{

get;

set;

}

///

<summary>

///

商戶系統(tǒng)內(nèi)部的訂單號,32

個字符內(nèi)、可包含字母,確保在商戶系統(tǒng)唯一,詳細說明

///

</summary>

public

string

out_trade_no

{

get;

set;

}

///

<summary>

///

訂單總金額,單位為分,不能帶小數(shù)點

///

</summary>

public

string

total_fee

{

get;

set;

}

///

<summary>

///

終端IP

///

</summary>

public

string

spbill_create_ip

{

get;

set;

}

///

<summary>

///

交易起始時間

///

</summary>

public

string

time_start

{

get;

set;

}

///

<summary>

///

交易結(jié)束時間

///

</summary>

public

string

time_expire

{

get;

set;

}

///

<summary>

///

接收微信支付成功通知

///

</summary>

public

string

notify_url

{

get;

set;

}

///

<summary>

///

JSAPI、NATIVE、APP

///

</summary>

public

string

trade_type

{

get;

set;

}

///

<summary>

///

用戶在商戶appid下的唯一標(biāo)識,trade_type為JSAPI

時,此參數(shù)必傳

///

</summary>

public

string

openid

{

get;

set;

}

///

<summary>

///

只在

trade_type

NATIVE

時需要填寫。此id為二維碼中包含的商品ID,商戶自行維護。

///

</summary>

public

string

product_id

{

get;

set;

}

}

public

class

UnifyReceive

{

///

<summary>

///

SUCCESS/FAIL此字段是通信標(biāo)識,非交易標(biāo)識,交易是否成功需要查看result_code來判斷

///

</summary>

public

string

return_code

{

get;

set;

}

///

<summary>

///

返回信息,如非空,為錯誤原因

///

</summary>

public

string

return_msg

{

get;

set;

}

///

<summary>

///

微信分配的公眾賬號ID

///

</summary>

public

string

appid

{

get;

set;

}

///

<summary>

///

微信支付分配的商戶號

///

</summary>

public

string

mch_id

{

get;

set;

}

///

<summary>

///

隨機字符串,不長于32位

///

</summary>

public

string

nonce_str

{

get;

set;

}

///

<summary>

///

簽名

///

</summary>

public

string

sign

{

get;

set;

}

///

<summary>

///

業(yè)務(wù)結(jié)果

///

</summary>

public

string

result_code

{

get;

set;

}

///

<summary>

///

預(yù)支付ID

///

</summary>

public

string

prepay_id

{

get;

set;

}

///

<summary>

///

交易類型

///

</summary>

public

string

trade_type

{

get;

set;

}

///

<summary>

///

二維碼鏈接

///

</summary>

public

string

code_url

{

get;

set;

}

public

UnifyReceive(string

xml)

{

XElement

doc

=

XElement.Parse(xml);

return_code

=

doc.Element("return_code").Value;

return_msg

=

doc.Element("return_msg").Value;

if

(return_code

==

"SUCCESS")

{

appid

=

doc.Element("appid").Value;

mch_id

=

doc.Element("mch_id").Value;

nonce_str

=

doc.Element("nonce_str").Value;

sign

=

doc.Element("sign").Value;

result_code

=

doc.Element("result_code").Value;

if

(result_code

==

"SUCCESS")

{

trade_type

=

doc.Element("trade_type").Value;

prepay_id

=

doc.Element("prepay_id").Value;

if

(trade_type

==

"NATIVE")

{

code_url

=

doc.Element("code_url").Value;

}

trade_type

=

doc.Element("trade_type").Value;

}

}

}

}TestJs.aspx內(nèi)容:<%@

Page

Language="C#"

AutoEventWireup="true"

CodeBehind="JsPay.aspx.cs"

Inherits="WeChatPayDemo.JsPay"

%>

<html

xmlns="/1999/xhtml">

<head

runat="server">

<meta

http-equiv="Content-Type"

content="text/html;

charset=utf-8"

/>

<title></title>

<script

src="/jquery-1.9.0.js"></script>

<script

src="Scripts/wxpay.js"></script>

<script>

$(function

()

{

$("#submit").click(function

()

{

var

OID

="<%=openid%>";

alert(OID);

$.get("WxPay/WxPay.ashx?action=jspayparam",

{

body:

$("#body").val(),

total_fee:

$("#price").val(),

out_trade_no:

$("#order").val(),

trade_type:

"JSAPI",

msgid:

"<%=openid%>"

},

function

(data)

{

WxPay.Pay(data.appId,

data.timeStamp,

data.nonceStr,

data.package,

data.signType,

data.paySign,

function

()

{

alert("支付成功");

});

},

"json");

});

})

</script>

</head>

<body>

<form

id="form1"

runat="server">

<p>

商品描述:<input

type="text"

id="body"

/>

商品價格:<input

type="text"

id="price"

/>

訂單號:<input

type="text"

id="order"

/>

<input

type="button"

value="提交訂單"

id="submit"

/>

</p>

</form>

</body>

</html>JsPay.aspx.cs代碼:

public

partial

class

JsPay

:

System.Web.UI.Page

{

public

string

openid

=

"";

protected

void

Page_Load(object

sender,

EventArgs

e)

{

string

code

=

Request["code"];

if

(string.IsNullOrEmpty(code))

{

//如果code沒獲取成功,重新拉取一遍

GetAuthUrl("wxxxxxxxxxxxxxxxxxxxxxxx",

"/JsPay.aspx");

}

openid

=

GetOpenID("wxxxxxxxxxxxxxxxxxxxxxxx",

"dsdssdsdsdsdsdsdsdsdsd",

JKRequest.GetQueryString("code"),

()

=>

{

});

}

public

string

GetOpenID(string

appid,

string

secret,

string

code,

Action

CallBack)

{

try

{

string

retdata

=

Utils.HttpGet(string.Format("/sns/oauth3/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",

appid,

secret,

code));

.LogHelper.WriteFile(retdata);

JObject

jobj

=

(JObject)JsonConvert.DeserializeObject(retdata);

string

openid

=

jobj.Value<string>("openid");

return

openid;

}

catch

(Exception)

{

CallBack();

return

"";

}

//

return

GetUserInfo(access_token,

openid);

}

///

<summary>

///

獲取鑒權(quán)地址

///

</summary>

///

<param

name="appid"></param>

///

<param

name="redirect_url"></param>

///

<returns></returns>

public

void

GetAuthUrl(string

appid,

string

redirect_url)

{

Response.Redirect(string.Format("/connect/oauth3/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123#wechat_redirect",

appid,

Utils.UrlEncode(redirect_url)));

}

}WxPay.ashx代碼:///

<summary>

///

WxPay

的摘要說明

///

</summary>

public

class

WxPay

:

IHttpHandler

{

///

<summary>

///

公眾賬號ID

///

</summary>

private

string

appid

=

"wxxxxxxxxxxxxxxxx";

///

<summary>

///

商戶號

///

</summary>

private

string

mch_id

=

"12333333333";

///

<summary>

///

通知url

///

</summary>

private

string

notify_url

=

"/Notify2.aspx";

///

<summary>

///

密鑰

///

</summary>

private

string

key

=

"chinapagexxxxxxxxxxxxx";

public

void

ProcessRequest(HttpContext

context)

{

string

action

=

JKRequest.GetQueryString("action");

switch

(action)

{

case

"unifysign":

GetUnifySign(context);

break;

case

"jspayparam":

GetJsPayParam(context);

break;

case

"nativedynamic":

GetPayQr(context);

break;

}

}

#region

獲取js支付參數(shù)

void

GetJsPayParam(HttpContext

context)

{

JsEntities

jsEntities

=

new

JsEntities()

{

appId

=

appid,

nonceStr

=

.Utils.GetRandom(),

package

=

string.Format("prepay_id={0}",

GetPrepayId(context)),

signType

=

"MD5",

timeStamp

=

.Utils.ConvertDateTimeInt(DateTime.Now).ToString()

};

string

url,

sign;

string

xmlStr

=

.Utils.GetUnifyRequestXml<JsEntities>(jsEntities,

key,

out

url,

out

sign);

LogHelper.WriteFile(xmlStr);

jsEntities.paySign

=

sign;

context.Response.Write(JsonConvert.SerializeObject(jsEntities));

}

#endregion

#region

獲取預(yù)支付ID

//

string

GetPrepayId(HttpContext

context)

{

string

xml;

GetUnifySign(context,

out

xml);

LogHelper.WriteFile("GetPrepayId71--"

+

xml);

UnifyReceive

unifyReceive

=

new

UnifyReceive(.Utils.HttpPost("/pay/unifiedorder",

xml));

LogHelper.WriteFile("unifyReceive73--"

+

unifyReceive.prepay_id);

return

unifyReceive.prepay_id;

}

#endregion

#region

獲取統(tǒng)一簽名

void

GetUnifySign(HttpContext

context)

{

string

xml;

context.Response.Write(GetUnifySign(context,

out

xml));

}

#endregion

#region

獲取統(tǒng)一簽名

string

GetUnifySign(HttpContext

context,

out

string

xml)

{

string

url,

sign;

xml

=

WxPayHelper.Utils.GetUnifyUrlXml<UnifyEntities>(GetUnifyEntities(context),

key,

out

url,

out

sign);

return

sign;

}

#endregion

#region

獲取二維碼

void

GetPayQr(HttpContext

context)

{

string

url

=

GetPayUrl(context);

WxPayHelper.Utils.GetQrCode(url);

}

#endregion

#region

獲取二維碼鏈接

string

GetPayUrl(HttpContext

context)

{

string

xml;

GetUnifySign(context,

out

xml);

WxPayHelper.Utils.WriteTxt(xml);

UnifyReceive

unifyReceive

=

new

UnifyReceive(WxPayHelper.Utils.HttpPost("/pay/unifiedorder",

xml));

return

unifyReceive.code_url;

}

#endregion

#region

獲取統(tǒng)一支付接口參數(shù)對象

UnifyEntities

GetUnifyEntities(HttpContext

context)

{

string

msgid

=

JKRequest.GetQueryString("msgid");

LogHelper.WriteFile("115"+msgid);

UnifyEntities

unify

=

new

UnifyEntities

{

appid

=

appid,

body

=

JKRequest.GetQueryString("body"),

mch_id

=

mch_id,

nonce_str

=

WxPayHelper.Utils.GetRandom(),

out_trade_no

=

JKRequest.GetQueryString("out_trade_no"),

notify_url

=

notify_url,

spbill_create_ip

=

JKRequest.GetIP(),

trade_type

=

JKRequest.GetQueryString("trade_type"),

total_fee

=

JKRequest.GetQueryString("total_fee")

};

if

(unify.trade_type

==

"NATIVE")

{

duct_id

=

msgid;

}

else

{

unify.openid

=

msgid;

}

return

unify;

}

#endregion

public

bool

IsReusable

{

get

{

return

false;

}

}

}Utils.cs代碼:

public

class

Utils

{

#region

MD5加密

public

static

string

MD5(string

pwd)

{

MD5

md5

=

new

MD5CryptoServiceProvider();

byte[]

data

=

System.Text.Encoding.Default.GetBytes(pwd);

byte[]

md5data

=

md5.ComputeHash(data);

md5.Clear();

string

str

=

"";

for

(int

i

=

0;

i

<

md5data.Length;

i++)

{

str

+=

md5data[i].ToString("x").PadLeft(2,

'0');

}

return

str;

}

///

<summary>

///

獲取文件的md5

///

</summary>

///

<param

name="filepath">文件路徑,url路徑</param>

///

<returns>md5字符串</returns>

string

GetMD5HashFromFile(string

filepath)

{

try

{

WebClient

wc

=

new

WebClient();

var

file

=

wc.OpenRead(new

Uri(filepath));

System.Security.Cryptography.MD5

md5

=

new

System.Security.Cryptography.MD5CryptoServiceProvider();

byte[]

retVal

=

md5.ComputeHash(file);

file.Close();

StringBuilder

sb

=

new

StringBuilder();

for

(int

i

=

0;

i

<

retVal.Length;

i++)

{

sb.Append(retVal[i].ToString("x2"));

}

return

sb.ToString();

}

catch

(Exception

ex)

{

throw

new

Exception("GetMD5HashFromFile()

fail,error:"

+

ex.Message);

}

}

#endregion

#region

對象轉(zhuǎn)換處理

///

<summary>

///

判斷對象是否為Int32類型的數(shù)字

///

</summary>

///

<param

name="Expression"></param>

///

<returns></returns>

public

static

bool

IsNumeric(object

expression)

{

if

(expression

!=

null)

return

IsNumeric(expression.ToString());

return

false;

}

///

<summary>

///

判斷對象是否為Int32類型的數(shù)字

///

</summary>

///

<param

name="Expression"></param>

///

<returns></returns>

public

static

bool

IsNumeric(string

expression)

{

if

(expression

!=

null)

{

string

str

=

expression;

if

(str.Length

>

0

&&

str.Length

<=

11

&&

Regex.IsMatch(str,

@"^[-]?[0-9]*[.]?[0-9]*$"))

{

if

((str.Length

<

10)

||

(str.Length

==

10

&&

str[0]

==

'1')

||

(str.Length

==

11

&&

str[0]

==

'-'

&&

str[1]

==

'1'))

return

true;

}

}

return

false;

}

///

<summary>

///

是否為Double類型

///

</summary>

///

<param

name="expression"></param>

///

<returns></returns>

public

static

bool

IsDouble(object

expression)

{

if

(expression

!=

null)

return

Regex.IsMatch(expression.ToString(),

@"^([0-9])[0-9]*(\.\w*)?$");

return

false;

}

///

<summary>

///

檢測是否符合email格式

///

</summary>

///

<param

name="strEmail">要判斷的email字符串</param>

///

<returns>判斷結(jié)果</returns>

public

static

bool

IsValidEmail(string

strEmail)

{

return

Regex.IsMatch(strEmail,

@"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");

}

public

static

bool

IsValidDoEmail(string

strEmail)

{

return

Regex.IsMatch(strEmail,

@"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

}

///

<summary>

///

檢測是否是正確的Url

///

</summary>

///

<param

name="strUrl">要驗證的Url</param>

///

<returns>判斷結(jié)果</returns>

public

static

bool

IsURL(string

strUrl)

{

return

Regex.IsMatch(strUrl,

@"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");

}

///

<summary>

///

將字符串轉(zhuǎn)換為數(shù)組

///

</summary>

///

<param

name="str">字符串</param>

///

<returns>字符串?dāng)?shù)組</returns>

public

static

string[]

GetStrArray(string

str)

{

return

str.Split(new

char[',']);

}

///

<summary>

///

將數(shù)組轉(zhuǎn)換為字符串

///

</summary>

///

<param

name="list">List</param>

///

<param

name="speater">分隔符</param>

///

<returns>String</returns>

public

static

string

GetArrayStr(List<string>

list,

string

speater)

{

StringBuilder

sb

=

new

StringBuilder();

for

(int

i

=

0;

i

<

list.Count;

i++)

{

if

(i

==

list.Count

-

1)

{

sb.Append(list[i]);

}

else

{

sb.Append(list[i]);

sb.Append(speater);

}

}

return

sb.ToString();

}

///

<summary>

///

object型轉(zhuǎn)換為bool型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的bool類型結(jié)果</returns>

public

static

bool

StrToBool(object

expression,

bool

defValue)

{

if

(expression

!=

null)

return

StrToBool(expression,

defValue);

return

defValue;

}

///

<summary>

///

string型轉(zhuǎn)換為bool型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的bool類型結(jié)果</returns>

public

static

bool

StrToBool(string

expression,

bool

defValue)

{

if

(expression

!=

null)

{

if

(string.Compare(expression,

"true",

true)

==

0)

return

true;

else

if

(string.Compare(expression,

"false",

true)

==

0)

return

false;

}

return

defValue;

}

///

<summary>

///

將對象轉(zhuǎn)換為Int32類型

///

</summary>

///

<param

name="expression">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

int

ObjToInt(object

expression,

int

defValue)

{

if

(expression

!=

null)

return

StrToInt(expression.ToString(),

defValue);

return

defValue;

}

///

<summary>

///

將字符串轉(zhuǎn)換為Int32類型

///

</summary>

///

<param

name="expression">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

int

StrToInt(string

expression,

int

defValue)

{

if

(string.IsNullOrEmpty(expression)

||

expression.Trim().Length

>=

11

||

!Regex.IsMatch(expression.Trim(),

@"^([-]|[0-9])[0-9]*(\.\w*)?$"))

return

defValue;

int

rv;

if

(Int32.TryParse(expression,

out

rv))

return

rv;

return

Convert.ToInt32(StrToFloat(expression,

defValue));

}

///

<summary>

///

Object型轉(zhuǎn)換為decimal型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的decimal類型結(jié)果</returns>

public

static

decimal

ObjToDecimal(object

expression,

decimal

defValue)

{

if

(expression

!=

null)

return

StrToDecimal(expression.ToString(),

defValue);

return

defValue;

}

///

<summary>

///

string型轉(zhuǎn)換為decimal型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的decimal類型結(jié)果</returns>

public

static

decimal

StrToDecimal(string

expression,

decimal

defValue)

{

if

((expression

==

null)

||

(expression.Length

>

10))

return

defValue;

decimal

intValue

=

defValue;

if

(expression

!=

null)

{

bool

IsDecimal

=

Regex.IsMatch(expression,

@"^([-]|[0-9])[0-9]*(\.\w*)?$");

if

(IsDecimal)

decimal.TryParse(expression,

out

intValue);

}

return

intValue;

}

///

<summary>

///

Object型轉(zhuǎn)換為float型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

float

ObjToFloat(object

expression,

float

defValue)

{

if

(expression

!=

null)

return

StrToFloat(expression.ToString(),

defValue);

return

defValue;

}

///

<summary>

///

string型轉(zhuǎn)換為float型

///

</summary>

///

<param

name="strValue">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

float

StrToFloat(string

expression,

float

defValue)

{

if

((expression

==

null)

||

(expression.Length

>

10))

return

defValue;

float

intValue

=

defValue;

if

(expression

!=

null)

{

bool

IsFloat

=

Regex.IsMatch(expression,

@"^([-]|[0-9])[0-9]*(\.\w*)?$");

if

(IsFloat)

float.TryParse(expression,

out

intValue);

}

return

intValue;

}

///

<summary>

///

將對象轉(zhuǎn)換為日期時間類型

///

</summary>

///

<param

name="str">要轉(zhuǎn)換的字符串</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

DateTime

StrToDateTime(string

str,

DateTime

defValue)

{

if

(!string.IsNullOrEmpty(str))

{

DateTime

dateTime;

if

(DateTime.TryParse(str,

out

dateTime))

return

dateTime;

}

return

defValue;

}

///

<summary>

///

將對象轉(zhuǎn)換為日期時間類型

///

</summary>

///

<param

name="str">要轉(zhuǎn)換的字符串</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

DateTime

StrToDateTime(string

str)

{

return

StrToDateTime(str,

DateTime.Now);

}

///

<summary>

///

將對象轉(zhuǎn)換為日期時間類型

///

</summary>

///

<param

name="obj">要轉(zhuǎn)換的對象</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

DateTime

ObjectToDateTime(object

obj)

{

return

StrToDateTime(obj.ToString());

}

///

<summary>

///

將對象轉(zhuǎn)換為日期時間類型

///

</summary>

///

<param

name="obj">要轉(zhuǎn)換的對象</param>

///

<param

name="defValue">缺省值</param>

///

<returns>轉(zhuǎn)換后的int類型結(jié)果</returns>

public

static

DateTime

ObjectToDateTime(object

obj,

DateTime

defValue)

{

return

StrToDateTime(obj.ToString(),

defValue);

}

///

<summary>

///

將對象轉(zhuǎn)換為字符串

///

</summary>

///

<param

name="obj">要轉(zhuǎn)換的對象</param>

///

<returns>轉(zhuǎn)換后的string類型結(jié)果</returns>

public

static

string

ObjectToStr(object

obj)

{

if

(obj

==

null)

return

"";

return

obj.ToString().Trim();

}

///

<summary>

///

判斷是否郵箱

///

</summary>

///

<param

name="expression"></param>

///

<returns></returns>

public

static

bool

IsEmail(string

expression)

{

return

Regex.IsMatch(expression,

@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

}

///

<summary>

///

判斷是否手機

///

</summary>

///

<param

name="expression"></param>

///

<returns></returns>

public

static

bool

IsMobile(string

expression)

{

return

Regex.IsMatch(expression,

@"^1[3|4|5|6|7|8|9][0-9]{9}$");

}

public

static

bool

IsPhone(string

telphone)

{

Regex

regex

=

new

Regex(@"^(\d{3,4}-)?\d{6,8}$");

return

regex.IsMatch(telphone);

}

#endregion

#region

分割字符串

///

<summary>

///

分割字符串

///

</summary>

public

static

string[]

SplitString(string

strContent,

string

strSplit)

{

if

(!string.IsNullOrEmpty(strContent))

{

if

(strContent.IndexOf(strSplit)

<

0)

return

new

string[]

{

strContent

};

return

Regex.Split(strContent,

Regex.Escape(strSplit),

RegexOptions.IgnoreCase);

}

else

return

new

string[0]

{

};

}

///

<summary>

///

分割字符串

///

</summary>

///

<returns></returns>

public

static

string[]

SplitString(string

strContent,

string

strSplit,

int

count)

{

string[]

result

=

new

string[count];

string[]

splited

=

SplitString(strContent,

strSplit);

for

(int

i

=

0;

i

<

count;

i++)

{

if

(i

<

splited.Length)

result[i]

=

splited[i];

else

result[i]

=

string.Empty;

}

return

result;

}

#endregion

#region

刪除最后結(jié)尾的一個逗號

///

<summary>

///

刪除最后結(jié)尾的一個逗號

///

</summary>

public

static

string

DelLastComma(string

str)

{

if

(str.Length

<

1)

{

return

"";

}

return

str.Substring(0,

str.LastIndexOf(","));

}

#endregion

#region

刪除最后結(jié)尾的指定字符后的字符

///

<summary>

///

刪除最后結(jié)尾的指定字符后的字符

///

</summary>

public

static

string

DelLastChar(string

str,

string

strchar)

{

if

(string.IsNullOrEmpty(str))

return

"";

if

(str.LastIndexOf(strchar)

>=

0

&&

str.LastIndexOf(strchar)

==

str.Length

-

1)

{

return

str.Substring(0,

str.LastIndexOf(strchar));

}

return

str;

}

#endregion

#region

生成指定長度的字符串

///

<summary>

///

生成指定長度的字符串,即生成strLong個str字符串

///

</summary>

///

<param

name="strLong">生成的長度</param>

///

<param

name="str">以str生成字符串</param>

///

<returns></returns>

public

static

string

StringOfChar(int

strLong,

string

str)

{

string

ReturnStr

=

"";

for

(int

i

=

0;

i

<

strLong;

i++)

{

ReturnStr

+=

str;

}

return

ReturnStr;

}

#endregion

#region

生成日期隨機碼

///

<summary>

///

生成日期隨機碼

///

</summary>

///

<returns></returns>

public

static

string

GetRamCode()

{

#region

return

DateTime.Now.ToString("yyyyMMddHHmmssffff");

#endregion

}

#endregion

#region

生成隨機字母或數(shù)字

///

<summary>

///

生成隨機數(shù)字

///

</summary>

///

<param

name="length">生成長度</param>

///

<returns></returns>

public

static

string

Number(int

Length)

{

return

Number(Length,

false);

}

///

<summary>

///

生成隨機數(shù)字

///

</summary>

///

<param

name="Length">生成長度</param>

///

<param

name="Sleep">是否要在生成前將當(dāng)前線程阻止以避免重復(fù)</param>

///

<returns></returns>

public

static

string

Number(int

Length,

bool

Sleep)

{

if

(Sleep)

System.Threading.Thread.Sleep(3);

string

result

=

"";

System.Random

random

=

new

Random();

for

(int

i

=

0;

i

<

Length;

i++)

{

result

+=

random.Next(10).ToString();

}

return

result;

}

///

<summary>

///

生成隨機字母字符串(數(shù)字字母混和)

///

</summary>

///

<param

name="codeCount">待生成的位數(shù)</param>

public

static

string

GetCheckCode(int

codeCount)

{

string

str

=

string.Empty;

int

rep

=

0;

long

num2

=

DateTime.Now.Ticks

+

rep;

rep++;

Random

random

=

new

Random(((int)(((ulong)num2)

&

0xffffffffL))

|

((int)(num2

>>

rep)));

for

(int

i

=

0;

i

<

codeCount;

i++)

{

char

ch;

int

num

=

random.Next();

if

((num

%

2)

==

0)

{

ch

=

(char)(0x30

+

((ushort)(num

%

10)));

}

else

{

ch

=

(char)(0x41

+

((ushort)(num

%

0x1a)));

}

str

=

str

+

ch.ToString();

}

return

str;

}

///

<summary>

///

根據(jù)日期和隨機碼生成訂單號

///

</summary>

///

<returns></returns>

public

static

string

GetOrderNumber()

{

string

num

=

DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms

return

num

+

Number(2).ToString();

}

private

static

int

Next(int

numSeeds,

int

length)

{

byte[]

buffer

=

new

byte[length];

System.Security.Cryptography.RNGCryptoServiceProvider

Gen

=

new

System.Security.Cryptography.RNGCryptoServiceProvider();

Gen.GetBytes(buffer);

uint

randomResult

=

0x0;//這里用uint作為生成的隨機數(shù)

for

(int

i

=

0;

i

<

length;

i++)

{

randomResult

|=

((uint)buffer[i]

<<

((length

-

1

-

i)

*

8));

}

return

(int)(randomResult

%

numSeeds);

}

#endregion

#region

截取字符長度

///

<summary>

///

截取字符長度

///

</summary>

///

<param

name="inputString">字符</param>

///

<param

name="len">長度</param>

///

<returns></returns>

public

static

string

CutString(string

inputString,

int

len)

{

if

(string.IsNullOrEmpty(inputString))

return

"";

inputString

=

DropHTML(inputString);

ASCIIEncoding

ascii

=

new

ASCIIEncoding();

int

tempLen

=

0;

string

tempString

=

"";

byte[]

s

=

ascii.GetBytes(inputString);

for

(int

i

=

0;

i

<

s.Length;

i++)

{

if

((int)s[i]

==

63)

{

tempLen

+=

2;

}

else

{

tempLen

+=

1;

}

try

{

tempString

+=

inputString.Substring(i,

1);

}

catch

{

break;

}

if

(tempLen

>

len)

break;

}

//如果截過則加上半個省略號

byte[]

mybyte

=

System.Text.Encoding.Default.GetBytes(inputString);

if

(mybyte.Length

>

len)

tempString

+=

"…";

return

tempString;

}

#endregion

#region

清除HTML標(biāo)記

public

static

string

DropHTML(string

Htmlstring)

{

if

(string.IsNullOrEmpty(Htmlstring))

return

"";

//刪除腳本

Htmlstring

=

Regex.Replace(Htmlstring,

@"<script[^>]*?>.*?</script>",

"",

RegexOptions.IgnoreCase);

//刪除HTML

Htmlstring

=

Regex.Replace(Htmlstring,

@"<(.[^>]*)>",

"",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"([\r\n])[\s]+",

"",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"-->",

"",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"<!--.*",

"",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(quot|#34);",

"\"",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(amp|#38);",

"&",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(lt|#60);",

"<",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(gt|#62);",

">",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(nbsp|#160);",

"

",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(iexcl|#161);",

"\xa1",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(cent|#162);",

"\xa2",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(pound|#163);",

"\xa3",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"&(copy|#169);",

"\xa9",

RegexOptions.IgnoreCase);

Htmlstring

=

Regex.Replace(Htmlstring,

@"(\d+);",

"",

RegexOptions.IgnoreCase);

Htmlstring.Replace("<",

"");

Htmlstring.Replace(">",

"");

Htmlstring.Replace("\r\n",

"");

Htmlstring

=

HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

return

Htmlstring;

}

#endregion

#region

清除HTML標(biāo)記且返回相應(yīng)的長度

public

static

string

DropHTML(string

Htmlstring,

int

strLen)

{

return

CutString(DropHTML(Htmlstring),

strLen);

}

#endregion

#region

TXT代碼轉(zhuǎn)換成HTML格式

///

<summary>

///

字符串字符處理

///

</summary>

///

<param

name="chr">等待處理的字符串</param>

///

<returns>處理后的字符串</returns>

///

//把TXT代碼轉(zhuǎn)換成HTML格式

public

static

String

ToHtml(string

Input)

{

StringBuilder

sb

=

new

StringBuilder(Input);

sb.Replace("&",

"&");

sb.Replace("<",

"<");

sb.Replace(">",

">");

sb.Replace("\r\n",

"<br

/>");

sb.Replace("\n",

"<br

/>");

sb.Replace("\t",

"

");

//sb.Replace("

",

"

");

return

sb.ToString();

}

#endregion

#region

HTML代碼轉(zhuǎn)換成TXT格式

///

<summary>

///

字符串字符處理

///

</summary>

///

<param

name="chr">等待處理的字符串</param>

///

<returns>處理后的字符串</returns>

///

//把HTML代碼轉(zhuǎn)換成TXT格式

public

static

String

ToTxt(String

Input)

{

StringBuilder

sb

=

new

StringBuilder(Input);

sb.Replace("

",

"

");

sb.Replace("<br>",

"\r\n");

sb.Replace("<br>",

"\n");

sb.Replace("<br

/>",

"\n");

sb.Replace("<br

/>",

"\r\n");

sb.Replace("<",

"<");

sb.Replace(">",

">");

sb.Replace("&",

"&");

return

sb.ToString();

}

#endregion

#region

檢測是否有Sql危險字符

///

<summary>

///

檢測是否有Sql危險字符

///

</summary>

///

<param

name="str">要判斷字符串</param>

///

<returns>判斷結(jié)果</returns>

public

static

bool

IsSafeSqlString(string

str)

{

return

!Regex.IsMatch(str,

@"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");

}

///

<summary>

///

檢查危險字符

///

</summary>

///

<param

name="Input"></param>

///

<returns></returns>

public

static

string

Filter(string

sInput)

{

if

(sInput

==

null

||

sInput

==

"")

return

null;

string

sInput1

=

sInput.ToLower();

strin

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論