c# 微信授权登录与微信支付
起因:最近工作上有一个项目需要在公众号页面用到评论然后发起微信支付的操作,之前未接触过微信,
特别记录一下开发过程的一些细节
stemp1:阅读微信公众号开发文档,十分重要
微信支付:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_4
2个页面讲解参数是比较清晰的,但是细节方面其实很多开发者都查阅了很多其他文献才能继续调试开发
stemp2: 登录授权需要前台获取到code 然后提交给后台,后台拿到code才能提交到微信拿到
//通过code获取openid
private string getToken(string code)
{
string _url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
WebClient wc = new WebClient();
//取得微信返回的openid,access_token数据
String strReturn = wc.DownloadString(_url);
return strReturn;
}
此处直接使用WebClient,是比较笨的方法,后来使用了几个统一的方法
多参数使用 string param = JSONHelper.ObjectToJSON(obj);转化后的串/// <summary>
/// POST方式调用接口
/// </summary>
/// <param name="Url">要请求Url</param>
/// <returns></returns>
public static string RequestUrlByPOST(string Url, string postData = "UTF-8")
{
string strHtml = "";
try
{
HttpWebRequest wr;
System.GC.Collect();
wr = (HttpWebRequest)WebRequest.Create(Url);
wr.Headers.Add("charset:utf-8");
var encoding = Encoding.GetEncoding("utf-8");
byte[] bytes = encoding.GetBytes(postData);
wr.Method = "POST";
wr.Timeout = Int32.MaxValue;
wr.Credentials = CredentialCache.DefaultCredentials;
wr.ContentType = "text/xml";
wr.ContentLength = bytes.Length;
wr.ServicePoint.Expect100Continue = false;
using (Stream requestStream = wr.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK && wr.HaveResponse)
{
if (response != null)
{
using (Stream stream = response.GetResponseStream())//获取返回的字符流格式
{
using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))//解决乱码:设置utf-8字符格式
{
if (sr != null)
{
strHtml = sr.ReadToEnd();
}
}
}
}
}
}
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
return strHtml;
}
/// <summary>
/// POST方式调用接口
/// </summary>
/// <param name="Url">要请求Url</param>
/// <returns>