First of all, wechat users need to log in automatically to check the session. If the session expires, log in again
wx.checkSession({ success: function (res) { }, fail: function (res) { console.log("Need to sign in again"); wx.login({ success(res) { if (res.code) { console.log("User login voucher" + res.code); wx.request({ url: 'http://localhost:62923/index.aspx', data: { code: res.code, }, success(res) { console.log("Obtain openid: " + res.data.openid + " session_key: " + res.data.session_key); } }) } } }); } });
Login obtains code to exchange openid (user unique ID) and session key (decode encrypted information) from the background
string js_code = Request.QueryString["code"]; string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd4137ad6add09a40&secret=c147d93a4a810d42e0b4bde3a0d3fb51&js_code=" + js_code + "&grant_type=authorization_code"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); 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.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); Response.Write(retString);
Load user information (Revision) now use data component or button
//wx.getUserInfo({ // data: { withCredentials: true }, // success(res) { // console.log(res.userInfo.nickName + "/"); // } // });
Then, configure the Socket service - hpsocket = > httpserver to create websocket
(1) HP socket requires that hpsocket4c u.dll and HPSocketCS.DLL must be 32-bit and 64 bit is useless
(2) the applet connection cannot be placed in app.js, otherwise it cannot be connected and the handshake is stuck all the time.
const app = getApp(); const config = app.config; const wafer = require('../../vendors/wafer-client-sdk/index'); const lab = require('../../lib/lab'); Page({ data: { status: 'waiting', url: 'wss://' + config.host + '/ws', connecting: false, hintLine1: 'Complete server development,', hintLine2: 'Let the server support WebSocket Connect' }, /** * WebSocket Connected or not */ socketOpen: false, /** * Start connecting to WebSocket */ connect() { this.setData({ status: 'waiting', connecting: true, hintLine1: 'on connection', hintLine2: '...' }); this.listen(); wafer.setLoginUrl(`https://${config.host}/login`); wafer.login({ success: () => { const header = wafer.buildSessionHeader(); const query = Object.keys(header).map(key => `${key}=${encodeURIComponent(header[key])}`).join('&'); wx.connectSocket({ // The wx.connectSocket() API header parameter of the applet is invalid. Attach the session information to the URL url: `${this.data.url}?${query}`, header }); }, fail: (err) => { this.setData({ status: 'warn', connecting: false, hintLine1: 'Login failed', hintLine2: err.message || err }); } }); }, /** * Listen to WebSocket events */ listen() { wx.onSocketOpen(() => { this.socketOpen = true; this.setData({ status: 'success', connecting: false, hintLine1: 'Successful connection', hintLine2: 'Now you can go through WebSocket Sent and received message' }); console.info('WebSocket Connected'); }); wx.onSocketMessage((message) => { this.setData({ hintLine2: message.data }); lab.finish('websocket'); }); wx.onSocketClose(() => { this.setData({ status: 'waiting', hintLine1: 'WebSocket Closed' }); console.info('WebSocket Closed'); }); wx.onSocketError(() => { setTimeout(() => { this.setData({ status: 'warn', connecting: false, hintLine1: 'Error occurred', hintLine2: 'WebSocket Connection establishment failed' }); }); console.error('WebSocket error'); }); }, /** * Send a message with current time information */ send() { wx.sendSocketMessage({ data: new Date().toTimeString().split(' ').shift() + '.' + (new Date().getMilliseconds()) }); }, /** * Close WebSocket connection */ close() { this.socketOpen = false; wx.closeSocket(); } });
The next step is reverse proxy, because it must be accessed by wss legal domain name and forwarded to ws.