代码改变世界

C#获取微信小程序openid等用户信息(前端+asp.net服务器端代码)

2019-07-14 16:59  .net小跟班(杜)  阅读(6161)  评论(2编辑  收藏  举报

服务器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;
using System.Data;
using System.Text;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// api 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
[System.Web.Script.Services.ScriptService]
public class api : System.Web.Services.WebService
{
    [WebMethod]
    public void OpenID(string code)
    {
        //临时登录凭证code 获取 session_key 和 openid
        string js_code = code;
        //此处填写自己小程序的appid和secret
        string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=" + js_code + "&grant_type=authorization_code";
        
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
        request.Method = "GET";
        request.ContentType = "textml;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
        string jsonData = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();

        string jsonString = jsonData;
        JObject json = JObject.Parse(jsonString);
        string openid = json["openid"].ToString();

        Context.Response.Write(GetJson(openid));
    }

    #region  把对象序列化 JSON 字符串
    /// <summary>
    /// 把对象序列化 JSON 字符串 
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="obj">对象实体</param>
    /// <returns>JSON字符串</returns>
    public static string GetJson<T>(T obj)
    {
        //记住 添加引用 System.ServiceModel.Web 
        /**
         * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
         * */
        DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            json.WriteObject(ms, obj);
            string szJson = Encoding.UTF8.GetString(ms.ToArray());
            return szJson;
        }
    }
    #endregion
}