/** * * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下: * { * "access_token":"ACCESS_TOKEN", * "expires_in":7200, * "refresh_token":"REFRESH_TOKEN", * "openid":"OPENID", * "scope":"SCOPE", * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" * } * 其中access_token可用于获取共享收货地址 * openid是微信支付jsapi支付接口统一下单时必须的参数 * 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html * @失败时抛异常WxPayException */ public void GetOpenidAndAccessTokenFromCode(string code) { //构造获取openid及access_token的url SortedDictionary <string, object> dic = new SortedDictionary <string, object> { { "appid", Appid }, { "secret", Appsecret }, { "code", code }, { "grant_type", "authorization_code" } }; string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + ToUrl(dic); //请求url以获取数据 string result = WxHttpService.Get(url); //保存access_token,用于收货地址获取 JObject jd = (JObject)JsonConvert.DeserializeObject(result); AccessToken = (string)jd["access_token"]; //获取用户openid Openid = (string)jd["openid"]; //获取用户unionid if (jd["unionid"] == null) { Unionid = ""; } else { Unionid = (string)jd["unionid"]; } }
/// <summary> /// 获取用户信息 /// </summary> public void GetUserInfo() { //构造获取用户信息的url SortedDictionary <string, object> dic = new SortedDictionary <string, object> { { "access_token", AccessToken }, { "openid", Openid }, { "lang", "zh_CN" } }; string url = "https://api.weixin.qq.com/sns/userinfo?" + ToUrl(dic); //请求url以获取数据 string result = WxHttpService.Get(url); JObject jd = (JObject)JsonConvert.DeserializeObject(result); Nickname = (string)jd["nickname"]; Sex = (int)jd["sex"] > 0?(int)jd["sex"] - 1:(int)jd["sex"]; Headimgurl = (string)jd["headimgurl"]; }