vue微信公衆號授權頁面獲取openid、跨域

微信公衆號開發需要獲取用戶的openid,根據微信公衆號的官方文檔說明,需要做以下幾個準備工作

1.開發者需要先到公衆平臺官網中的“開發 - 接口權限 - 網頁服務 - 網頁帳號 - 網頁授權獲取用戶基本信息”配置選項中,修改授權回調域名。請注意,這裏填寫的是域名。注意:不能是ip地址

  如果不進行域名授權配置,微信在授權回調的時候會返回redirect_uri錯誤。

2.配置域名是要求在web服務器中有微信提供的能訪問到的文件,所以還需要一個web服務器,如下圖

 

第一步:跳轉到授權頁,獲取code

appid在微信開發者工具中獲取

 let urlNow=encodeURIComponent(window.location.href);
// let scope='snsapi_userinfo';    //snsapi_userinfo 非靜默授權用戶有感知 snsapi_base 靜默授權用戶無感知  

let url= 'https://open.weixin.qq.com'+'/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+urlNow+'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
window.location.href = url

授權成功後會重定向的頁面中,會帶有code參數,通過以下代碼獲取code,code每5分鐘會更新,請勿保存。

getUrlKey:function(name){//獲取url 參數
    return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
},

第二步.通過code換取網頁授權openid

appsecret在微信開發者工具中獲取

this.$axios.get('https://api.weixin.qq.com'+'/sns/oauth2/access_token?appid='+appid+'&secret='+appsecret+'&code='+code+'&grant_type=authorization_code')
  .then(res=>{
    
      this.openid = res.data.openid;
   }).catch(error=>{
        
})

 

第三步.解決剛開始的兩個問題

3.1由於本地測試沒有域名,可以使用natapp用臨時域名映射到本地。參考

3.2有了配置後需要配置web服務器,這裏我使用Tomcat,下載Tomcat並安裝。

打開Tomcat的目錄進入webapps目錄下,新建文件夾:myapp,並在該目錄下創建WEB-INF文件夾,新建web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

  <display-name>myword</display-name>
  <description>
     <error-code>404</error-code>
     <location>/index.html</location>
  </description>

</web-app>

將從微信公衆號下載下來的text文件放入myapp文件夾下,同時在微信開發者工具配置域名。點擊保存

第四步.vue打包

打包前在vue.config.js中配置(這裏使用vue-cli3.0)。

  publicPath: process.env.NODE_ENV === 'production'
    ? '/myapp/'
    : '/',

執行 npm run build

將打包好的放入tomcat的myapp文件夾下

此時的目錄結構如上。

啓動Tomcat,mac的啓動命令: sudo sh ./startup.sh

 

5.跨域

由於微信限制,微信授權頁面必須在微信開發中工具中打開。由於本地服務和微信接口的api存在跨域問題,本地調試時可以調用一下命令打開微信開發中工具:

open -a /Applications/wechatwebdevtools.app --args --disable-web-security --user-data-dir --allow-running-insecure-content

或者使用Nginx解決跨域問題。

在微信開發中工具中輸入: http://xxx.xxx.cc/myapp

 

vue的完整代碼

created(){
   let code= this.getUrlKey("code");
   if(code){
      this.$axios.get('https://api.weixin.qq.com'+'/sns/oauth2/access_token?appid='+appid+'&secret='+appsecret+'&code='+code+'&grant_type=authorization_code')
      .then(res=>{
           this.openid = res.data.openid;
       }).catch(error=>{
                
      })
   }else{
            this.getCodeApi();
   }
},
methods:{
    getCodeApi(){//獲取code   
       let urlNow=encodeURIComponent(window.location.href);
       // let scope='snsapi_userinfo';    //snsapi_userinfo snsapi_base   //靜默授權 用戶無感知
   
       let url= 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+urlNow+'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
       window.location.href = url
    },
    getUrlKey:function(name){//獲取url 參數
       return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
        },
    },

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章