发布:2022/8/21 22:36:13作者:管理员 来源:本站 浏览次数:1238
需求:自助机调用接口生成二维码,用户扫描二维码付款后,回调方法里写入到数据库,自助机轮询查数据库判断用户是否付款。
using bk.Services.Log;
using bk.web.Common.Alipay;
using bk.web.Common.Weixin;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Com.Alipay;
using Com.Alipay.Business;
using Com.Alipay.Domain;
using Com.Alipay.Model;
using System;
using bk.web.Models;
using bk.Core.Domain;
using System.IO;
using bk.Core;
using bk.Services.Admin;
using System.Threading.Tasks;
using bk.Core.Infrastructure;
using System.Linq;
using System.Configuration;
namespace bk.web.Controllers
{
public class PayNotifyController : Controller
{
private readonly IAgent_User_ImgService _userService;
private readonly IAgentOperationPayService _payService;
private readonly IAgentOperationService _operateService;
private readonly IAgentDevice_PayService _amountService;
public PayNotifyController(
IAgent_User_ImgService userService,
IAgentOperationPayService payService,
IAgentOperationService operateService,
IAgentDevice_PayService amountService)
{
this._userService = userService;
_payService = payService;
_operateService = operateService;
_amountService = amountService;
}
// GET: PayNotify
public ActionResult Index()
{
return View();
}
#region 微信支付回调
/// <summary>
/// 支付结果通知回调处理类
/// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给微信支付后台
/// </summary>
public void wxNotify()
{
Log.Info(this.GetType().ToString(), "微信支付回调开始");
WxPayData notifyData = GetNotifyData();
//检查支付结果中transaction_id是否存在
if (!notifyData.IsSet("transaction_id"))
{
//若transaction_id不存在,则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "支付结果中微信订单号不存在");
Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
Response.Write(res.ToXml());
Response.End();
}
string transaction_id = notifyData.GetValue("transaction_id").ToString();
//查询订单,判断订单真实性
if (!QueryOrder(transaction_id))
{
//若订单查询失败,则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "订单查询失败");
Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
Response.Write(res.ToXml());
Response.End();
}
//查询订单成功
else
{
//更新数据库
//WriteLog.Debug("notifyData begin:");
//var dicValue = notifyData.GetValues();
//foreach (var item in dicValue)
//{
// WriteLog.Debug(item.Key + " : " + item.Value);
//}
//WriteLog.Debug("notifyData end;");
string out_trade_no = notifyData.GetValue("out_trade_no").ToString();
UpdatePayData(1, out_trade_no, transaction_id);
WxPayData res = new WxPayData();
res.SetValue("return_code", "SUCCESS");
res.SetValue("return_msg", "OK");
Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
Response.Write(res.ToXml());
Response.End();
}
}
private void UpdatePayData(int payType, string out_trade_no, string transaction_id)
{
//更新AgentOperationPay
M_AgentOperationPay m = _payService.GetByOrderNo(out_trade_no);
if (m == null)
{
}
else
{
m.SerialNo = transaction_id;
m.Payment = payType;
m.PayStatus = 1;
_payService.Update(m);
//更新AgentOperation
M_AgentOperation om = _operateService.GetByOperationNo(m.OperationNo);
om.Status = 1;
_operateService.Update(om);
}
}
/// <summary>
/// 接收从微信支付后台发送过来的数据并验证签名
/// </summary>
/// <returns>微信支付后台返回的数据</returns>
public WxPayData GetNotifyData()
{
//接收从微信后台POST过来的数据
System.IO.Stream s = Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
s.Flush();
s.Close();
s.Dispose();
WriteLog.Debug("Receive data from WeChat : " + builder.ToString());
//转换数据格式并验证签名
WxPayData data = new WxPayData();
try
{
data.FromXml(builder.ToString());
}
catch (WxPayException ex)
{
//若签名错误,则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", ex.Message);
WriteLog.Debug("Sign check error : " + res.ToXml());
Response.Write(res.ToXml());
Response.End();
}
WriteLog.Debug("Check sign success");
return data;
}
//查询订单
private bool QueryOrder(string transaction_id)
{
WxPayData req = new WxPayData();
req.SetValue("transaction_id", transaction_id);
WxPayData res = WxPayApi.OrderQuery(req);
if (res.GetValue("return_code").ToString() == "SUCCESS" &&
res.GetValue("result_code").ToString() == "SUCCESS")
{
return true;
}
else
{
return false;
}
}
#endregion
#region 支付宝回调
public void aliNotify()
{
WriteLog.Debug("支付宝回调开始");
WriteLog.Debug("aliNotify : begin");
SortedDictionary<string, string> sPara = GetRequestPost();
if (sPara.Count > 0)//判断是否有带返回参数
{
//Notify aliNotify = new Notify();
Com.Alipay.Notify aliNotify = new Com.Alipay.Notify(Config.charset, Config.sign_type, Config.pid, Config.mapiUrl, Config.alipay_public_key);
//对异步通知进行验签
bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);
//对验签结果
//bool isSign = Aop.Api.Util.AlipaySignature.RSACheckV2(sPara, Config.alipay_public_key ,Config.charset,Config.sign_type,false );
if (verifyResult && CheckParams()) //验签成功 && 关键业务参数校验成功
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代码
//——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
//获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表
//商户订单号
string out_trade_no = Request.Form["out_trade_no"];
//支付宝交易号
string trade_no = Request.Form["trade_no"];
//交易状态
//在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。
string trade_status = Request.Form["trade_status"];
//更新数据库
if (trade_status == "TRADE_SUCCESS" || trade_status == "TRADE_FINISHED")
{
UpdatePayData(2, out_trade_no, trade_no);
}
//判断是否在商户网站中已经做过了这次通知返回的处理
//如果没有做过处理,那么执行商户的业务程序
//如果有做过处理,那么不执行商户的业务程序
WriteLog.Debug("aliNotify : success");
Response.Write("success"); //请不要修改或删除
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else//验证失败
{
WriteLog.Debug("aliNotify : fail");
Response.Write("fail");
}
}
else
{
WriteLog.Debug("aliNotify : 无通知参数");
Response.Write("无通知参数");
}
}
/// <summary>
/// 获取支付宝POST过来通知消息,并以“参数名=参数值”的形式组成数组
/// </summary>
/// <returns>request回来的信息组成的数组</returns>
public SortedDictionary<string, string> GetRequestPost()
{
int i = 0;
SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
NameValueCollection coll;
//Load Form variables into NameValueCollection variable.
coll = Request.Form;
// Get names of all forms into a string array.
string[] requestItem = coll.AllKeys;
for (i = 0; i < requestItem.Length; i++)
{
sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
WriteLog.Debug("aliNotify : GetRequestPost, key="+ requestItem[i] + ",value="+ Request.Form[requestItem[i]]);
}
return sArray;
}
/// <summary>
/// 对支付宝异步通知的关键参数进行校验
/// </summary>
/// <returns></returns>
private bool CheckParams()
{
bool ret = true;
//获得商户订单号out_trade_no
string out_trade_no = Request.Form["out_trade_no"];
//TODO 商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,
//获得支付总金额total_amount
string total_amount = Request.Form["total_amount"];
//TODO 判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
//获得卖家账号seller_email
string seller_email = Request.Form["seller_email"];
//TODO 校验通知中的seller_email(或者seller_id) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id / seller_email)
//获得调用方的appid;
//如果是非授权模式,appid是商户的appid;如果是授权模式(token调用),appid是系统商的appid
string app_id = Request.Form["app_id"];
//TODO 验证app_id是否是调用方的appid;。
//验证上述四个参数,完全吻合则返回参数校验成功
return ret;
}
#endregion
#region 微信、支付宝生成二维码url
public JsonResult GetWxAliCodeUrl(WxAliPayRequestOnlyUrl req)
{
WriteLog.Debug("计时:开始时间=" + DateTime.Now.ToString());
WxAliPayResponse result = new WxAliPayResponse();
#region 业务参数判断 和 签名判断--占不加业务
//bool have_err = false;
//string err_msg = "缺少参数:";
//if (req == null)
//{
// result.Code = "1000";
// result.Msg = "传入参数为空";
// return Json(result);
//}
//if (string.IsNullOrEmpty(req.file_name))
//{
// have_err = true;
// err_msg += "文件名称不能为空";
//}
//if (string.IsNullOrEmpty(req.sign))
//{
// have_err = true;
// err_msg += "、签名不能为空";
//}
//if (string.IsNullOrEmpty(req.avatar))
//{
// have_err = true;
// err_msg += "、照片不能为空";
//}
//if (req.time_stamp <= 0)
//{
// have_err = true;
// err_msg += "、请传入正确的时间戳格式";
//}
//if (string.IsNullOrEmpty(req.SFZMHM))
//{
// have_err = true;
// err_msg += "身份证明号码不能为空";
//}
//if (string.IsNullOrEmpty(req.SFZMMC))
//{
// have_err = true;
// err_msg += "身份证明名称不能为空";
//}
//if (string.IsNullOrEmpty(req.SFZMLX))
//{
// have_err = true;
// err_msg += "身份证明类型不能为空";
//}
//if (req.Img_Type != 1 && req.Img_Type != 2 && req.Img_Type != 3)
//{
// have_err = true;
// err_msg += "照片类型格式不正确";
//}
//if (string.IsNullOrEmpty(req.OperationNo))
//{
// have_err = true;
// err_msg += "操作编号不能为空";
//}
//if (have_err)
//{
// //commonHelper.write_log("1001图片接口上传失败", err_msg);
// result.Code = "1001";
// result.Msg = err_msg;
// return Json(result);
//}
//string strtime_stamp = ConfigurationManager.AppSettings["time_stamp"];
//int intTimeStampCfg = 600;
//int.TryParse(strtime_stamp, out intTimeStampCfg);
//if (Math.Abs(CommonHelper.GetCurrentTimeStamp() - req.time_stamp) > intTimeStampCfg)
//{
// //commonHelper.write_log("1002图片接口上传失败", "请求过期----当前时间:" + commonHelper.GetCurrentTimeStamp() + "------传入时间:" + model.time_stamp);
// result.Code = "1002";
// result.Msg = "请求过期";
// return Json(result);
//}
//string api_user_key = ConfigurationManager.AppSettings["upload_img_key"];
//string mysign = string.Format("apikey={0}&time_stamp={1}&file_name={2}&operationNo={3}", api_user_key, req.time_stamp, req.file_name, req.OperationNo);
//mysign = CommonHelper.MD5Encrypt(mysign, 32);
//mysign = mysign.ToLower();
//WriteLog.Debug("GetWxAliCodeUrl: mysign="+ mysign + ", 签名参数sign="+ req.sign.ToLower());
//if (req.sign.ToLower() != mysign)
//{
// //commonHelper.write_log("1003图片接口上传失败", "签名不匹配----传入的签名:" + model.sign.ToLower() + "------正确的签名:" + mysign);
// result.Code = "1003";
// result.Msg = "签名不匹配";
// return Json(result);
//}
//WriteLog.Debug("业务参数判断 和 签名判断 成功");
#endregion
#region 判断参数
if (req == null)
{
result.Code = "1000";
result.Msg = "传入参数为空";
return Json(result);
}
if (string.IsNullOrEmpty(req.deviceNo))
{
result.Code = "1001";
result.Msg = "设备号不能为空";
return Json(result);
}
if (string.IsNullOrEmpty(req.busyCode))
{
result.Code = "1002";
result.Msg = "业务编号不能为空";
return Json(result);
}
if (string.IsNullOrEmpty(req.OperationNo))
{
result.Code = "1003";
result.Msg = "操作编号不能为空";
return Json(result);
}
if (string.IsNullOrEmpty(req.sign))
{
result.Code = "1004";
result.Msg = "签名不能为空";
return Json(result);
}
if (req.time_stamp <= 0)
{
result.Code = "1005";
result.Msg = "请传入正确的时间戳格式";
return Json(result);
}
string strtime_stamp = ConfigurationManager.AppSettings["time_stamp"];
int intTimeStampCfg = 600;
int.TryParse(strtime_stamp, out intTimeStampCfg);
if (Math.Abs(CommonHelper.GetCurrentTimeStamp() - req.time_stamp) > intTimeStampCfg)
{
//commonHelper.write_log("1002图片接口上传失败", "请求过期----当前时间:" + commonHelper.GetCurrentTimeStamp() + "------传入时间:" + model.time_stamp);
result.Code = "1006";
result.Msg = "请求过期";
return Json(result);
}
string api_user_key = ConfigurationManager.AppSettings["upload_img_key"];
string mysign = string.Format("apikey={0}&deviceNo={1}&busyCode={2}&OperationNo={3}&time_stamp={4}", api_user_key, req.deviceNo, req.busyCode, req.OperationNo, req.time_stamp);
mysign = CommonHelper.MD5Encrypt(mysign, 32);
mysign = mysign.ToLower();
if (!req.sign.ToLower().Equals(mysign))
{
//commonHelper.write_log("1003图片接口上传失败", "签名不匹配----传入的签名:" + model.sign.ToLower() + "------正确的签名:" + mysign);
result.Code = "1007";
result.Msg = "签名不匹配";
return Json(result);
}
#endregion
string WxCode = "", WxCodeUrl = "", AliCodeUrl = "", AliCode = "", Str_Out_trade_no = "";
//订单号
Str_Out_trade_no = GetOut_trade_no();
//商品ID
string Str_productId = GetRandom(9);
//金额
string strAmount = GetAmount(req.deviceNo, req.busyCode, req.isTest);
string Str_total_amount = strAmount;// "0.01";//支付宝支付金额,以 元 为单位
int Int_total_amount = ParIntForWeixin(strAmount);// 1;//微信支付金额,以 分 为单位
#region weixin
NativePay nativePay = new NativePay();
//生成扫码支付模式二url
string url2 = nativePay.GetPayUrl(Str_Out_trade_no, Str_productId, Int_total_amount);
Log.Info(this.GetType().ToString(), "WeiXinNativePay url2 : " + url2);
WxCode = "SUCCESS";
WxCodeUrl = HttpUtility.UrlEncode(url2);
#endregion
#region ali
AlipayTradePrecreateContentBuilder builder = BuildPrecreateContent(Str_Out_trade_no, Str_productId, Str_total_amount);
//string out_trade_no = builder.out_trade_no;
//推荐使用轮询撤销机制,不推荐使用异步通知,避免单边账问题发生。
IAlipayTradeService serviceClient = F2FBiz.CreateClientInstance(Config.serverUrl, Config.appId, Config.merchant_private_key, Config.version,
Config.sign_type, Config.alipay_public_key, Config.charset);
string notify_url = Config.NotifyUrl; //商户接收异步通知的地址
AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, notify_url);
//以下返回结果的处理供参考。
//payResponse.QrCode即二维码对于的链接
//将链接用二维码工具生成二维码,顾客可以用支付宝钱包扫码支付。
switch (precreateResult.Status)
{
case ResultEnum.SUCCESS:
AliCode = "SUCCESS";
AliCodeUrl = HttpUtility.UrlEncode(precreateResult.response.QrCode);
break;
case ResultEnum.FAILED:
AliCode = "FAILED";
AliCodeUrl = precreateResult.response.Body;
break;
case ResultEnum.UNKNOWN:
AliCode = "UNKNOWN";
if (precreateResult.response == null)
{
AliCodeUrl = "配置或网络异常,请检查后重试";
}
else
{
AliCodeUrl = "系统异常,请更新外部订单后重新发起请求";
}
break;
}
#endregion
//处理业务数据,存图片、写数据库
Task.Run(()=> WritePayDataNew(req, Str_Out_trade_no));
WriteLog.Debug("计时:结束时间=" + DateTime.Now.ToString());
result.Code = "200";
result.Msg = "成功";
result.WxCode = WxCode;
result.WxCodeUrl = WxCodeUrl;
result.AliCode = AliCode;
result.AliCodeUrl = AliCodeUrl;
result.Out_trade_no = Str_Out_trade_no;
return Json(result);
}
private int ParIntForWeixin(string strAmount)
{
double p = 0;
double.TryParse(strAmount, out p);
int intp = (int)(p * 100);
if (intp == 0)
return 20 * 100;
else
return intp;
}
private string GetAmount(string deviceNo, string busyCode, string isTest)
{
var strTest = string.IsNullOrEmpty(isTest) ? "" : isTest;
if (strTest.Equals("1"))
{
//测试用,金额为配置的0.01
string TestamountPrice = ConfigurationManager.AppSettings["TestamountPrice"];
if (string.IsNullOrEmpty(TestamountPrice))
return "0.01";
else
return TestamountPrice;
}
else
{
IQueryable<M_AgentDevice_Pay> q = _amountService.GetByNoCode(deviceNo, busyCode);
var ls = q.ToList();
if (ls == null || ls.Count < 1)
{
string amountPrice = ConfigurationManager.AppSettings["amountPrice"];
if (string.IsNullOrEmpty(amountPrice))
return "20";
else
return amountPrice;
}
else
{
return ls[0].PayAmount;
}
}
}
/// <summary>
/// 支付宝 构造支付请求数据
/// </summary>
/// <returns>请求数据集</returns>
private AlipayTradePrecreateContentBuilder BuildPrecreateContent(string Str_Out_trade_no, string Str_productId, string Str_total_amount)
{
//bkin 三个参数:out_trade_no total_amount subject
//线上联调时,请输入真实的外部订单号。
string out_trade_no = Str_Out_trade_no;
AlipayTradePrecreateContentBuilder builder = new AlipayTradePrecreateContentBuilder();
//收款账号
builder.seller_id = Config.pid;
//订单编号
builder.out_trade_no = out_trade_no;
//订单总金额
builder.total_amount = Str_total_amount;
//参与优惠计算的金额
//builder.discountable_amount = "";
//不参与优惠计算的金额
//builder.undiscountable_amount = "";
//订单名称
builder.subject = "证件照";
//自定义超时时间
builder.timeout_express = "5m";
//订单描述
builder.body = "";
//门店编号,很重要的参数,可以用作之后的营销
builder.store_id = "test store id";
//操作员编号,很重要的参数,可以用作之后的营销
builder.operator_id = "证件照";
//传入商品信息详情
List<GoodsInfo> gList = new List<GoodsInfo>();
GoodsInfo goods = new GoodsInfo();
goods.goods_id = Str_productId;
goods.goods_name = "证件照";
goods.price = Str_total_amount;
goods.quantity = "1";
gList.Add(goods);
builder.goods_detail = gList;
//系统商接入可以填此参数用作返佣
//ExtendParams exParam = new ExtendParams();
//exParam.sysServiceProviderId = "20880000000000";
//builder.extendParams = exParam;
return builder;
}
private void WritePayData(WxAliPayRequest req, string Str_Out_trade_no)
{
WriteLog.Debug("WritePayData begin");
if (req == null)
return;
var filePath = Base64_to_File(req.avatar);
//
var _payService1 = EngineContext.Current.Resolve<IAgent_User_ImgService>();
var _payService2 = EngineContext.Current.Resolve<IAgentOperationPayService>();
var _payService3 = EngineContext.Current.Resolve<IAgentOperationService>();
//插入 Agent_User_Img 表
var m = new M_Agent_User_Img()
{
SFZMHM = req.SFZMHM,
SFZMMC = req.SFZMMC,
SFZMLX = req.SFZMLX,
Img_Type = req.Img_Type,
Img_Url = filePath,
OperationNo = req.OperationNo,
Img_Spec = req.Img_Spec,
Create_Time = DateTime.Now,
IsDeleted = false
};
_payService1.Insert(m);
//插入 AgentOperationPay 表
var m2 = new M_AgentOperationPay()
{
Payment = 0,//支付成功回调更新为 (1, "微信支付");(2, "支付宝支付");(3, "银联支付");(4, "现金支付");
Amount = (decimal)0.01,
Quantity = 1,
PayStatus = 0,//支付成功回调更新为1
AddTime = DateTime.Now,
IsDeleted = false,
OrderNo = Str_Out_trade_no,
SerialNo = Str_Out_trade_no,
OperationNo = req.OperationNo
};
_payService2.Insert(m2);
//插入 AgentOperation 表
var m3 = new M_AgentOperation()
{
AgentNo = "bsr_zxj",
OperationNo = req.OperationNo,
AgentDeviceNo = req.deviceNo,
BusinessNo = "dgnzxj",
OperationStatus = true,
AddTime = DateTime.Now,
IsDeleted = false,
ValidateCode = "1111",
Status = 0 //支付成功回调更新为1
};
_payService3.Insert(m3);
}
private void WritePayDataNew(WxAliPayRequestOnlyUrl req, string Str_Out_trade_no)
{
WriteLog.Debug("WritePayData begin");
if (req == null)
return;
//
var _payService2 = EngineContext.Current.Resolve<IAgentOperationPayService>();
var _payService3 = EngineContext.Current.Resolve<IAgentOperationService>();
//插入 AgentOperationPay 表
var m2 = new M_AgentOperationPay()
{
Payment = 0,//支付成功回调更新为 (1, "微信支付");(2, "支付宝支付");(3, "银联支付");(4, "现金支付");
Amount = (decimal)0.01,
Quantity = 1,
PayStatus = 0,//支付成功回调更新为1
AddTime = DateTime.Now,
IsDeleted = false,
OrderNo = Str_Out_trade_no,
SerialNo = Str_Out_trade_no,
OperationNo = req.OperationNo
};
_payService2.Insert(m2);
//插入 AgentOperation 表
var m3 = new M_AgentOperation()
{
AgentNo = "bsr_zxj",
OperationNo = req.OperationNo,
AgentDeviceNo = req.deviceNo,
BusinessNo = "dgnzxj",
OperationStatus = true,
AddTime = DateTime.Now,
IsDeleted = false,
ValidateCode = "1111",
Status = 0 //支付成功回调更新为1
};
_payService3.Insert(m3);
}
private void WritePayData2(WxAliPayRequest req, string Str_Out_trade_no)
{
WriteLog.Debug("WritePayData begin");
if (req == null)
return;
var filePath = Base64_to_File(req.avatar);
//插入 Agent_User_Img 表
var m = new M_Agent_User_Img()
{
SFZMHM = req.SFZMHM,
SFZMMC = req.SFZMMC,
SFZMLX = req.SFZMLX,
Img_Type = req.Img_Type,
Img_Url = filePath,
OperationNo = req.OperationNo,
Img_Spec = req.Img_Spec,
Create_Time = DateTime.Now,
IsDeleted = false
};
_userService.Insert(m);
//插入 AgentOperationPay 表
var m2 = new M_AgentOperationPay()
{
Payment = 1,
Amount = (decimal)0.01,
Quantity = 1,
PayStatus = 0,
AddTime = DateTime.Now,
IsDeleted = false,
OrderNo = Str_Out_trade_no,
SerialNo = Str_Out_trade_no,
OperationNo = req.OperationNo
};
_payService.Insert(m2);
//插入 AgentOperation 表
var m3 = new M_AgentOperation()
{
AgentNo = "bsr_zxj",
OperationNo = req.OperationNo,
AgentDeviceNo = req.deviceNo,
BusinessNo = "dgnzxj",
OperationStatus = true,
AddTime = DateTime.Now,
IsDeleted = false,
ValidateCode = "1111",
Status = 1
};
_operateService.Insert(m3);
}
private string GetOut_trade_no()
{
return System.DateTime.Now.ToString("yyyyMMddHHmmss") + GetRandom(10);
}
private string Base64_to_File(string imageCode)
{
if (string.IsNullOrEmpty(imageCode))
return "";
byte[] arr2 = Convert.FromBase64String(imageCode);
using (MemoryStream ms2 = new MemoryStream(arr2))
{
string dir = "/user_img/" + DateTime.Now.ToString("yyyyMMdd") + "/";
if (!Directory.Exists(Server.MapPath(dir)))
{
Directory.CreateDirectory(Server.MapPath(dir));
}
string fileName = Guid.NewGuid() + ".jpg";
string dirFile = Server.MapPath(dir) + fileName;
System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
bmp2.Save(dirFile, System.Drawing.Imaging.ImageFormat.Jpeg);
//bmp2.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
//bmp2.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
//bmp2.Save(filePath + ".png", System.Drawing.Imaging.ImageFormat.Png);
return dir + fileName;
}
}
//生成N位的随机数 全数字
private string GetRandom(int len)
{
string k = "";
Random rand = new Random(GetRandomSeed());
for (int i = 0; i < len; i++)
{
k += rand.Next(0, 10).ToString();
}
return k;
}
//取随机数种子
private int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
#endregion
#region 客户端轮询此接口,查是否已经付款
//根据订单号来查询
[HttpPost]
public JsonResult CheckIsPay(string out_trade_no)
{
var m = _payService.GetByOrderNo(out_trade_no);
if (m == null)
{
return Json(new { code = "0", msg = "未支付" });
}
else if (m.PayStatus == 1)
{
return Json(new { code = "1", msg = "已支付" });
}
else
{
return Json(new { code = "0", msg = "未支付" });
}
}
#endregion
}
}