using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using Essensoft.AspNetCore.Payment.Alipay.Domain;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
namespace New_College.Common
{
public class WeixinHelper
{
///
/// 获取AuthCodeSession
///
///
///
///
///
public static T AuthCode2Session(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(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 获取AccessToken
///
///
///
///
///
public static T GetAccessToken(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(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static T WxaBusinessGetUserPhoneNumber(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(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("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
}
if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
{
throw new Exception("统一支付接口中,缺少必填参数product_id!trade_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;
}
///
/// 生成随机数
///
///
public static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
///
/// POST请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
///
///
///
public static string HttpPost(string postData, string url, string contentType = null, int timeOut = 30, Dictionary 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;
}
}
}
///
/// 后台解密手机号
///
///
///
///
///
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 "";
}
}
}
}