注:需要开通微信支付的服务号!
public ActionResult Index()
{
ViewBag.url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + {服务号appid} + "&redirect_uri=http%3A%2F%2F" + {微信重定向域名(填写程序域名,例如:www.xxxx.com)} + "%2F"+{程序控制器名,例如:Home}+"%2F"+{程序Action名,例如:RedirectWeChat}+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
return View();
}
public static string accesstoken(string WeChatWxAppId, string WeChatWxAppSecret)
{
string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WeChatWxAppId, WeChatWxAppSecret));
if (strJson.IndexOf("errcode") == -1)
{
return GetJsonValue(strJson, "access_token");
}
else
{
return "";
}
}
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' });
}
}
return result;
}
public static string RequestUrl(string url, string method="post")
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.ContentType = "text/html";
request.Headers.Add("charset", "utf-8");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string content = sr.ReadToEnd();
return content;
}
public ActionResult RedirectWeChat(string code, string state)
{
if (string.IsNullOrEmpty(code))
{
return Content("您拒绝了授权!");
}
string access_token = accesstoken(微信AppId, 微信AppSecret);
string st = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + 微信AppId + "&secret=" + 微信AppSecret + "&code=" + code + "&grant_type=authorization_code";
string data = RequestUrl(st);
string openid=GetJsonValue(data, "openid");
string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
data = RequestUrl(url);
string subscribe=GetJsonValue(data, "subscribe");
if (subscribe == "0")
{
return RedirectToAction("");
}
return RedirectToAction("");
}
public ActionResult HB()
{
string openid = "";
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
string orderNo = 商户号 + DateTime.Now.ToString("yyyymmdd")+"随机10位数字";
string Code = ""
Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("act_name", "");
data.Add("client_ip", "192.168.1.1");
data.Add("mch_billno", orderNo);
data.Add("mch_id", "");
data.Add("nonce_str", Code);
data.Add("re_openid", openid);
data.Add("remark", "");
data.Add("send_name","");
data.Add("total_amount", "100");
data.Add("total_num", "1");
data.Add("wishing", "恭喜发财");
data.Add("wxappid", );
string xml = GetXML(data, key);
string str=PostWebRequests(url, xml);
return View("");
}
public static string GetXML(Dictionary<string, string> data,string paykey)
{
string retStr;
MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
var data1=from d in data orderby d.Key select d;
string data2 = "";
string XML = "<xml>";
foreach (var item in data1)
{
if (item.Value + "" != "")
{
data2 += item.Key +"="+ item.Value + "&";
}
XML += "<" + item.Key + ">" + item.Value+""+ "</" + item.Key + ">";
}
data2 += paykey;
byte[] inputBye;
byte[] outputBye;
try
{
inputBye = Encoding.UTF8.GetBytes(data2);
}
catch
{
inputBye = Encoding.GetEncoding("GB2312").GetBytes(data2);
}
outputBye = m5.ComputeHash(inputBye);
retStr = System.BitConverter.ToString(outputBye);
retStr = retStr.Replace("-", "").ToUpper();
XML += "<sign>" + retStr + "</sign>";
XML += "</xml>";
return XML;
}
public static string PostWebRequests(string postUrl, string menuInfo)
{
string returnValue = string.Empty;
try
{
Encoding encoding = Encoding.UTF8;
byte[] bytes = encoding.GetBytes(menuInfo);
string cert = @"E:\cdcert\apiclient_cert.p12";
string password = "1212121";
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
X509Certificate cer = new X509Certificate(cert, password, X509KeyStorageFlags.MachineKeySet);
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(postUrl);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
webrequest.ContentLength = bytes.Length;
webrequest.GetRequestStream().Write(bytes, 0, bytes.Length);
HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
Stream stream = webreponse.GetResponseStream();
string resp = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return "";
}
}
以下是微信开发官方相关文档
1.【微信支付】公众号支付开发者文档
2. 微信开放平台
3.企业号开发者接口文档
4.微信公众平台开发者文档