微信受权和sdk加密算法

准备工作:

要求效劳器 民众号 基本设置 这些微信民众平台上都有,就不引见了,接下来进入正题。

➣ 微信网页受权

node js-sdk 受权
民众平台的手艺文档目标为了简明扼要的交卸接口的运用,语句不免艰涩,这里写了些了我所明白的微信开放平台中关于应用node.js运用受权和js-sdk的一些要领,概况请见微信民众平台.假如用户在微信客户端中接见第三方网页,民众号能够经由过程微信网页受权机制,来猎取用户基本信息,进而完成营业逻辑。跟着微信管控更加严肃,像一些最基本的网页转发都须要受权处置惩罚才猎取到图片和形貌,形貌检察也是相称严厉。#

网页受权回调域名的申明

在微信民众号要求用户网页受权之前,开辟者须要先到民众平台官网中的“开辟 – 接口权限 – 网页效劳 – 网页帐号 – 网页受权猎取用户基本信息”的设置选项中,修正受权回调域名。请注重,这里填写的是域名(是一个字符串),而不是URL,因而请勿加 http:// 等协定头;

受权回调域名设置范例为全域名,比方须要网页受权的域名为:www.qq.com,设置今后此域名下面的页面http://www.qq.com/music.htmlhttp://www.qq.com/login.html 都能够举行OAuth2.0鉴权。但http://pay.qq.comhttp://music.qq.comhttp://qq.com没法举行OAuth2.0…

网页受权的两种scope的区分(snsapi_base snsapi_userinfo)

以snsapi_base为scope提议的网页受权,是用来猎取进入页面的用户的openid的,而且是寂静受权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是营业页面)

以snsapi_userinfo为scope提议的网页受权,是用来猎取用户的基本信息的。但这类受权须要用户手动赞同,而且因为用户赞同过,所以不必关注,就可在受权后猎取该用户的基本信息。

网页受权access_token和平常access_token的区分

微信网页受权是经由过程OAuth2.0机制完成的,在用户受权给民众号后,民众号能够猎取到一个网页受权特有的接口挪用凭据(网页受权access_token),经由过程网页受权access_token能够举行受权后接口挪用,如猎取用户基本信息;

其他微信接口,须要经由过程基本支撑中的“猎取access_token”接口来猎取到的平常access_token挪用。

➣ 详细步骤:

* 代码设置:

package.json
{
  "name": "js-sdk",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "body-parser": "^1.18.2",
    "cheerio": "^1.0.0-rc.2",
    "connect-mongo": "^2.0.1",
    "connect-redis": "^3.3.3",
    "cookie-parser": "^1.4.3",
    "crypto": "^1.0.1",
    "ejs": "^2.5.7",
    "express": "^4.16.2",
    "express-session": "^1.15.6",
    "fs": "^0.0.1-security",
    "mongoose": "^5.0.16",
    "morgan": "^1.9.0",
    "redis": "^2.8.0",
    "request": "^2.83.0",
    "sha1": "^1.1.1",
    "util": "^0.10.3",
    "utility": "^1.13.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^4.1.0",
    "gulp-babel": "^7.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-connect": "^5.2.0",
    "gulp-imagemin": "^4.1.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-minify-html": "^1.0.6",
    "gulp-px2rem-plugin": "^0.4.0",
    "gulp-uglify": "^3.0.0",
    "gulp-util": "^3.0.8"
  }
}

app.js
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const indexRoute = require("./app/routes/index.route");
const app = express();


app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'ejs');

/*设置静态文件途径*/
app.use(express.static(path.join(__dirname, "public")));

/*设置要求日记*/
app.use(logger("dev"));

/*剖析application/json花样数据*/
app.use(bodyParser.json());

/*剖析application/www-x-form-urlencoded花样数据*/
app.use(bodyParser.urlencoded({extended: false}));

/*剖析cookie*/
app.use(cookieParser());

/*剖析session*/
const session = require('express-session');
app.use(session({
    secret: "123456", //发起运用随机字符串
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 24 * 60 * 60 * 1000}
}));

/*设置路由*/
app.use("/", indexRoute);

app.use((req,res,next)=>{
    let err = new Error("Error 404, the source is not found!");
    err.status = 404;
    next(err);
});

app.use((err, req, res, next)=>{
    console.log(err);
    res.status(err.status || 500).send(err.message);
    next();
});

module.exports = app;
config/env.config.js
module.exports = {
  port:"80",
    "token":"yourtoken",
    "appID":"***",
    "appsecret":"***",
    "userAppID": "***",
    "userAppSecret": "***"
}
app/routes/index.routes.js
const express = require('express');
const path = require("path");
const authMiddleware = require("../middlewares/auth.middleware");
const router = express.Router();
const querystring = require('querystring');
const url = require('url');
const cheerio = require('cheerio')

router.get("/", authMiddleware.getCode, (req,res,next)=>{
    res.sendFile(path.join(__dirname, "../views/index.html"));
})

app/views/index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    这里只是测试getCode胜利与否
</body>
</html>

新建 app/config.access_token.json待用

新建 app/config.ticket.json待用

app/middlewares/auth.middlewares.js

exports.getUserInfo = (req,res,next)=>{
    console.log("<-----------------猎取getUserInfo--------------------->")
    console.log('----->req.access_token : '+req.access_token);
    let access_token = req.access_token;
    let openid = req.openid;
    let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
    request(url, (err,httpResponse,body)=>{
        console.log("---->--经由过程access_token和openid猎取到的用户个人信息 :")
        console.log(body);
        let result = JSON.parse(body);
        res.cookie("openid", result.openid, {maxAge: 24 * 60 * 60 * 1000, httpOnly: false});
        res.cookie("nickname", result.nickname, {maxAge: 24 * 60 * 60 * 1000, httpOnly: false});
        res.cookie("headimgurl", result.headimgurl, {maxAge: 24 * 60 * 60 * 10000, httpOnly: false});
        res.cookie("unionid", result.unionid, {maxAge: 24 * 60 * 60 * 1000, httpOnly: false})
        next();
    })
}

* 以snsapi_base为scope提议的受权

第一步:用户赞同受权,猎取code

app/middleares/auth.middlewares.js
const config = require("../../config/env.config");
const request = require("request");
const appid = config.appID;
const appsecret = config.appsecret;
/*猎取code*/
exports.getCode = function(req,res,next){
    console.log('--|cookies : '+ JSON.stringify(req.cookies));
    if(req.cookies.openid){
        next();
    }else{
        let back_url = escape(req.url);//解码,处理url?背面参数返回消逝题目 2.req.url 猎取URL
        console.log('猎取的url路由参数为 :'+back_url)
        let redirect_uri = `{你的域名}/getUserInfo?back_url=${back_url}`;    //注重这里实行了getUserInfo路由
        let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect `;
        console.log('重定向的url : '+url);
        //next();
        res.redirect(url);//res.redirect()重定向跳转 参数仅为URL时和res.location(url)一样
    };
};

第二步:经由过程code调换网页受权access_token

/*猎取access_token*/
exports.getAccess_token = (req,res,next)=>{
    console.log("<------------------猎取snsapi_base access_token----------------------->")
    console.log(JSON.stringify(req.query))
    let code = req.query.code;
    let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code `;
    request(url, (err, httpResponse, body)=>{
        console.log(err);
        console.log('--||--code调换的一切信息 :'+body);
        let result = JSON.parse(body);
        req.access_token = result.access_token;
        req.openid = result.openid;
        next();
    })
};

第三步:拉取用户信息(需scope为 snsapi_userinfo)

/getUserInfo运用了getAccess_token getUserInfo 中间件 在code没逾期的状况下能够进一步猎取access_token 和个人信息
router.get("/getUserInfo", authMiddleware.getAccess_token, authMiddleware.getUserInfo, function (req, res, next) {
    console.log("<------------------'/getUserInfo'----------------------->");
    console.log('----->|查询的url字符串参数 :' + JSON.stringify(req.query));
    let back_url = req.query.back_url;
    for (let item in req.query) {
        if (item !== "back_url" && item !== "code" && item !== "state") {
            back_url += "&" + item + "=" + req.query[item];
        };
    };
    console.log('---->|从新挑选途径back_url : ' + back_url);
    res.redirect(back_url);
});
# * 以snsapi_userinfo为scope提议的受权
app/middlewares/accessToken.middlesware.js
let weixinConfig = require("../../config/env.config.js");
let request = require("request");
let fs = require("fs");
//猎取accessToken
exports.accessToken = function (req, res, next) {
    console.log("<------------------'猎取snsapi_userinfo accessToken'----------------------->");
    let valide = isValide(); //{ code: 0, result: result.access_token } or{code:1001}
    if (valide.code === 0) {
        //access_token还没逾期,用之前的
        req.query.access_token = valide.result;
        next();
    } else {
        //从新猎取access_token && expire_in
        let appid = weixinConfig.appID;
        let secret = weixinConfig.appsecret;
        let url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        request(url, function (error, response, body) {
            let result = JSON.parse(body);
            let now = new Date().getTime(); //new Date().getTime() 取得的是毫秒
            result.expires_in = now + (result.expires_in - 20) * 1000; //expire_in平常是7200s 提早20毫秒

            req.query.access_token = result.access_token; //new access_token
            req.query.tokenExpired = result.expires_in; // 7200s
            next();
        });
    };
};

//猎取ticket
exports.ticket = function (req, res, next) {
    console.log("<------------------'猎取ticket'----------------------->");
    let ticketResult = isTicket();
    if (ticketResult.code === 0) {
        console.log('已经有了ticket : ' + JSON.stringify(ticketResult));
        req.query.ticket = ticketResult.result;
        next();
    } else {
        console.log("最先猎取ticket");
        let access_token = req.query.access_token;
        let _tokenResult = {
            access_token: req.query.access_token,
            expires_in: req.query.tokenExpired
        };
        let url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        request(url, function (err, response, body) {
            let result = JSON.parse(body);
            console.log(result);
            if (result.errcode == "0") {
                let now = new Date().getTime();
                result.expires_in = now + (result.expires_in - 20) * 1000; //   转变时刻为当前时刻的两小时后
                fs.writeFileSync("./config/access_token.json", JSON.stringify(_tokenResult)); //fs.writeFileSync:以同步的体式格局将data写入文件,文件已存在的状况下,原内容将被替代。
                fs.writeFileSync("./config/ticket.json", JSON.stringify(result));
                console.log('异步写入access_token ticket.json');
                req.query.ticket = result.ticket;
                next();
            };
        });
    };
};

function isValide() {
    //有用
    let result = fs.readFileSync("./config/access_token.json").toString(); //同步读取json文件 //这里用toString的缘由:读出来的数据是一堆包含着16进制数字的对象,必需经由过程toString转为字符串情势
    if (result) {
        result = JSON.parse(result);
        let now = new Date().getTime();
        if (result.access_token && result.expires_in && now < result.expires_in) {
            console.log("access_token 还在7200s之内,没有逾期"); //access_token有用 expires_in应当指的是间隔天生时刻的7200秒后
            return { code: 0, result: result.access_token };
        } else {
            console.log("access_token 失效");
            return { code: 1001 };
        }
    } else {
        return { code: 1001 };
    };
};

function isTicket() {
    let result = fs.readFileSync("./config/ticket.json").toString();
    console.log("result:", result);
    if (result) {
        result = JSON.parse(result);
        console.log(result);
        let now = new Date().getTime();
        if (result.ticket && result.expires_in && now < result.expires_in) {
            console.log("ticket有用,相沿当前ticket.json里的ticket");
            return { code: 0, result: result.ticket };
        } else {
            console.log("ticket无效须要猎取");
            return { code: 1001 };
        }
    } else {
        return { code: 1001 };
    };
}

accessToken.middlesware.js写了关于猎取以snsapi_userinfo为scope提议的网页受权的access_token ticket,并用fs以json字符串的情势存到当地,并检测逾期时刻,假如没逾期就继承读取运用,假如逾期就从新猎取并贮存在心的access_token ticket到当地

app/routes/index.routes.js

const crypto = require("crypto");
const sha1 = require("sha1");
const accessTokenMiddle = require("../middlewares/accessToken.middleware.js");
const weixin = require("../../config/env.config");

router.get("/weixin", accessTokenMiddle.accessToken, accessTokenMiddle.ticket, function (req, res, next) {
    console.log("<------------------'/weixin'----------------------->");
    console.log('----->| req.query : ' + JSON.stringify(req.query));
    crypto.randomBytes(16, function (ex, buf) {
        let appId = weixin.appID;
        let noncestr = buf.toString("hex");
        let jsapi_ticket = req.query.ticket;
        let timestamp = new Date().getTime();
        timestamp = parseInt(timestamp / 1000);
        let url = req.query.url;
        console.log("参数 :");
        console.log(noncestr);
        console.log(jsapi_ticket);
        console.log(timestamp);
        console.log(url);

        let str = ["noncestr=" + noncestr, "jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "url=" + url].sort().join("&");
        console.log("待殽杂加密的字符串 : ");
        console.log(str);
        let signature = sha1(str);

        console.log("微信sdk署名signature :");
        console.log(signature);

        let result = { code: 0, result: { appId: appId, timestamp: timestamp, nonceStr: noncestr, signature: signature } };

        res.json(result); //res.json 等同于将一个对象或数组传到给res.send()
    });
});

在html页面运用微信民众平台供应的API 须要援用 http://res.wx.qq.com/open/js/…
在静态文件中挪用分享功用的api 更多API请翻开 # 微信JS-SDK申明文档

public/index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <p>userList....</p>
    <button style="color:purple;" onclick="clickMe()">clickMe</button>
</body>
<script src="http://www.jq22.com/jquery/jquery-2.1.1.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script src="../js/userList.js"></script>
</html>
public/js/userList.js

let signatureUrl = url.split("#")[0];
let URL = encodeURIComponent(signatureUrl);

let title = "这是分享的表题目";
let desc = "this is description";
let shareUrl = window.location.href;
let logo = "http://yizhenjia.com/dist/newImg/logo.png";
SHARE(title, desc, shareUrl, logo); 

$.get("/weixin?url=" + URL, function(result) {
    if (result.code == 0) {
        wx.config({
            debug: false, // 开启调试形式,挪用的一切api的返回值会在客户端alert出来,若要检察传入的参数,能够在pc端翻开,参数信息会经由过程log打出,仅在pc端时才会打印。
            appId: result.result.appId, // 必填,民众号的唯一标识
            timestamp: result.result.timestamp, // 必填,天生署名的时刻戳
            nonceStr: result.result.nonceStr, // 必填,天生署名的随机串
            signature: result.result.signature, // 必填,署名,见附录1
            jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline", "chooseImage", "scanQRCode", "getLocation", "openLocation"] // 必填,须要运用的JS接口列表,一切JS接口列表见附录2
        });
    };
});

function SHARE(title, desc, shareUrl, logo) {        
    wx.ready(function() {
        // config信息考证后会实行ready要领,一切接口挪用都必需在config接口取得效果以后,config是一个客户端的异步操纵,所以假如须要在页面加载时就挪用相干接口,则须把相干接口放在ready函数中挪用来确保准确实行。关于用户触发时才挪用的接口,则能够直接挪用,不须要放在ready函数中。
        //分享
        wx.onMenuShareAppMessage({
            title: title, // 分享题目
            desc: desc, // 分享形貌
            link: shareUrl, // 分享链接
            imgUrl: logo, // 分享图标
            type: '', // 分享范例,music、video或link,不填默以为link
            dataUrl: '', // 假如type是music或video,则要供应数据链接,默以为空
            success: function() {
                用户确认分享后实行的回调函数
                alert("分享胜利!");
            },
            cancel: function() {
                // 用户作废分享后实行的回调函数
            },
            fail: function(err) {
                alert("分享失利");
            }
        });
    });
    wx.error(function(res) {
        // config信息考证失利会实行error函数,如署名逾期致使考证失利,详细错误信息能够翻开config的debug形式检察,也能够在返回的res参数中检察,关于SPA能够在这里更新署名。
        //alert("Error");
    });
}      

解释:

微信开辟必需在微信开辟者东西上开辟,且只能是默许80端口,在开辟中经常有80端口被占用的状况,假如有请运用

lsof -i tcp:80
kill -9 历程

假如想在手机上测试 并抓包数据 能够运用charles抓包东西

翻开charles 点击Proxy setting 设置 port
保证手机和电脑处于统一Wi-Fi下,设置手动代办 输入IP和端口 检察ip地点 :charles上可检察 或许终端输入ifconfig (cmd:ipconfig)
扫码或运用地点即可接见

在猎取以snsapi_userinfo为scope提议的网页受权的时刻运用的体式格局是fs贮存到当地的体式格局,你也能够采纳其他体式格局

    原文作者:不会飞的Porco
    原文地址: https://segmentfault.com/a/1190000017563804
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞