NewGaoKaoApi/New_College.Common/Helper/WeixinHelper.cs

303 lines
12 KiB
C#
Raw Permalink Blame History

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.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
namespace New_College.Common
{
public class WeixinHelper
{
/// <summary>
/// 获取AuthCodeSession
/// </summary>
/// <param name="appid"></param>
/// <param name="secret"></param>
/// <param name="code"></param>
/// <returns></returns>
public static T AuthCode2Session<T>(string appid, string secret, string code) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", appid, secret, code); ;
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 获取AccessToken
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="appid"></param>
/// <param name="secret"></param>
/// <returns></returns>
public static T GetAccessToken<T>(string appid, string secret) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("https://api.weixin.qq.com/cgi-bin/token?appid={0}&secret={1}&grant_type=client_credential", appid, secret);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
///消息订阅
/// </summary>
/// <param name="accessToken"></param>
/// <param name="openID"></param>
/// <param name="templateID"></param>
/// <param name="data"></param>
/// <returns></returns>
public static T SendSubscribeMessageAsync(string accessToken, string openID, Dictionary<string, object> data)
{
// 构造请求数据
var sendMessageRequest = new
{
access_token = accessToken,
page = "pages/index/index",
data = data,
template_id = "ZqRgty6dYqHXEGzUYAGSWcwOzNLNo1kWxMK-PO1dEBc",
touser = openID,
lang = "zh_CN",
miniprogram_state = "formal"
};
// 发送请求
var requestUrl = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={accessToken}";
var jsonContent = JsonConvert.SerializeObject(sendMessageRequest);
using (var httpClient = new HttpClient())
{
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
//var response = httpClient.PostAsync(requestUrl, httpContent);
var responseStr = httpClient.PostAsync(requestUrl, httpContent).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
public static T WxaBusinessGetUserPhoneNumber<T>(string access_token, string code) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}", access_token);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new WxaBusinessModel() { code = code }), Encoding.UTF8, "application/json");
var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
private class WxaBusinessModel
{
public string code { get; set; }
}
/**
*
* 统一下单
* @param WxPaydata inputObj 提交给统一下单API的参数
* @param int timeOut 超时时间
* @throws WePayException
* @return 成功时返回,其他抛异常
*/
public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 60)
{
string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//检测必填参数
if (!inputObj.IsSet("out_trade_no"))
{
throw new Exception("缺少统一支付接口必填参数out_trade_no");
}
else if (!inputObj.IsSet("body"))
{
throw new Exception("缺少统一支付接口必填参数body");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new Exception("缺少统一支付接口必填参数total_fee");
}
else if (!inputObj.IsSet("trade_type"))
{
throw new Exception("缺少统一支付接口必填参数trade_type");
}
//关联参数
if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
{
throw new Exception("统一支付接口中缺少必填参数openidtrade_type为JSAPI时openid为必填参数");
}
if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
{
throw new Exception("统一支付接口中缺少必填参数product_idtrade_type为JSAPI时product_id为必填参数");
}
//异步通知url未设置则使用配置文件中的url
if (!inputObj.IsSet("notify_url"))
{
inputObj.SetValue("notify_url", WeixinConfig.NotifyUrl);//异步通知url
}
inputObj.SetValue("appid", WeixinConfig.Appid);//公众账号ID
inputObj.SetValue("mch_id", WeixinConfig.MCHID);//商户号
inputObj.SetValue("spbill_create_ip", "8.8.8.8");//终端ip
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
//签名
inputObj.SetValue("sign", inputObj.MakeSign());
string xml = inputObj.ToXml();
var start = DateTime.Now;
// Log.Info("XcxPayApi", "UnfiedOrder request : " + xml);
string response = HttpPost(xml, url, "application/xml", timeOut);
//Log.Info("XcxPayApi", "UnfiedOrder response : " + response);
// WebHookHelper.WebHookmarkdownSend(response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);
WxPayData result = new WxPayData();
result.FromXml(response);
// ReportCostTime(url, timeCost, result);//测速上报网络不好时使用
return result;
}
/// <summary>
/// 生成随机数
/// </summary>
/// <returns></returns>
public static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
/// <summary>
/// POST请求
/// </summary>
/// <param name="postData"></param>
/// <param name="url"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="timeOut"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static string HttpPost(string postData, string url, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
{
postData = postData ?? "";
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
if (headers != null)
{
foreach (var header in headers)
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent client = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
client.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = httpClient.PostAsync(url, client).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
/// <summary>
/// 后台解密手机号
/// </summary>
/// <param name="encryptedData"></param>
/// <param name="IV"></param>
/// <param name="Session_key"></param>
/// <returns></returns>
public static string getPhoneNumber(string encryptedData, string IV, string Session_key)
{
try
{
byte[] encryData = Convert.FromBase64String(encryptedData); // strToToHexByte(text);
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Key = Convert.FromBase64String(Session_key); // Encoding.UTF8.GetBytes(AesKey);
rijndaelCipher.IV = Convert.FromBase64String(IV);// Encoding.UTF8.GetBytes(AesIV);
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
string result = Encoding.Default.GetString(plainText);
//动态解析result 成对象
dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
return model.phoneNumber;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
return "";
}
}
}
}