zoukankan      html  css  js  c++  java
  • 2.我的第一个小程序(获取用户信息--包括敏感信息)

    小友初学微信小程序开发,如果有些问题不对,请指出,谢谢

     

    我还是来说一下我的学习之路吧!!!

    源代码链接  https://pan.baidu.com/s/1tjPtLvAh0tIpgQFE3w1fIQ    密码:p4tl

    1.在开发小程序的时候,我们需要吧开发工具中的不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书这个给打开,因为我们在微信公众平台申请成为小程序开发者时需要设置一个叫做合法服务器域名的东西,每当我们请求服务器的时候,它都会验证我们请求的服务器是不是合法的(也就是我们设置的服务器地址)

    设置的合法服务器域名的地方 : 登入微信公众平台--->设置--->开发设置      (如果开发完了,上线的话,就可以设置这里)

    关闭验证的地方:打开小程序开发工具--->点击右上角的详情按钮--->最后有一个选项给打开        (一般我们在开发测试的时候最好打开,这样便于开发)

    2.因为我是学习所以我打开了此选项-----现在我们需要配置IIS(现在电脑基本自带了,没有的也可以去下载)

    这个是配置电脑的IIS

    如果这样就可以了,就错了,我们还需要在执行一些dism命令(按照顺序一步一步执行)原文地址

    dism /online /enable-feature /featurename:IIS-ISAPIFilter
    dism /online /enable-feature /featurename:IIS-ISAPIExtensions
    dism /online /enable-feature /featurename:IIS-NetFxExtensibility45
    dism /online /enable-feature /featurename:IIS-ASPNET45
    c:windowsmicrosoft.netframework64v4.0.30319aspnet_regiis.exe -i

    3.这全部弄完后,我们现在就可以开始实现我们第一个微信小程序了

    1)如果我们只是获取用户的一些基本信息(例如 昵称 头像等),不包括敏感信息(例如openid)

    小程序代码如下:

     wx.getUserInfo({
          success: function(res) {
            console.log(res.userInfo);
            console.log(res.userInfo.nickName);
            console.log(res.userInfo.avatarUrl);
          },
     })

    文档说明:

      为优化用户体验,使用 wx.getUserInfo 接口直接弹出授权框的开发方式将逐步不再支持。从2018年4月30日开始,小程序与小游戏的体验版、开发版调用 wx.getUserInfo 接口,将无法弹出授权询问框,默认调用失败。正式版暂不受影响。开发者可使用以下方式获取或展示用户信息:  详细链接

     改进后的小程序代码:

     wxml

    <button open-type="getUserInfo" id='btnInner' type='primary' lang="zh_CN" bindgetuserinfo="onGotUserInfo">进入小程序</button>

     js

    onGotUserInfo: function (e) {
        console.log(e);
        console.log(e.detail);
        console.log(e.detail.rawData);
        console.log(e.detail.userInfo);
    }

     效果:

            

     4.获取用户的敏感信息(关于网络请求的开发文档

    代码如下:

      wxml

    <button open-type="getUserInfo" id='btnInner' type='primary' lang="zh_CN" bindgetuserinfo="onGotUserInfo">进入小程序</button>

       js

    onGotUserInfo: function (e) {
        wx.login({
          success: function (logRes) {
            if (e.detail.errMsg) {
              wx.request({
                url: 'http://localhost:80/handlers/WxAjaxHandler.ashx',
                data: {
                  funType: "AES_decrypt",
                  iv: e.detail.iv,//偏移向量
                  code: logRes.code,//微信登入凭证-----方便后台用code和自己的appid换取session_key(密钥)
                  encryptedData: e.detail.encryptedData//密文 
                },
                header: {
                  "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                },   
                method: 'post',
                dataType: 'json',
                responseType: 'text',
                success: function (res) {
                  console.log(res.data);
                },
              })
            }
          },
        })
      }

       c#后台代码如下:

    using MyCommon;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    
    namespace WebApplication5.handlers
    {
        /// <summary>
        /// WxAjaxHandler 的摘要说明
        /// </summary>
        public class WxAjaxHandler : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                string strReturn = "";
                string funType = context.Request["funType"];
                if ("AES_decrypt".Equals(funType))
                {
                    string iv = context.Request["iv"];
                    string code = context.Request["code"];
                    string encryptedData = context.Request["encryptedData"];
                    AES aes = new AES();
                    strReturn = aes.AESDecrypt(code, iv, encryptedData);
                }
                context.Response.Write(strReturn);
            }
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }

      AES解密代码如下:查看自己的appid和AppSecret的地方:登入微信公众平台--->设置--->开发设置

    详细解密说明

    using Models;
    using Newtonsoft.Json;
    using System;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace MyCommon
    {
        public class AES:System.Web.UI.Page
        {
            private const string appid = "appid";//自己的appid
            private const string appsecret = "appsecret";//自己的小程序的密钥appsecret
    
            /// <summary>
            /// 1.对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
            /// 2.对称解密的目标密文为 Base64_Decode(encryptedData)。
            /// 3.对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。
            /// 4.对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回。
            /// </summary>
            /// <param name="code">登入凭证</param>
            /// <param name="iv">偏移向量</param>
            /// <param name="encryptedDataStr">要被解码的敏感数据源</param>
            /// <returns></returns>
            public string AESDecrypt(string code, string iv, string encryptedDataStr)
            {
                try
                {
                    string key = GetStrKeyByCode(code);
                    WxModel jsonKey = JsonConvert.DeserializeObject<WxModel>(key);
                    key = jsonKey.session_key;
                    RijndaelManaged rijalg = new RijndaelManaged();   
                    //设置 cipher 格式 AES-128-CBC    
                    rijalg.KeySize = 128;
                    rijalg.Padding = PaddingMode.PKCS7;
                    rijalg.Mode = CipherMode.CBC;
                    rijalg.Key = Convert.FromBase64String(key);
                    rijalg.IV = Convert.FromBase64String(iv);
                    byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);
                    //解密    
                    ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);
                    string result;
                    using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    new Exception(ex.Message);
                    return null;
                }
            }
    
            /// <summary>
            /// 根据微信登入凭证和自己的appid,来获取用户的密钥session_key
            /// </summary>
            /// <param name="code">登入凭证</param>
            /// <returns>一个json格式的字符串</returns>
            protected string GetStrKeyByCode(string code)
            {
                string responseContent = string.Empty;
                string reqUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&js_code={1}&secret={2}&grant_type=authorization_code";
                string url = string.Format(reqUrl, appid, code, appsecret);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Method = "GET";
                req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
    
                using (WebResponse webRes = req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(webRes.GetResponseStream(), Encoding.Default))
                    {
                        responseContent = sr.ReadToEnd().ToString();
                    }
                }
                return responseContent;
            }
        }
    }

     model

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Models
    {
        public class WxModel
        {
            public string opendid { get; set; }
            public string session_key { get; set; }
        }
    }

     返回效果如下:

    返回的信息列表

    {
        "openId": "OPENID",
        "nickName": "NICKNAME",
        "gender": GENDER,
        "city": "CITY",
        "province": "PROVINCE",
        "country": "COUNTRY",
        "avatarUrl": "AVATARURL",
        "unionId": "UNIONID",
        "watermark":
        {
            "appid":"APPID",
            "timestamp":TIMESTAMP
        }
    }

     

     

     

    链接:https://pan.baidu.com/s/1tjPtLvAh0tIpgQFE3w1fIQ 密码:p4tl

  • 相关阅读:
    Eclipse查看某个方法被哪些类调用
    ServletContextListener的作用
    ServletContextListener使用详解(监听Tomcat启动、关闭)
    通用测试用例大全
    Spring常用注解汇总
    Spring @Lazy
    Qt 事件处理 快捷键(重写eventFilter的函数,使用Qt::ControlModifier判断)
    Qt之使用setWindowFlags方法遇到的问题(追踪进入QWidget的源码分析原因,最后用WINAPI解决问题)good
    delphi idhttp 实战用法(TIdhttpEx)
    delphi 线程教学第一节:初识多线程(讲的比较浅显),还有三个例子
  • 原文地址:https://www.cnblogs.com/zjdbk/p/9942537.html
Copyright © 2011-2022 走看看