1.在appsettings配置你的小程序配置信息
csharp
//微信小程序信息配置
"WechatConfig": {
"appid": "", //小程序ID
"secret": "" //小程序秘钥
},
2.请求接口时先获取Access_token
csharp
#region 获取小程序的Access_token
public object GetAccess_token(string appid, string secret)
{
string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);
req.Method = "GET";
req.ContentType = "textml;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string jsonData = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
string jsonSr = jsonData;
JObject jsons = JObject.Parse(jsonSr);
string accesstoken = jsons["access_token"].ToString();
return accesstoken;
}
#endregion
3.授权时获取手机号
csharp
#region 获取微信绑定手机号
public object GetPhoneNumber(string code, string appid, string secret)
{
string errCode = "";
try
{
var accesstoken = GetAccess_token(appid, secret);
string serviceAddress = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accesstoken;
JObject codes = new JObject();
codes["code"] = code;
string sendData = JsonConvert.SerializeObject(codes);
//换成Post请求方式
string jsonString = UrlPost(sendData, serviceAddress);
dynamic model = JToken.Parse(jsonString) as dynamic;
JObject json = JObject.Parse(jsonString);
errCode = json["errcode"].ToString();
string purePhoneNumber = json["phone_info"]["phoneNumber"].ToString();
//签发token
//string token;
//_authenservice.IsAuthenticated(code, out token);
return new { Code = 200, Msg = "获取成功", Tel = purePhoneNumber, Token = token };
}
catch (Exception e)
{
return new { Code = 0, Msg = "获取失败" + e.Message };
}
}
#endregion
4.微信接口要求必须使用Post请求方法
csharp
#region 提交Post请求
/// <summary>
/// 提交Post请求
/// </summary>
/// <param name="parameterData">参数集合</param>
/// <param name="serviceUrl">URL</param>
/// <param name="ContentType"></param>
/// <param name="Accept"></param>
/// <returns></returns>
public static string UrlPost(string parameterData, string serviceUrl, string ContentType = "application/json", string Accept = "application/json")
{
//先根据用户请求的uri构造请求地址
//string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
//创建Web访问对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//把用户传过来的数据转成"UTF-8"的字节流
byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(parameterData);
myRequest.Method = "POST";
//myRequest.Accept = "application/json";
//myRequest.ContentType = "application/json"; // //Content-Type: application/x-www-form-urlencoded
myRequest.AutomaticDecompression = DecompressionMethods.GZip;
myRequest.Accept = Accept;
//myRequest.ContentType = ContentType;
myRequest.ContentType = "application/json; charset=UTF-8";
myRequest.ContentLength = buf.Length;
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect = true;
//myRequest.Headers.Add("content-type", "application/json");
//myRequest.Headers.Add("accept-encoding", "gzip");
//myRequest.Headers.Add("accept-charset", "utf-8");
//发送请求
Stream stream = myRequest.GetRequestStream();
stream.Write(buf, 0, buf.Length);
stream.Close();
//通过Web访问对象获取响应内容
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
//通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
string returnData = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
reader.Close();
myResponse.Close();
return returnData;
}
#endregion
//小程序官方文档