You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

442 lines
18 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using NetLibrary;
using NetLibrary.Log;
using Newtonsoft.Json;
namespace TradeManage
{
public partial class oauth2 : System.Web.UI.Page
{
const string Token = "qianyun"; //你的token
static string appId = "wx2f5849d8aa573da3";//公众号的appId
static string appSecret = "34cc0ed309a8250eed74ea4df0b59fb5";//公众号的appSecret
static string Code = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if ((Server.UrlDecode(Page.Request.QueryString["Code"]) != null) && (Server.UrlDecode(Page.Request.QueryString["Code"]) != ""))
{
Code = Request.QueryString["Code"].ToString();
PostUrl();
}
}
}
public void PostUrl()
{
//string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2f5849d8aa573da3&redirect_uri=http://www.mnkj.com/oauth2.aspx&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + Code + "&grant_type=authorization_code";
string ErrorMessage = "";
string XmlContent = CustomIO.HttpRequest(url, "Get", out ErrorMessage);
if(ErrorMessage!="")
ErrorFollow.TraceWrite("PostUrl", "PostUrl", ErrorMessage);
if (XmlContent != "")
{
//ErrorFollow.TraceWrite("PostUrl", "PostUrl", XmlContent);
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
weixin_token Model = JsonConvert.Deserialize<weixin_token>(XmlContent);
//string url1 = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
if (Model != null)
{
string OpenId = Model.openid;
if (OpenId == "")
return;
int UId = TradeData.BaseService.IsWeiXin(OpenId);
if (UId == -1)
{
Response.Write("<script type='text/javascript'>alert('对不起,您已经领过红包了,不能重复领取!');WeixinJSBridge.call('closeWindow');</script>");
}
else if (UId ==0)
{
Response.Write("<script type='text/javascript'>alert('对不起,红包已经发完,请关注下次活动!');WeixinJSBridge.call('closeWindow');</script>");
}
else if(UId>0)
{
PostPage(OpenId, UId);
}
// ErrorFollow.TraceWrite("OpenId1", "OpenId1", OpenId);
}
//ErrorFollow.TraceWrite("PostUrl", "PostUrl", "access_token:" + Model.access_token + ";refresh_token:" + Model.refresh_token + ";expires_in:" + Model.expires_in.ToString() + ";openid:" + Model.openid);
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// ErrorFollow.TraceWrite("OpenId2", "OpenId2", OpenId);
//int UId = TradeData.BaseService.IsWeiXin(OpenId);
// if (UId == -1)
// {
// Response.Write("<script type='text/javascript'>alert('您已经领过红包了!');</script>");
// }
// else
// Response.Redirect("weixin/weixinauth.aspx?OpenId="+OpenId);
}
public void PostPage(string OpenId, int amount)
{
try
{
PayWeiXin model = new PayWeiXin();
PayForWeiXinHelp PayHelp = new PayForWeiXinHelp();
string result = string.Empty;
//传入OpenId
string openId = OpenId;// "obpqPs0mhCF1GHOiB6ExmyFc4Zzg";
//传入红包金额(单位分)
// Random r = new Random();
// decimal hb = r.Next(100, 200);
//string amount = hb.ToString();
//接叐收红包的用户 用户在wxappid下的openid
model.re_openid = openId;//"oFIYdszuDXVqVCtwZ-yIcbIS262k";
//付款金额,单位分
model.total_amount = amount;
//最小红包金额,单位分
model.min_value = amount;
//最大红包金额,单位分
model.max_value = amount;
//调用方法
string postData = PayHelp.DoDataForPayWeiXin(model);
result = PayHelp.PayForWeiXin(postData);
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
string jsonResult = JsonConvert.SerializeXmlNode(doc);
if (jsonResult.Contains("SUCCESS")==true)
{
TradeModel.WX_User md = new TradeModel.WX_User();
md.openId = openId;
md.InDate = DateTime.Now;
md.GetMoney = Convert.ToDecimal(amount);
md.GetDate = DateTime.Now;
TradeData.BaseService.SaveWXUser(md);
Response.Write("<script type='text/javascript'>alert('恭喜您,已经成功领取红包,请返回微信查看红包!');WeixinJSBridge.call('closeWindow');</script>");
}
else
{
Response.Write("<script type='text/javascript'>alert('对不起,领取红包失败!');window.close();</script>");
TradeData.BaseService.UseWeiXin(openId);
ErrorFollow.TraceWrite("PostPage", "PostPage", jsonResult);
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("PostPage", "PostPage", ex.Message); //写日志
return;
}
}
}
public class weixin_token
{
public string access_token { get; set; }
public Int32? expires_in { get; set; }
public string refresh_token { get; set; }
public string openid { get; set; }
public string scope { get; set; }
}
public class PayForWeiXinHelp
{
/// <summary>
/// 调用微信支付接口前处理数据包括sign验证等
/// </summary>
/// <param name="payForWeiXin"></param>
/// <returns></returns>
public string DoDataForPayWeiXin(PayWeiXin payForWeiXin)
{
#region 处理nonce_str随机字符串不长于 32 位本程序生成长度为16位的
string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
payForWeiXin.nonce_str = RandomStr(str, 16);
#endregion
#region 商户信息从config文件中读取
//商户支付密钥key
string key = "0123456789ABCDefghijklmnopqrstuv";
//商户号
payForWeiXin.mch_id = "1245142102";
//商户 appid
payForWeiXin.wxappid = "wx2f5849d8aa573da3";
//提供方名称
payForWeiXin.nick_name = "云界抑菌健康生活馆";
payForWeiXin.act_id = "act_id";
//红包収送者名称
payForWeiXin.send_name = "云界抑菌健康生活馆";
//红包収放总人数
payForWeiXin.total_num = 1;
//红包祝福诧
payForWeiXin.wishing = "欢迎访问云界抑菌优享健康生活";
//活劢名称
payForWeiXin.act_name = "云界抑菌剂优享活动";
//备注信息
payForWeiXin.remark = "无";
//商户logo的url
payForWeiXin.logo_imgurl = "";
//分享文案
payForWeiXin.share_content = "";
//分享链接
payForWeiXin.share_url = "";
//分享的图片url
payForWeiXin.share_imgurl = "";
//调用接口的机器 Ip 地址
payForWeiXin.client_ip = "121.41.56.160";
#endregion
#region 订单信息
//生成订单号组成: mch_id+yyyymmdd+10 位一天内不能重复的数字
//生成10位不重复的数字
string num = "0123456789";
string randomNum = RandomStr(num, 10);
payForWeiXin.mch_billno = payForWeiXin.mch_billno + System.DateTime.Now.ToString("yyyyMMdd") + randomNum;
#endregion
string postData = @"<xml>
<mch_billno>{0}</mch_billno>
<mch_id>{1}</mch_id>
<wxappid>{2}</wxappid>
<nick_name>{3}</nick_name>
<send_name>{4}</send_name>
<re_openid>{5}</re_openid>
<total_amount>{6}</total_amount>
<min_value>{7}</min_value>
<max_value>{8}</max_value>
<total_num>{9}</total_num>
<wishing>{10}</wishing>
<client_ip>{11}</client_ip>
<act_name>{12}</act_name>
<act_id>{13}</act_id>
<remark>{14}</remark>
<nonce_str>{15}</nonce_str>";
postData = string.Format(postData,
payForWeiXin.mch_billno,
payForWeiXin.mch_id,
payForWeiXin.wxappid,
payForWeiXin.nick_name,
payForWeiXin.send_name,
payForWeiXin.re_openid,
payForWeiXin.total_amount,
payForWeiXin.min_value,
payForWeiXin.max_value,
payForWeiXin.total_num,
payForWeiXin.wishing,
payForWeiXin.client_ip,
payForWeiXin.act_name,
payForWeiXin.act_id,
payForWeiXin.remark,
payForWeiXin.nonce_str
);
//原始传入参数
string[] signTemp = { "mch_billno=" + payForWeiXin.mch_billno, "mch_id=" + payForWeiXin.mch_id, "wxappid=" + payForWeiXin.wxappid, "nick_name=" + payForWeiXin.nick_name, "send_name=" + payForWeiXin.send_name, "re_openid=" + payForWeiXin.re_openid, "total_amount=" + payForWeiXin.total_amount, "min_value=" + payForWeiXin.min_value, "max_value=" + payForWeiXin.max_value, "total_num=" + payForWeiXin.total_num, "wishing=" + payForWeiXin.wishing, "client_ip=" + payForWeiXin.client_ip, "act_name=" + payForWeiXin.act_name, "act_id=" + payForWeiXin.act_id, "remark=" + payForWeiXin.remark, "nonce_str=" + payForWeiXin.nonce_str };
List<string> signList = signTemp.ToList();
//拼接原始字符串
if (!string.IsNullOrEmpty(payForWeiXin.logo_imgurl))
{
postData += "<logo_imgurl>{0}</logo_imgurl> ";
postData = string.Format(postData, payForWeiXin.logo_imgurl);
signList.Add("logo_imgurl=" + payForWeiXin.logo_imgurl);
}
if (!string.IsNullOrEmpty(payForWeiXin.share_content))
{
postData += "<share_content>{0}</share_content> ";
postData = string.Format(postData, payForWeiXin.share_content);
signList.Add("share_content=" + payForWeiXin.share_content);
}
if (!string.IsNullOrEmpty(payForWeiXin.share_url))
{
postData += "<share_url>{0}</share_url> ";
postData = string.Format(postData, payForWeiXin.share_url);
signList.Add("share_url=" + payForWeiXin.share_url);
}
if (!string.IsNullOrEmpty(payForWeiXin.share_imgurl))
{
postData += "<share_imgurl>{0}</share_imgurl> ";
postData = string.Format(postData, payForWeiXin.share_imgurl);
signList.Add("share_imgurl=" + payForWeiXin.share_imgurl);
}
#region 处理支付签名
//对signList按照ASCII码从小到大的顺序排序
signList.Sort();
string signOld = string.Empty;
string payForWeiXinOld = string.Empty;
int i = 0;
foreach (string temp in signList)
{
signOld += temp + "&";
i++;
}
signOld = signOld.Substring(0, signOld.Length - 1);
//拼接Key
signOld += "&key=" + key;
//处理支付签名
payForWeiXin.sign = Encrypt(signOld).ToUpper();
#endregion
postData += "<sign>{0}</sign></xml>";
postData = string.Format(postData, payForWeiXin.sign);
return postData;
}
/// <summary>
/// 调用微信支付接口
/// </summary>
/// <param name="payForWeiXin"></param>
/// <returns></returns>
public string PayForWeiXin(string postData)
{
string result = string.Empty;
try
{
result = PostPage("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", postData);
}
catch (Exception ex)
{
}
return result;
}
/// <summary>
/// post微信请求
/// </summary>
/// <param name="posturl"></param>
/// <param name="postData"></param>
/// <returns></returns>
public string PostPage(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
//CerPath证书路径
string certPath = "D:\\mtkjerp\\Scripts\\cert\\apiclient_cert.p12";//"E:\\tfstmsk\\erp\\TradeManage\\TradeManage\\Scripts\\cert\\apiclient_cert.p12";
//证书密码
string password = "1245142102";
X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet);
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = data.Length;
request.ClientCertificates.Add(cert);
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页html代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
public string RandomStr(string str, int Length)
{
string result = string.Empty;
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
result += str[rd.Next(str.Length)];
}
return result;
}
/// <summary>
/// Md5加密
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static String Encrypt(String s)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
bytes = md5.ComputeHash(bytes);
md5.Clear();
string ret = "";
for (int i = 0; i < bytes.Length; i++)
{
ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
}
return ret.PadLeft(32, '0');
}
}
public class PayWeiXin
{
public string nonce_str { get; set; }
public string sign { get; set; }
public string mch_billno { get; set; }
public string mch_id { get; set; }
public string wxappid { get; set; }
public string nick_name { get; set; }
public string send_name { get; set; }
public string re_openid { get; set; }
public int total_amount { get; set; }
public int min_value { get; set; }
public int max_value { get; set; }
public int total_num { get; set; }
public string wishing { get; set; }
public string client_ip { get; set; }
public string act_id { get; set; }
public string act_name { get; set; }
public string remark { get; set; }
public string logo_imgurl { get; set; }
public string share_content { get; set; }
public string share_url { get; set; }
public string share_imgurl { get; set; }
}
}