盛派网络:微信支付微信授权类库下载
微信小程序支付后台代码
配置:
<!--身份证验证APPKEY-->
<add key="ServiceAppID" value="wxbcfbc3412920225" />
<add key="ServiceMechID" value="150351221" />
<add key="SubAppID" value="wxb25cd5d2014cbfc" />
<add key="SubMechID" value="160003570" />
<add key="AppKey" value="qiiwangluo18qingweiwangluo" />
<add key="SubAppKey" value="59F3DE7C78C4924A4ECF2446D08EF81" />
<add key="Notify_URL" value="http://AppApi/Pay/OrderInfoWechatNotify" />
<add key="IDCardQuery" value="007b4a461d947f1c2aa8cb1f88c04d" />
string nonceStr = Guid.NewGuid().ToString();
nonceStr = nonceStr.Replace("-", "");
string Noncestr = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
TenPayV3UnifiedorderRequestData TenPay = new TenPayV3UnifiedorderRequestData(
System.Configuration.ConfigurationManager.AppSettings["ServiceAppID"],
System.Configuration.ConfigurationManager.AppSettings["ServiceMechID"],
System.Configuration.ConfigurationManager.AppSettings["SubAppID"],
System.Configuration.ConfigurationManager.AppSettings["SubMechID"],
"购买商品" + OrderInfo.OrderNo,
OrderInfo.OrderNo,
Convert.ToInt32(OrderInfo.PayPrice * 100),
"127.0.0.1",
System.Configuration.ConfigurationManager.AppSettings["Notify_URL"],
Senparc.Weixin.MP.TenPayV3Type.JSAPI,
"",
Users.WxOpenID,
System.Configuration.ConfigurationManager.AppSettings["AppKey"],
Noncestr
);
UnifiedorderResult UResult = TenPayV3.Unifiedorder(TenPay);
#region 计算APP支付签名
string AppKeySign = string.Empty;
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
string NonceStr = JSSDKHelper.GetNoncestr();
RequestHandler AppPayRequestHandler = new RequestHandler(null);
AppPayRequestHandler.Init();
AppPayRequestHandler.SetParameter("appId", System.Configuration.ConfigurationManager.AppSettings["SubAppID"]);
AppPayRequestHandler.SetParameter("package", "prepay_id="+UResult.prepay_id);
AppPayRequestHandler.SetParameter("signType", "MD5");
AppPayRequestHandler.SetParameter("nonceStr", NonceStr);
AppPayRequestHandler.SetParameter("timeStamp", timestamp);
AppKeySign = AppPayRequestHandler.CreateMd5Sign("key", System.Configuration.ConfigurationManager.AppSettings["AppKey"]);
#endregion
UnifiedorderResult UResult1 = TenPayV3.Unifiedorder(TenPay);
if (UResult != null && UResult.return_code == "SUCCESS")
{
if (UResult.result_code == "SUCCESS")
{
object data = new
{
PrepayId = UResult.prepay_id,
Price = Convert.ToInt32(OrderInfo.PayPrice * 100).ToString("0.##"),
OrderNumber = OrderInfo.OrderNo,
Sign = AppKeySign,
NonceStr = NonceStr,
TimeStamp = timestamp,
AppID = System.Configuration.ConfigurationManager.AppSettings["ServiceAppID"],
MechID = System.Configuration.ConfigurationManager.AppSettings["ServiceMechID"],
SubAppID = System.Configuration.ConfigurationManager.AppSettings["SubAppID"],
SubMechID = System.Configuration.ConfigurationManager.AppSettings["SubMechID"],
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "下单成功:" + UResult.return_msg }, JsonRequestBehavior.DenyGet);
}
}
#region 回调地址
public ActionResult OrderInfoWechatNotify()
{
Int32 intLen = Convert.ToInt32(Request.InputStream.Length);
byte[] b = new byte[intLen];
Request.InputStream.Read(b, 0, intLen);
string resultFromWx = System.Text.Encoding.UTF8.GetString(b);
Logger.Debug("==OrderInfoWechatNotify 回调参数:" + resultFromWx);
if (string.IsNullOrEmpty(resultFromWx))
{
return Content("<xml><return_code>FAIL</return_code><return_msg>支付失败</return_msg></xml>");
}
var xmlDoc = XDocument.Parse(resultFromWx);
try
{
IQingWei.Model.OrderInfo OrderInfo = OrderInfoBLL.GetModelByWhere(string.Format("OrderNo='{0}'", xmlDoc.Element("xml").Element("out_trade_no").Value));
if (OrderInfo == null)
{
return Content("<xml><return_code>FAIL</return_code><return_msg>订单不存在</return_msg></xml>");
}
if (xmlDoc.Element("xml").Element("return_code").Value == "FAIL")
{
OrderInfo.PayState = 0;
OrderInfo.OrderState = 1;
if (OrderInfoBLL.Update(OrderInfo))
{
return Content("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
}
}
#region 验证签名
RequestHandler paySignReqHandler = new RequestHandler(null);
paySignReqHandler.SetParameter("appid", xmlDoc.Element("xml").Element("appid").Value);
paySignReqHandler.SetParameter("bank_type", xmlDoc.Element("xml").Element("bank_type").Value);
paySignReqHandler.SetParameter("fee_type", xmlDoc.Element("xml").Element("fee_type").Value);
paySignReqHandler.SetParameter("is_subscribe", xmlDoc.Element("xml").Element("is_subscribe").Value);
paySignReqHandler.SetParameter("mch_id", xmlDoc.Element("xml").Element("mch_id").Value);
paySignReqHandler.SetParameter("nonce_str", xmlDoc.Element("xml").Element("nonce_str").Value);
paySignReqHandler.SetParameter("out_trade_no", xmlDoc.Element("xml").Element("out_trade_no").Value);
paySignReqHandler.SetParameter("result_code", xmlDoc.Element("xml").Element("result_code").Value);
paySignReqHandler.SetParameter("return_code", xmlDoc.Element("xml").Element("return_code").Value);
paySignReqHandler.SetParameter("sign", xmlDoc.Element("xml").Element("sign").Value);
paySignReqHandler.SetParameter("time_end", xmlDoc.Element("xml").Element("time_end").Value);
paySignReqHandler.SetParameter("total_fee", xmlDoc.Element("xml").Element("total_fee").Value);
paySignReqHandler.SetParameter("trade_type", xmlDoc.Element("xml").Element("trade_type").Value);
paySignReqHandler.SetParameter("transaction_id", xmlDoc.Element("xml").Element("transaction_id").Value);
paySignReqHandler.SetParameter("sub_appid", xmlDoc.Element("xml").Element("sub_appid").Value);
paySignReqHandler.SetParameter("sub_mch_id", xmlDoc.Element("xml").Element("sub_mch_id").Value);
paySignReqHandler.SetParameter("sub_is_subscribe", xmlDoc.Element("xml").Element("sub_is_subscribe").Value);
paySignReqHandler.SetParameter("cash_fee", xmlDoc.Element("xml").Element("cash_fee").Value);
paySignReqHandler.SetParameter("openid", xmlDoc.Element("xml").Element("openid").Value);
paySignReqHandler.SetParameter("sub_openid", xmlDoc.Element("xml").Element("sub_openid").Value);
if (xmlDoc.Element("xml").Element("coupon_count") != null)
{
paySignReqHandler.SetParameter("coupon_count", xmlDoc.Element("xml").Element("coupon_count").Value);
paySignReqHandler.SetParameter("coupon_fee", xmlDoc.Element("xml").Element("coupon_fee").Value);
paySignReqHandler.SetParameter("coupon_fee_0", xmlDoc.Element("xml").Element("coupon_fee_0").Value);
paySignReqHandler.SetParameter("coupon_id_0", xmlDoc.Element("xml").Element("coupon_id_0").Value);
paySignReqHandler.SetParameter("coupon_fee", xmlDoc.Element("xml").Element("coupon_fee").Value);
}
var paySign = paySignReqHandler.CreateMd5Sign("key", System.Configuration.ConfigurationManager.AppSettings["AppKey"]);
if (paySign != xmlDoc.Element("xml").Element("sign").Value)
{
return Content("<xml><return_code>FAIL</return_code><return_msg>签名验证失败</return_msg></xml>");
}
#endregion
if (Convert.ToInt32(OrderInfo.PayPrice * 100) != Convert.ToInt32(xmlDoc.Element("xml").Element("total_fee").Value))
{
return Content("<xml><return_code>FAIL</return_code><return_msg>订单金额不一致</return_msg></xml>");
}
OrderInfo.PayState = 1;
OrderInfo.OrderState = 2;
OrderInfo.PayDate = DateTime.Now;
OrderInfo.ParOrderNo = xmlDoc.Element("xml").Element("transaction_id").Value;
if (OrderInfoBLL.Update(OrderInfo))
{
if (OrderInfo.UserCouponReceiveId != Guid.Empty)
{
UserCouponReceiveBLL.UpdateCouponReceiveStatus(OrderInfo.UserCouponReceiveId);
}
var equipModel = equipmentBLL.GetModelByWhere(string.Format(" id='{0}' ", OrderInfo.EquipId));
#region 支付成功 - 根据设备类型通知服务器
if (OrderInfo.TypeNo != null)
{
IQingWei.Model.EquipType EquipType = EquipTypeBLL.GetModelByWhere(string.Format("TypeNo='{0}'", OrderInfo.TypeNo));
if (EquipType.ProtocolMode == 4)
{
SendYaoYaoChe(equipModel.Sn, OrderInfo.OrderNo, (OrderInfo.GoodsNumber * OrderInfo.GoodsCount).ToString());
}
}
#endregion
return Content("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
}
return Content("<xml><return_code>FAIL</return_code><return_msg>订单不存在</return_msg></xml>");
}
catch (Exception ex)
{
Logger.Debug("==回调方法执行错误: " +ex.Message);
return Content("<xml><return_code>FAIL</return_code><return_msg>" + ex.Message + "</return_msg></xml>");
}
}
#endregion
微信登录
public class wxlogin
{
#region Http (GET/POST)
public static string sendPost(string url, IDictionary<string, string> parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = 5000;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
request.Method = "GET";
request.ReadWriteTimeout = 5000;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
#endregion
#region 组装普通文本请求参数
static string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(name))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
#endregion
#region 把响应流转换为文本
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
#endregion
#region 获取微信登陆openid和session_key
public static JObject Getopenid(string AppID, string Secret, string code)
{
string Data = "";
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("appId", AppID);
parameters.Add("secret", Secret);
parameters.Add("js_code", code);
parameters.Add("grant_type", "authorization_code");
Data = sendPost("https://api.weixin.qq.com/sns/jscode2session", parameters, "GET");
JObject jObject = JObject.Parse(Data);
if (jObject["errcode"] != null)
{
return null;
}
else
{
return jObject;
}
}
#endregion
#region XML Post请求
public static string XMLsendPost(string XML, string url)
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] encodedBytes = Encoding.UTF8.GetBytes(XML);
myHttpWebRequest.ContentLength = encodedBytes.Length;
Stream requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(encodedBytes, 0, encodedBytes.Length);
requestStream.Close();
HttpWebResponse result;
try
{
result = (HttpWebResponse)myHttpWebRequest.GetResponse();
}
catch (Exception ex)
{
return string.Empty;
}
if (result.StatusCode == HttpStatusCode.OK)
{
using (Stream mystream = result.GetResponseStream())
{
using (StreamReader reader = new StreamReader(mystream))
{
return reader.ReadToEnd();
}
}
}
return null;
}
#endregion
#region 请求URL
public static string Post(string Url, string jsonParas)
{
string strURL = Url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string paraUrlCoded = System.Web.HttpUtility.UrlEncode("param");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception)
{
writer = null;
Console.Write("连接服务器失败!");
}
writer.Write(payload, 0, payload.Length);
writer.Close();
String strValue = "";
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
return GetResponseAsString(response, encoding);
}
#endregion
#region 公众号获取用户信息
public static string GetInfos(string _code)
{
string _access_tokens = GetToken(_code);
JObject json = JObject.Parse(_access_tokens);
string access_token = json["access_token"].ToString();
string refresh_token = json["refresh_token"].ToString();
string openid = json["openid"].ToString();
return openid;
}
static string GetToken(string _code)
{
if (_code.IndexOf("\"") > -1)
_code = _code.Replace("\"", "");
string URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
string RequestPara = "?appid=wxb16e70ee139561f1";
RequestPara += "&secret=41af799f8767ab7d5ce18df8f4431a4c";
RequestPara += "&code=" + _code;
RequestPara += "&grant_type=authorization_code";
string _access_tokens = GetData(URL, RequestPara);
_access_tokens = _access_tokens.Replace("\"", "'");
return _access_tokens;
}
static string GetUserInfo(string access_token, string openid)
{
if (access_token.IndexOf("\"") > -1)
access_token = access_token.Replace("\"", "");
if (openid.IndexOf("\"") > -1)
openid = openid.Replace("\"", "");
string I_URL = "https://api.weixin.qq.com/sns/userinfo";
string I_RequestPara = "?access_token=" + access_token;
I_RequestPara += "&openid=" + openid;
I_RequestPara += "&lang=zh_CN";
string _infos = GetData(I_URL, I_RequestPara);
_infos = _infos.Replace("\"", "'");
return _infos;
}
static string RefreshToken(string refresh_token)
{
if (refresh_token.IndexOf("\"") > -1)
refresh_token = refresh_token.Replace("\"", "");
string R_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
string R_RequestPara = "?appid=wxb16e70ee139561f1";
R_RequestPara += "&grant_type=refresh_token";
R_RequestPara += "&refresh_token=" + refresh_token;
string _infos = GetData(R_URL, R_RequestPara);
_infos = _infos.Replace("\"", "'");
return _infos;
}
static string GetData(string URL, string RequestPara)
{
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
WebRequest hr = HttpWebRequest.Create(URL + RequestPara);
byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
hr.Method = "GET";
System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();
return ReturnVal;
}
#endregion
public static string m_PostSubmit(string strUrl, string strParam)
{
string strResult = "error";
try
{
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strUrl);
Encoding encoding = Encoding.UTF8;
byte[] bs = Encoding.ASCII.GetBytes(strParam);
string responseData = System.String.Empty;
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = bs.Length;
try
{
using (System.IO.Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse())
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseData = reader.ReadToEnd().ToString();
strResult = responseData;
}
}
}
catch (System.Exception ex)
{
strResult = "error:" + ex.Message;
}
}
catch (System.Exception ex)
{
strResult = "error:" + ex.Message;
}
return strResult;
}
}
微信小程序授权
#region 用户端登录
[HttpPost]
public JsonResult Account_UsersWxLogin(string param)
{
JObject jObject = JObject.Parse(param);
if (jObject != null)
{
try
{
string AppID = System.Configuration.ConfigurationManager.AppSettings["AppID"].ToString();
string Secret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
JObject Data = new JObject();
string UserName = string.Empty;
int IsOneClick = 0;
try
{
if (!string.IsNullOrEmpty(jObject["code"].ToString()))
{
Data = wxlogin.Getopenid(AppID, Secret, jObject["code"].ToString());
}
if (string.IsNullOrEmpty(jObject["UserName"].ToString()) && Data != null)
{
string Result = AesDecode(jObject["toDecrypt"].ToString(), Data["session_key"].ToString(), jObject["ivBytes"].ToString());
JObject jObjects = JObject.Parse(Result);
UserName = jObjects["phoneNumber"].ToString();
IsOneClick = 2;
}
else
{
UserName = jObject["UserName"].ToString();
}
}
catch (Exception ex)
{
ErrLog.LogResult("授权登录错误信息" + ex.Message);
}
if (string.IsNullOrEmpty(UserName))
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "登录失败,用户名不存在!" }, JsonRequestBehavior.DenyGet);
}
string WhereSql = string.Format("UserName='{0}' and UserType='UU'", UserName);
IQingWei.SysManage.Model.Account_Users Users = Account_UsersBLL.GetModels(WhereSql);
if (!string.IsNullOrEmpty(jObject["UserName"].ToString()))
{
if (!string.IsNullOrEmpty(jObject["Password"].ToString()))
{
if (Users.Password != MD5Helper.Encrypt(MD5Helper.Encrypt(jObject["Password"].ToString())))
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "登录失败,请确认用户名密码是否正确!" }, JsonRequestBehavior.DenyGet);
}
}
}
object data = new object();
if (Users == null)
{
IQingWei.SysManage.Model.Account_Users User = new SysManage.Model.Account_Users();
User.Activity = true;
User.UserType = "UU";
if (!string.IsNullOrEmpty(jObject["AgentCode"].ToString()))
{
int code = int.Parse(jObject["AgentCode"].ToString()) - 10000;
IQingWei.SysManage.Model.Account_Users _Account_Users = Account_UsersBLL.GetModel(code);
User.User_iGreator = code;
User.User_iGreatorPath = _Account_Users.User_iGreatorPath + "," + _Account_Users.UserID;
}
else
{
User.User_iGreator = 0;
User.User_iGreatorPath = "0";
}
User.TrueName = UserName;
User.User_dateGreate = DateTime.Now;
User.User_dataValid = DateTime.Now;
User.User_dateExpire = DateTime.Now;
User.UserName = UserName;
User.Password = MD5Helper.Encrypt(MD5Helper.Encrypt("123456"));
User.Phone = UserName;
User.Activation = false;
User.WxOpenID = Data["openid"].ToString();
int UserID = Account_UsersBLL.Add(User);
if (UserID > 0)
{
data = new
{
UserID = UserID,
UserName = UserName,
NickName = User.NickName,
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "" }, JsonRequestBehavior.DenyGet);
}
}
if (Data != null && Data.Count > 0 && !string.IsNullOrEmpty(Data["openid"].ToString()))
{
if (string.IsNullOrEmpty(Users.WxOpenID) || Users.WxOpenID != Data["openid"].ToString())
{
IQingWei.SysManage.Model.Account_Users User = Account_UsersBLL.GetModel(Users.UserID);
User.WxOpenID = Data["openid"] != null ? Data["openid"].ToString() : "";
Account_UsersBLL.Update(User);
data = new
{
UserID = User.UserID,
UserName = User.UserName,
NickName = User.NickName,
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "" }, JsonRequestBehavior.DenyGet);
}
}
if (!Users.Activity)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "登录失败,该账号不能使用!" }, JsonRequestBehavior.DenyGet);
}
if (Users.UserType != "UU")
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "不能在此平台登陆此账号!" }, JsonRequestBehavior.DenyGet);
}
data = new
{
UserID = Users.UserID,
UserName = Users.UserName,
NickName = Users.NickName,
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "登录成功!" }, JsonRequestBehavior.DenyGet);
}
catch (Exception ex)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请求失败!" + ex.Message }, JsonRequestBehavior.DenyGet);
}
}
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请求失败,传递参数出现错误!" }, JsonRequestBehavior.DenyGet);
}
#endregion
微信H5授权
#region 微信H5授权
public JsonResult Account_UsersWxLogin(string param)
{
JObject jObject = JObject.Parse(param);
if (jObject != null)
{
try
{
string AppID = "wx7d13807d301db9";
string Secret = "4ef696437c586bb2d32eb1b0d39d92";
string EquipmentSN = !string.IsNullOrEmpty(jObject["EquipmentSN"].ToString()) ? jObject["EquipmentSN"].ToString() : "";
Senparc.Weixin.MP.AdvancedAPIs.OAuth.OAuthAccessTokenResult _OAuthAccessTokenResult = null;
Senparc.Weixin.MP.AdvancedAPIs.OAuth.OAuthUserInfo _OAuthUserInfo = null;
if (string.IsNullOrEmpty(jObject["code"].ToString()))
{
return Json(new Result { DATA = "", ERROR_CODE = "1", ERROR_MESSAGE = "Code不为空!" }, JsonRequestBehavior.DenyGet);
}
if (string.IsNullOrEmpty(EquipmentSN))
{
return Json(new Result { DATA = "", ERROR_CODE = "1", ERROR_MESSAGE = "设备SN不为空!" }, JsonRequestBehavior.DenyGet);
}
_OAuthAccessTokenResult = OAuthApi.GetAccessToken(AppID, Secret, jObject["code"].ToString());
if (_OAuthAccessTokenResult.ErrorCodeValue == 40029)
{
return Json(new Result { DATA = _OAuthAccessTokenResult, ERROR_CODE = "1", ERROR_MESSAGE = "Code无效错误!" }, JsonRequestBehavior.DenyGet);
}
_OAuthUserInfo = OAuthApi.GetUserInfo(_OAuthAccessTokenResult.access_token, _OAuthAccessTokenResult.openid);
if (_OAuthUserInfo == null)
{
return Json(new Result { DATA = _OAuthUserInfo, ERROR_CODE = "1", ERROR_MESSAGE = "openid错误,获取用户信息错误!" }, JsonRequestBehavior.DenyGet);
}
string UserName = "";
int IsOneClick = 0;
if (string.IsNullOrEmpty(_OAuthUserInfo.nickname))
{
UserName = _OAuthUserInfo.nickname;
IsOneClick = 2;
}
else
{
UserName = _OAuthUserInfo.nickname;
}
if (string.IsNullOrEmpty(UserName))
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "登录失败,用户名不存在!" }, JsonRequestBehavior.DenyGet);
}
string WhereSql = string.Format(" UserType='UU' and WxOpenID='{0}'", _OAuthAccessTokenResult.openid);
List<IQingWei.SysManage.Model.Account_Users> Userlist = Account_UsersBLL.GetModelList(WhereSql, "User_dateGreate desc");
object data = new object();
if (Userlist == null || Userlist.Count == 0)
{
IQingWei.SysManage.Model.Account_Users User = new SysManage.Model.Account_Users();
User.Activity = true;
User.UserType = "UU";
User.User_iGreator = 0;
User.User_iGreatorPath = "0";
User.TrueName = UserName;
User.User_dateGreate = DateTime.Now;
User.User_dataValid = DateTime.Now;
User.User_dateExpire = DateTime.Now;
User.UserName = UserName;
User.Password = MD5Helper.Encrypt(MD5Helper.Encrypt("123456"));
User.Phone = UserName;
User.Activation = false;
User.WxOpenID = _OAuthAccessTokenResult.openid;
int UserID = Account_UsersBLL.Add(User);
if (UserID > 0)
{
data = new
{
UserID = UserID,
UserName = UserName,
EquipmentSN = EquipmentSN
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "" }, JsonRequestBehavior.DenyGet);
}
}
if (!Userlist[0].Activity)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "登录失败,该账号不能使用!" }, JsonRequestBehavior.DenyGet);
}
if (Userlist[0].UserType != "UU")
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "不能在此平台登陆此账号!" }, JsonRequestBehavior.DenyGet);
}
data = new
{
UserID = Userlist[0].UserID,
UserName = Userlist[0].UserName,
EquipmentSN = EquipmentSN,
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "登录成功!" }, JsonRequestBehavior.DenyGet);
}
catch (Exception ex)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请求失败!" + ex.Message }, JsonRequestBehavior.DenyGet);
}
}
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请求失败,传递参数出现错误!" }, JsonRequestBehavior.DenyGet);
}
#endregion