您好,登錄后才能下訂單哦!
后臺
public ActionResult WxAddVoucher_Center(double money)
{
int money= int.Parse((money * 100).ToString());
String ip = Request.UserHostAddress;
//隨機商品ID
String id = "";
Random rd = new Random();
for (int i = 1; i < 16; i++)
{
id += (rd.Next(0, 9)).ToString();
}
PayMent pm=new PayMent();
String WeixinAPI = pm.JSAPIPayMent("商品描述", openid, ip, money, id);
return Content(WeixinAPI);
}
配置微信支付的必須參數
public class Wxconfig{
public const string appid = "";//公眾號ID
public const string secret = "";//微信公眾號的secret
public const string url = "";//回調url
public const string mch_id = "";//商戶號
public const string paysignkey = "";//證書密匙
}
// 定義返回JSON數據類型的微信支付方法
public class PayMent
/// <summary>
/// 微信支付
/// </summary>
/// <param name="boby">商品描述</param>
/// <param name="mch_id">商戶號</param>
/// <param name="openid">用戶openid</param>
/// <param name="spbill_create_ip">終端IP</param>
/// <param name="total_fee">金額</param>
/// <param name="out_trade_no">商戶訂單號</param>
/// <returns></returns>
public String JSAPIPayMent( string boby, string openid, string spbill_create_ip, int total_fee, string out_trade_no)
{
UnifiedOrder order = new UnifiedOrder();
order.appid = WXconfig.appid;
order.attach = "vinson";
order.body = boby;
order.device_info = "";
order.mch_id = WXconfig.mch_id;
order.nonce_str = TenpayUtil.getNoncestr();
order.notify_url = WXconfig.url;
order.openid = openid;
order.out_trade_no = out_trade_no;
order.trade_type = "JSAPI";
order.spbill_create_ip = spbill_create_ip;
order.total_fee = total_fee;
TenpayUtil tenpay = new TenpayUtil();
string paySignKey = WXconfig.paysignkey;
string prepay_id = tenpay.getPrepay_id(order, paySignKey);
string timeStamp = TenpayUtil.getTimestamp();
string nonceStr = TenpayUtil.getNoncestr();
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
sParams.Add("appId", WXconfig.appid);
sParams.Add("timeStamp", timeStamp);
sParams.Add("nonceStr", nonceStr);
sParams.Add("package", "prepay_id=" + prepay_id);
sParams.Add("signType", "MD5");
string paySign = tenpay.getsign(sParams, paySignKey);
string package = "prepay_id=" + prepay_id;
return MD5Util.toJson(WXconfig.appid, timeStamp, nonceStr, package, "MD5", paySign);
}
}
//-------TenpayUtil類
public class TenpayUtil
{
/// <summary>
/// 統一支付接口
/// </summary>
const string UnifiedPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/// <summary>
/// 隨機串
/// </summary>
public static string getNoncestr()
{
Random random = new Random();
return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK").ToLower().Replace("s", "S");
}
/// <summary>
/// 時間截,自1970年以來的秒數
/// </summary>
public static string getTimestamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// 獲取微信簽名
/// </summary>
/// <param name="sParams"></param>
/// <returns></returns>
public string getsign(SortedDictionary<string, object> sParams, string key)
{
int i = 0;
string sign = string.Empty;
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, object> temp in sParams)
{
if (temp.Value.ToString() == "" || temp.Value == null || temp.Key.ToLower() == "sign")
{
continue;
}
i++;
sb.Append(temp.Key.Trim() + "=" + temp.Value.ToString() + "&");
}
sb.Append("key=" + key.Trim() + "");
string signkey = sb.ToString();
sign = MD5Util.GetMD5(signkey, "utf-8");
//utf-8
return sign;
}
/// <summary>
/// post數據到指定接口并返回數據
/// </summary>
public string PostXmlToUrl(string url, string postData)
{
string returnmsg = "";
//Byte[] temp = Encoding.UTF8.GetBytes(postData);
//string dataGBK = Encoding.GetEncoding("GBK").GetString(temp);
using (System.Net.WebClient wc = new System.Net.WebClient())
{
returnmsg = wc.UploadString(url, "POST", postData);
}
return returnmsg;
}
/// <summary>
/// 獲取prepay_id
/// </summary>
public string getPrepay_id(UnifiedOrder order, string key)
{
string prepay_id = "";
string post_data = getUnifiedOrderXml(order, key);
string request_data = PostXmlToUrl(UnifiedPayUrl, post_data);
//Log.WriteLog1(request_data);
SortedDictionary<string, object> requestXML = GetInfoFromXml(request_data);
foreach (KeyValuePair<string, object> k in requestXML)
{
if (k.Key == "prepay_id")
{
prepay_id = k.Value.ToString();
break;
}
}
return prepay_id;
}
/// <summary>
/// 把XML數據轉換為SortedDictionary<string, string>集合
/// </summary>
/// <param name="strxml"></param>
/// <returns></returns>
protected SortedDictionary<string, object> GetInfoFromXml(string xmlstring)
{
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);
XmlElement root = doc.DocumentElement;
int len = root.ChildNodes.Count;
for (int i = 0; i < len; i++)
{
string name = root.ChildNodes[i].Name;
if (!sParams.ContainsKey(name))
{
sParams.Add(name.Trim(), root.ChildNodes[i].InnerText.Trim());
}
}
}
catch { }
return sParams;
}
/// <summary>
/// 微信統一下單接口xml參數整理
/// </summary>
/// <param name="order">微信支付參數實例</param>
/// <param name="key">密鑰</param>
/// <returns></returns>
protected string getUnifiedOrderXml(UnifiedOrder order, string key)
{
string return_string = string.Empty;
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
sParams.Add("appid", order.appid);
sParams.Add("attach", order.attach);
sParams.Add("body", order.body);
sParams.Add("device_info", order.device_info);
sParams.Add("mch_id", order.mch_id);
sParams.Add("nonce_str", order.nonce_str);
sParams.Add("notify_url", order.notify_url);
sParams.Add("openid", order.openid);
sParams.Add("out_trade_no", order.out_trade_no);
sParams.Add("spbill_create_ip", order.spbill_create_ip);
sParams.Add("total_fee", order.total_fee);
sParams.Add("trade_type", order.trade_type);
order.sign = getsign(sParams, key);
sParams.Add("sign", order.sign);
//拼接成XML請求數據
StringBuilder sbPay = new StringBuilder();
foreach (KeyValuePair<string, object> k in sParams)
{
if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
{
sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
}
else
{
sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
}
}
return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
Byte[] temp = Encoding.UTF8.GetBytes(return_string);
string dataGBK = Encoding.GetEncoding("utf-8").GetString(temp);
return return_string;
// GBK
}
}
//---微信統一接口請求實體對象
/// <summary>
/// 微信統一接口請求實體對象
/// </summary>
[Serializable]
public class UnifiedOrder
{
/// <summary>
/// 公眾號ID(微信分配的公眾賬號 ID)
/// </summary>
public string appid = "";
/// <summary>
/// 商戶號(微信支付分配的商戶號)
/// </summary>
public string mch_id = "";
/// <summary>
/// 微信支付分配的終端設備號
/// </summary>
public string device_info = "";
/// <summary>
/// 隨機字符串,不長于 32 位
/// </summary>
public string nonce_str = "";
/// <summary>
/// 簽名
/// </summary>
public string sign = "";
/// <summary>
/// 商品描述
/// </summary>
public string body = "";
/// <summary>
/// 附加數據,原樣返回
/// </summary>
public string attach = "";
/// <summary>
/// 商戶系統內部的訂單號,32個字符內、可包含字母,確保在商戶系統唯一,詳細說明
/// </summary>
public string out_trade_no = "";
/// <summary>
/// 訂單總金額,單位為分,不能帶小數點
/// </summary>
public int total_fee = 0;
/// <summary>
/// 終端IP
/// </summary>
public string spbill_create_ip = "";
/// <summary>
/// 訂 單 生 成 時 間 , 格 式 為yyyyMMddHHmmss,如 2009 年12 月 25 日 9 點 10 分 10 秒表示為 20091225091010。時區為 GMT+8 beijing。該時間取自商戶服務器
/// </summary>
public string time_start = "";
/// <summary>
/// 交易結束時間
/// </summary>
public string time_expire = "";
/// <summary>
/// 商品標記 商品標記,該字段不能隨便填,不使用請填空,使用說明詳見第 5 節
/// </summary>
public string goods_tag = "";
/// <summary>
/// 接收微信支付成功通知
/// </summary>
public string notify_url = "";
/// <summary>
/// JSAPI、NATIVE、APP
/// </summary>
public string trade_type = "";
/// <summary>
/// 用戶標識 trade_type 為 JSAPI時,此參數必傳
/// </summary>
public string openid = "";
/// <summary>
/// 只在 trade_type 為 NATIVE時需要填寫。
/// </summary>
public string product_id = "";
}
// 轉JSon對象
/// <summary>
/// json
/// </summary>
/// <returns></returns>
public static String toJson(string appId, string timeStamp, string nonceStr, string packageA, string signType, string paySign)
{
String json = "{";
json += "\"appId\":" + "\"" + appId + "\",";
json += "\"timeStamp\":" + "\"" + timeStamp + "\",";
json += "\"nonceStr\":" + "\"" + nonceStr + "\",";
json += "\"package\":" + "\"" + packageA + "\",";
json += "\"signType\":" + "\"" + signType + "\",";
json += "\"paySign\":" + "\"" + paySign + "\"";
json += "}";
return json;
}
前端代碼
<input id="btn" type="button" value="充值"/>
<script>
$("#btn").click(function () {
$.get(url,data, function (t) {//其中url是后臺地址,data是金額
var r = $.parseJSON(t);
callpay(r);
}
})
//支付功能
function jsApiCall(r) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', r,
function (res) {
//alert(res.err_code + res.err_desc);
//alert(res.err_msg);
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert(”支付成功”);
} else {
alert("交易取消");
}
}
);
}
function callpay(r) {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
} else {
jsApiCall(r);
}
}
</script>
項目地址:https://gitee.com/qq-w/wechat.git
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。