微信小程序-获取用户session_key,openid,unionid - 后端为 nodejs

版权声明:本文为 zzwwjjdj1(意外金喜) 原创文章,非商用自由转载-保持署名-注明出处,谢谢。 https://blog.csdn.net/zzwwjjdj1/article/details/79351005

微信小程序-获取用户session_key,openid,unionid - 后端为nodejs8.0+

步骤:

1、通过wx.login接口获取code既jscode,传递到后端;

2、后端请求

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

地址,就能获取到openid和unionid。

小程序接口promise化和封装 

1、utils文件夹下创建wechat.js文件

  1. /**
  2. * Promise化小程序接口
  3. */
  4. class Wechat {
  5. /**
  6. * 登陆
  7. * @return {Promise}
  8. */
  9. static login() {
  10. return new Promise((resolve, reject) => wx.login({ success: resolve, fail: reject }));
  11. };
  12. /**
  13. * 获取用户信息
  14. * @return {Promise}
  15. */
  16. static getUserInfo() {
  17. return new Promise((resolve, reject) => wx.getUserInfo({ success: resolve, fail: reject }));
  18. };
  19. /**
  20. * 发起网络请求
  21. * @param {string} url
  22. * @param {object} params
  23. * @return {Promise}
  24. */
  25. static request(url, params, method = "GET", type = "json") {
  26. console.log("向后端传递的参数", params);
  27. return new Promise((resolve, reject) => {
  28. let opts = {
  29. url: url,
  30. data: Object.assign({}, params),
  31. method: method,
  32. header: { 'Content-Type': type },
  33. success: resolve,
  34. fail: reject
  35. }
  36. console.log("请求的URL", opts.url);
  37. wx.request(opts);
  38. });
  39. };
  40. /**
  41. * 获取微信数据,传递给后端
  42. */
  43. static getCryptoData() {
  44. let code = "";
  45. return this.login()
  46. .then(data => {
  47. code = data.code;
  48. console.log("login接口获取的code:", code);
  49. return this.getUserInfo();
  50. })
  51. .then(data => {
  52. console.log("getUserInfo接口", data);
  53. let obj = {
  54. js_code: code,
  55. };
  56. return Promise.resolve(obj);
  57. })
  58. .catch(e => {
  59. console.log(e);
  60. return Promise.reject(e);
  61. })
  62. };
  63. /**
  64. * 从后端获取openid
  65. * @param {object} params
  66. */
  67. static getMyOpenid(params) {
  68. let url = 'https://xx.xxxxxx.cn/api/openid';
  69. return this.request(url, params, "POST", "application/x-www-form-urlencoded");
  70. };
  71. }
  72. module.exports = Wechat;

2、修改小程序的app.js文件

  1. let wechat = require('./utils/wechat.js');
  2. App({
  3. onLaunch() {
  4. this.getUserInfo();
  5. },
  6. getUserInfo() {
  7. wechat.getCryptoData()
  8. .then(d => {
  9. return wechat.getMyOpenid(d);
  10. })
  11. .then(d => {
  12. console.log("从后端获取的openid", d.data);
  13. })
  14. .catch(e => {
  15. console.log(e);
  16. })
  17. }
  18. })

后端nodejs,是用的express命令行生成的项目框架

1、创建common文件夹,创建utils文件,使用request模块请求接口,promise化request

  1. const request = require("request");
  2. class Ut {
  3.     /**
  4.      * promise化request
  5.      * @param {object} opts
  6.      * @return {Promise<[]>}
  7.      */
  8.     static promiseReq(opts = {}) {
  9. return new Promise((resolve, reject) => {
  10.     request(opts, (e, r, d) => {
  11. if (e) {
  12.     return reject(e);
  13. }
  14.         if (r.statusCode != 200) {
  15.     return reject(`back statusCode:${r.statusCode}`);
  16. }
  17. return resolve(d);
  18.     });
  19. })
  20.     };
  21. };
  22. module.exports = Ut;

2、新增路由,appId、secret在小程序的后台获取

  1. router.post("/openid", async (req, res) => {
  2. const Ut = require("../common/utils");
  3. try {
  4. console.log(req.body);
  5. let appId = "wx70xxxxxxbed01b";
  6. let secret = "5ec6exxxxxx49bf161a79dd4";
  7. let { js_code } = req.body;
  8. let opts = {
  9. url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
  10. }
  11. let r1 = await Ut.promiseReq(opts);
  12. r1 = JSON.parse(r1);
  13. console.log(r1);
  14. res.json(r1);
  15. }
  16. catch (e) {
  17. console.log(e);
  18. res.json('');
  19. }
  20. })

结果:


这个返回结果没有unionid,按照官方的说法,需要在微信开放平台绑定小程序;

如果需要解密和数据校验,请跳转这里

参考地址:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html

https://mp.weixin.qq.com/debug/wxadoc/dev/api/uinionID.html

意外金喜的博客:http://blog.csdn.net/zzwwjjdj1


展开阅读全文

没有更多推荐了,返回首页