微信公衆號H5用戶受權

 其實不是很難,總結起來就是:ios

1.微信公衆號管理後臺設置redirect_uri。express

2.而後發起一個請求去重定向獲取code,而後把獲取到code以後重定向的URL放在獲取code的URL中axios

3.獲取到code以後就能夠獲取到openid一些之類的信息了api

上代碼:微信

const express = require('express')
const router = express.Router()

router.get('/oauth2/snsapi_base', function (req, res, next) {
  const redirectUrl = 'beta.weixin.douanquan.com/weixin/oauth2/snsapi_base_cb?sourceurl=' +
    encodeURIComponent((req.query.sourceurl || '/personal'))
  console.log("mmm----------", redirectUrl)
  console.log('/oauth2/snsapi_base', hospitalId, redirectUrl)

  res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?' +
    'appid=' + "wxf1a4bbd24d59f858" +
    '&redirect_uri=' + encodeURIComponent(redirectUrl) +
    '&response_type=code' +
    '&scope=snsapi_base' +
    '&state=' + hospitalId +
    '#wechat_redirect'
  )
})

router.get('/oauth2/snsapi_base_cb', async function (req, res, next) {
  const hospitalId = req.session.hospitalId
  const wxConfig = config.wxAppidList[hospitalId]
  res.cookie("qqq","jjj")
  console.log('/oauth2/snsapi_base_cb', hospitalId, req.query.code, wxConfig)

  const { data } = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
    params: {
      appid: wxConfig.appId,
      secret: wxConfig.appSecret,
      code: req.query.code,
      grant_type: 'authorization_code'
    }
  })
  res.cookie('openid', data.openid)
 
})

這種是靜默受權的方式,換成彈框的把scope改爲snsapi_userinfocookie

相關文章
相關標籤/搜索