目标
解决三件事。
- 小程序嵌入h5.
- 获取用户信息。
- 将用户信息以及一个唯一ID传入web-view环境里。
一、小程序里嵌入H5网页
这个很简单。
- 申请注册微信小程序(必须是国内企业版)。
- 登录管理后台,设置–开发设置–配置业务域名。
- 给你的网站配置ssl证书,开启https,开发阶段可以用natapp之类的内网穿透工具做。
- 下载安装微信开发者工具,使用小程序模式,新建小程序,在index页面或者其他页面(跳转一下)写:
<web-view src="你的URL"></web-view>
,保存编译运行即可。
二、获取用户信息
在微信调试工具里打开app.js,可以看到有个方法叫wx.login,已经有写好的基本逻辑。用户信息可以console.log查看一下res这个变量。
wx.login({
success: res => {
if (res.code) {
console.log(res)
}// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
可以看到,res里包含的只是一些基本用户信息,并不包含一个唯一的ID让我们确定这个用户。所以需要利用获取openid的机制,利用ajax与自建服务器交互。其逻辑图在小程序开发文档–登录机制里写的很清楚。
在这里我直接贴出来我的代码(C#,ashx一般处理程序),里面包含了服务器端获取openid的方式(将信息传到后台的时候,我用的是明文,实际上为了安全,可以自己加密一下再传到后台。)
小程序端:
wx.login({
success: res => {
if (res.code) {
//console.log(res)
//发起网络请求
wx.request({
url: 'https://我的URL路径/处理文件.ashx',
header: {
"Content-Type": "applciation/json"
},
method: 'POST',
data: {
code: res.code
},
success: function (res) {
wx.setStorageSync('openid', res.data);
// console.log(res.data)这里是成功后回调函数,已经拿到了服务器端获取到的openid
//利用小程序的缓存能力,将获取到的openid存进缓存里,在小程序的生命周期里,都可以随意全局调用。
}
})
}// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
服务器端:
<%@ WebHandler Language="C#" Class="wx" %>
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Collections.Generic;
public class wx : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
HttpRequest request = context.Request;
Stream stream = request.InputStream;
string json = string.Empty;
string responseJson = string.Empty;
if (stream.Length != 0)
{
StreamReader streamReader = new StreamReader(stream);
json = streamReader.ReadToEnd();
}
Dictionary<string, object> ob =JSONSerializer.Deserialize<Dictionary<string, object>>(json);
string js_code=ob["code"].ToString();
//这里就是与微信服务器交互,获取openid
string data = HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid=你的appid&secret=你的secret&js_code="+js_code+"&grant_type=authorization_code");
Dictionary<string, object> suggestions =JSONSerializer.Deserialize<Dictionary<string, object>>(data);
string openid = suggestions["openid"].ToString();
//将openid返回
context.Response.Write(openid);
}
public static string HttpGet(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close(