在开发小程序微信支付的时候,如何调起小程序直接发起支付,是许多开发者困扰的问题,今天笔者把整个接口代码归纳如下,希望对你所有帮助:
源代码如下:
#region 创建统一订单接口 yefei 2022-10-09
/// <summary>
/// 创建统一订单接口 yefei 2022-10-09
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[HttpPost]
public HttpResponseMessage CreateUnifiedOrder(object data)
{
HttpResponseMessage result = null;
var ReturnStr = "{\"status\":\"N\",\"msg\":\"参数错误\"}";
string Sdata = data.ToString();
var admin = JsonConvert.DeserializeObject<dynamic>(Sdata);//动态对象
decimal subsidiary_id = 0;
decimal ufx_userid = 0;
string openid = null;
string ordertime = null;
string appid = System.Web.Configuration.WebConfigurationManager.AppSettings["small_appid3"].ToString();
string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["small_secret3"].ToString();
string key = System.Web.Configuration.WebConfigurationManager.AppSettings["wx_key3"].ToString();
string mch_id = System.Web.Configuration.WebConfigurationManager.AppSettings["wx_mch_id3"].ToString();
string ip = "219.234.87.16";
string PayResulturl = System.Web.Configuration.WebConfigurationManager.AppSettings["wxpay_notifyurl3"].ToString();
string aa = "购票通商城";
string strcode = aa;
byte[] buffer = Encoding.UTF8.GetBytes(strcode);
string body = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
string roomid = null; //商户订单号
string totalfee =null; //订单总金额
WisdomStarts.Common.Log.NetLog.WriteTextLog("请求了该接口:", "CreateUnifiedOrder");
if (admin.subsidiary_id != null)
{
subsidiary_id = admin.subsidiary_id;
}
if (admin.ufx_userid != null)
{
ufx_userid = admin.ufx_userid;
}
if (admin.openid != null)
{
openid = admin.openid;
}
if (admin.ordertime != null)
{
ordertime = admin.ordertime;
}
if (admin.roomid != null)
{
roomid = admin.roomid;
}
if (admin.totalfee != null)
{
totalfee = admin.totalfee;
}
if (subsidiary_id <= 0)
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"公司ID不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else if (ufx_userid <= 0)
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"分销用户ID不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else if (string.IsNullOrEmpty(openid))
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"openid不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else if (string.IsNullOrEmpty(ordertime))
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"订单时间不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else if (string.IsNullOrEmpty(roomid))
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"订单号不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else if (string.IsNullOrEmpty(totalfee))
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"订单金额不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
else
{
string Token = admin.Token;
#region 验证token
if (!string.IsNullOrEmpty(Token))
{
int t = new WisdomStars.Bll.Api.Common().PUB_VerificationToken(Token);
if (t <= 0)
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"登录失效\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
}
else
{
ReturnStr = "{\"result\":\"" + (int)KeyEnum.AppReturn.失败 + "\",\"msg\":\"token不能为空\",\"data\":\"\"}";
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
#endregion 验证token
if (subsidiary_id > 0 && ufx_userid > 0 && !string.IsNullOrEmpty(roomid) && !string.IsNullOrEmpty(totalfee))
{
var dic = new Dictionary<string, string>
{
{"appid", appid},
{"mch_id", mch_id},
{"nonce_str", GetRandomString(20)/*Random.Next().ToString()*/},
{"body",body},
{"out_trade_no",roomid},//商户自己的订单号码
{"total_fee",totalfee}, //正式
// {"total_fee","0.01"}, //测试
{"spbill_create_ip",ip},//服务器的IP地址
{"notify_url",PayResulturl},//异步通知的地址,不能带参数
{"trade_type","JSAPI" },
{"openid",openid}
};
//加入签名
dic.Add("sign", GetSignString(dic));
var sb = new StringBuilder();
sb.Append("<xml>");
foreach (var d in dic)
{
sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
}
sb.Append("</xml>");
var xml = new XmlDocument();
// xml.LoadXml(GetPostString("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.ToString()));
CookieCollection coo = new CookieCollection();
Encoding en = Encoding.GetEncoding("UTF-8");
HttpWebResponse response = CreatePostHttpResponse("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.ToString(), en);
//打印返回值
Stream stream = response.GetResponseStream(); //获取响应的字符串流
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
string html = sr.ReadToEnd(); //从头读到尾,放到字符串html
//Console.WriteLine(html);
//context.Response.Write(html);
//context.Response.End();
xml.LoadXml(html);
//对请求返回值 进行处理
var root = xml.DocumentElement;
DataSet ds = new DataSet();
StringReader stram = new StringReader(html);
XmlTextReader reader = new XmlTextReader(stram);
ds.ReadXml(reader);
string return_code = ds.Tables[0].Rows[0]["return_code"].ToString();
if (return_code.ToUpper() == "SUCCESS")
{
//通信成功
string result_code = ds.Tables[0].Rows[0]["result_code"].ToString();//业务结果
if (result_code.ToUpper() == "SUCCESS")
{
var res = new Dictionary<string, string>
{
{"appId", appid},
{"timeStamp", GetTimeStamp()},
{"nonceStr", dic["nonce_str"]},
// {"package", "prepay_id="+ds.Tables[0].Rows[0]["prepay_id"].ToString()},
{"prepay_id", ds.Tables[0].Rows[0]["prepay_id"].ToString()},
{"signType", "MD5"}
};
//在服务器上签名
res.Add("paySign", GetSignString(res));
//string str = ToUrlParams(data.GetValues());//转换为URL串
//string url = "weixin://wxpay/bizpayurl?" + str;
// string signapp = res.ToString();
string signapp = JsonConvert.SerializeObject(res);
ReturnStr = "{\"status\":\"Y\",\"msg\":\"操作成功\",\"signapp\":" + signapp.ToString() + "}";
// context.Response.Write(signapp);
}
}
else
{
ReturnStr = "{\"status\":\"N\",\"msg\":\"操作失败\",\"signapp\":\"0\"}";
}}
}
result = new HttpResponseMessage { Content = new StringContent(ReturnStr, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
#endregion 创建统一订单接口
二、请求参数:
{
"ufx_userid": "1",
"subsidiary_id": "10101537340017385406464",
"openid": "o55tG43Akb_yKS9MeXx8YOJJoqcw",
"ordertime": "2022-10-09 11:20",
"roomid": "509066274693557314636085",
"totalfee": "100",
"Token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VyTmFtZSI6IjEzOTAxMDQxNDcwIiwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTA5LTI2VDE2OjA2OjUwLjM4MjEyNzIrMDg6MDAiLCJUb2tlblR5cGUiOjR9.ZyiePFdekxmxr5BaY0atBAtmR8TSI8uStUtEZwbTpn4"
}
三、返回结果
{
"status": "Y",
"msg": "操作成功",
"signapp": {
"appId": "wx03fba3a77d0010ae",
"timeStamp": "1665295210",
"nonceStr": "ATUB8BGYOU83MLDVYNRG",
"prepay_id": "wx091359540853450ba8b9044ca84ac80000",
"signType": "MD5",
"paySign": "AA45E8D32B55E6BBE72F77D8588491B3"
}
}
本文暂时没有评论,来添加一个吧(●'◡'●)