.net微信公众号或微信打开,静默授权,获取微信登录者的openid

ajax提交时openid会丢失,所以第一次获取了,就放到cookie里,再提交时使用

JS代码

<script>
        $(function () {
            $(".submit").click(function () {
                var selOp = $("#selOp").val();//类型
                var userTEL = $("#userTEL").val();//电话
                var proposal = $("#proposal").val();//评价内容openid
                var code = $("#hdcode").val();//
                var openid = $("#hdopenid").val();//
                if (selOp.length > 100 || proposal.length>200) {
                    alert("输入太多字符");
                    return false;
                }
                var url = "Opinion.aspx?act=SetOp";
                $.ajax({
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: { selOp: selOp, userTEL: userTEL, proposal: proposal, code: code },
                    success: function (r) {
                        if (r.code > 0) {
                            alert("操作成功");
                            $(".submit").hide();
                            $(".submit01").hide();
                        }
                        else {
                            alert("操作失败");
                            $(".submit").hide();
                            $(".submit01").hide();
                        }
                    }, complete: function (r) {

                    }
                });
            });

        });

    </script>

后台代码

using BLL;
using DAL;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyProject
{
    public partial class Opinion : System.Web.UI.Page
    {
        private string act = "";
        public int selOp;//= "660";//
        public string userTEL;//= "660";//
        public string proposal;//= "185";//
        public string submitisshow = "none";//默认隐藏提交按钮
        public string openid = "";//
                                  //微信公众号信息部分
        public string appid = "appid";
        public string appsecret = "appsecret";
        public string redirect_uri = HttpUtility.UrlEncode("http://Abadfn.com/Amdfas/Opinion.aspx");//微信登录后回调地址,登录后跳转页面
        public string scope = "snsapi_base";
//snsapi_base: ,获取到openid
//snsapi_userinfo: 获取openid和用户资料(昵称、头像、国、省、城市、性别、权限)
        public string  code="";
        public StringBuilder sbSubjects = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["openid"]==null)
                {
                    GetOpenid();
                }
                else
                {
                    openid = Convert.ToString(Request.Cookies["openid"].Value);
                }
                

                if (!string.IsNullOrEmpty(Request["act"]))
                {
                    act = Request.QueryString["act"];
                }
                switch (act)
                {
                    case "SetOp":
                        SetOp();
                        break;
                    default:

                        break;
                }

                string str = "";
            }
        }

        
        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <param name="grantType"></param>
        /// <returns></returns>
        public void GetOpenid()
        {
            /*
          *微信认证获取openid部分:
          *临时认证code
          */
            //微信认证部分:第二步 获得code
            try
            {
                code = Request["code"];

                if (string.IsNullOrEmpty(code))
                {
                    //code = "";
                    Response.Redirect("Opinion.html");
                    //如果code没获取成功,重新拉取一遍
                    //OpenAccess();//正常用这行取CODE
                }
                //微信认证部分:第三步 获得openid
                string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appsecret, code);
                HttpClient httpClient = new HttpClient();
                string result = HttpClientHelper.GetResponse(url);
                //Common.CreateWebLog("result的值", result.ToString());
                JObject outputObj = JObject.Parse(result);
                openid = outputObj["openid"].ToString();
                Common.CreateWebLog("获取openid成功", openid.ToString());

                HttpCookie objCookie = new HttpCookie("openid", openid);
                Response.Cookies.Add(objCookie);
                //return openid;
            }
            catch (Exception ex)
            {
                Common.CreateWebLog("获取openid失败", ex.ToString());
                code = "";
            }
            
        }

        /*
      * 接入入口
      * 开放到微信菜单中调用
      * @param $dir_url 来源url
      * @since 1.0
      * @return void
      */
        public void OpenAccess()
        {
            //判断session不存在
            //if (Session["openid"] == null)
            //{
            //    //认证第一步:重定向跳转至认证网址
            //    string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&&response_type=code&scope={2}&m=oauth2#wechat_redirect", appid, redirect_uri, scope);
            //    Response.Redirect("Opinion.html");   //https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 
            //    Response.Write("<script language=\"javascript\" type=\"text/javascript\">window.location.href = \""+ url + "\" </ script >");
            //}
            判断session存在
            //else
            //{
            //    //跳转到前端页面.aspx
            //    //Response.Redirect(Request.Url.ToString());
            //    Response.Write("<script language=\"javascript\" type=\"text/javascript\">window.location.href = \"" + Request.Url.ToString() + "\" </ script >");
            //}
        }

        






        private void SetOp()
        {
            int code = 1;
            selOp = Convert.ToInt32(Request["selOp"]);
            userTEL = Convert.ToString(Request["userTEL"]);
            proposal = Convert.ToString(Request["proposal"]);
            OpinionModel model = new OpinionModel();
            model.UserID = "";
            model.Openid = openid;
            model.UserTEL = userTEL;
            model.TypeID = selOp;
            model.Proposal = proposal;//openid  userID,openid,userTEL,typeID,proposal
            if (proposal.Length>200|| selOp.ToString().Length>200)
            {
                code = 0;

            }
            else
            {
                code=OpinionBLL.Add(model);
            }

            //code = Templates_Subjects_ResultBLL.Add02(toUserid, comeUserid, strpro);
            var rsp_obj = new
            {
                code = code,
                result = code.ToString()
            };
            Response.Write(JsonConvert.SerializeObject(rsp_obj));//将rsp_obj转化为json并输出
            Response.End();
        }


    }
}

中间跳转页

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="JS/jquery-3.4.1.js"></script>
    <script>
        $(function () {

            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=http://adfsduan.com/Amedfdfore/Opinion.aspx&response_type=code&scope=snsapi_base&m=oauth2#wechat_redirect";

        });
    </script>
</head>
<body>

</body>
</html>

 

 

posted @ 2020-06-19 15:22  离。  阅读(44)  评论(0编辑  收藏