微信公众号网页授权

最近给一个客户写一个公众号抽奖页面,在开发之前,我发现客户的公众号是订阅号,然而只有服务号才能开通网页授权接口,
客户想在他们的订阅号上推送活动,最后解决的方法是用他们另一个服务号授权,订阅号推送。
长话不多说,其实微信官方文档写的也很清楚,有需要的小伙伴可以看一下官方文档。
官方文档地址: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)  //这里就获取到了用户的信息,接下来按照自己的需求进行了
  }
 }
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值