微信网页授权

最近给一个客户写一个公众号抽奖页面,在开发之前,我发现客户的公众号是订阅号,然而只有服务号才能开通网页授权接口,
客户想在他们的订阅号上推送活动,最后解决的方法是用他们另一个服务号授权,订阅号推送。
长话不多说,其实微信官方文档写的也很清楚,有需要的小伙伴可以看一下官方文档。
官方文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
我采用的技术栈:后端node+egg框架,前端vue框架
下面我们就来讲讲如何实现的步骤:

  1. 在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
  2. 引导用户进入授权页面同意授权,获取code
    这里需要两个参数,一是你公众号的appid,二是授权后重定向的回调链接地址redirect_uri,必需使用 urlEncode 对链接进行编码处理,
    代码:
'https://open.weixin.qq.com/connect/oauth2/authorize?appid=(你的公众号appid)&redirect_uri=(编码后的重定向回调链接地址)&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE,获取code

created (){
    const that = this

    let { code } =  that.$route.query
    const url = '/outlets/api/getCode'
      that  
        .axios
        .post(url, that.qs.stringify(
          {
            code
          }
        ))
        
   }

3.后端获取code,通过code换取网页授权access_token,然后通过access_token和用户唯一标识openid获取用户信息

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  // 通过code码获取用户信息报名
  async getCode() {
       const { code } = this.ctx.request.body;
       this.ctx.body = await this.service.home.getCode(code);
    }
}
  module.exports = HomeController;
'use strict';

const Service = require('egg').Service;

class HomeService extends Service {
// eslint-disable-next-line no-empty-function
  async getCode(code) {
    let content = 0;
    // 获取公众号信息
    const appInfo = this.config.info;  // 这里的公众号appid和appSecret我放在了config.default.js下
    // 1.通过code换取网页授权access_token的URL链接
    const token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appInfo.appid}&secret=${appInfo.appSecret}&code=${code}&grant_type=authorization_code`;
    let token = await this.ctx.curl(token_url);
    token = JSON.parse(token.data.toString());
    const access_token = token.access_token; // 访问令牌
    const openid = token.openid; // 用户唯一标识
    // 2.获取用户信息
    const getUser_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
    let userInfo = await this.ctx.curl(getUser_url);
    return userInfo
   console.log( userInfo)  //这里就获取到了用户的信息,接下来按照自己的需求进行了
  }
 }
 
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容