获取Openid

it2023-11-21  74

一、接口类

using System; using System.Data; using System.Text; using System.Web.Mvc; using Unionsoft.Application.Web.Utile; using Unionsoft.Application.WebApi.App_Start.Filter; using Unionsoft.Application.WebApi.Areas.HE_MemberMarketing.WechatInterface; using Unionsoft.Outside.ApiBusiness.Entity; namespace x { [ApiActionFilterAttribute] [ApiErrorHandleAttribute] public class OpenIDController:BaseApiController { [HttpGet] public ApiResult<WXAccessOpenIdEntity>GetOpenId(string code) { //实例化 ApiResult<WXAccessOpenId> result = new ApiResult<WXAccessOpenId>(); result.Data = WechatUtil.GetAccessOpenId(null,null,code.null); return result; } } } 二、调用方法 public static WXAccessOpenIdEntity GetAccessOpenId(string appid,string appsecret,string js_code,string grant_type) { if(appid==null&&appsecret==null&&grant_type==null) { appid="wx37af2f2bcfb8xxxx"; appsecret="e8f6825ec79ab2b4cf55bf27a674xxxx"; grant_type = "authorization_code"; } WXAccessOpenIdEntity entity = null; //获取session中的access_OpenId //1.声明strJson字符调用接口数据 string strJson=(string.Format("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&ja_code="+js_code+"&grant_type="+grant_type+"")); //2.创建HttpWebRequest请求接口数据 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strJson); //3.建立请求方式 request.Method = "Get"; //4.请求内容的类型 request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream myResponse = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream,Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); response.Close(); entity = JsonConvert.DeserilizeObject<WXAccessOpenIdEntity>(retString); return entity; } 三、Model实体 public class WXAccessOpenIdEntity { public string openid { get; set; } public string session_key { get; set; } public string unionid { get; set; } public string errcode { get; set; } public string errmsg { get; set; } }
最新回复(0)