ionic3+angular4的三方微信開發(登錄and分享)


登錄:

 1、在微信開放平台注冊開發者帳號,並擁有一個已審核通過的移動應用,並獲得相應的AppID和AppSecret,申請微信登錄且通過審核后,可開始接入流程。

 2、通過cordova添加微信插件;進入項目的目錄下,運行命令

    ionic cordova plugin add cordova-plugin-wechat  --variable wechatappid=AppID(就是你申請的AppID)

    3、微信需要在編譯文件中聲明變量,declare let Wechat;

         

    4、微信授權登錄,也是最重要的一步,獲取code,為獲取access_token提供參數
wechatLogin(){
       let loading = this.loadingCtrl.create({
             content: "跳轉微信登錄中...",//loading框顯示的內容
             dismissOnPageChange: true, // 是否在切換頁面之后關閉loading框
             showBackdrop: true //是否顯示遮罩層
       });
      loading.present();
      try {
           let scope = "snsapi_userinfo",
           state = "_" + (+new Date());
          Wechat.auth(scope, state, (response) => {
                 let res = response;

       console.log(JSON.stringify(res))
                //在調用service的getAccessToken方法獲取access_token,和acopenid,

     //然后再service的getWechatUserInfo方法獲取微信用戶的基本信息,最后保存登錄,完成
     }, (reason) => {

        console.log(reason);
      });
    } catch (error) {

       console.log(error);
    } finally {
        loading.dismiss();
    }
}

  5、獲取access_token和openid,這個方法接口放在service.ts文件里,由ts調用
           getAccessToken(data){

     //這里注意參數grant_type,官方文檔上說的值填寫authorization_code,實際上就是填寫的值是:"authorization_code";就行,不要理解成其他什么code

     let url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=??&secret=??&grant_type=authorization_code";
                 url = url+"&code="+data.code;
                return this.http.get(url, {}).toPromise().then(response => {
                         return response.json();
               }).catch(CommonService.handleError);
          }

  6、通過access_token和openid獲取用戶信息,這個方法接口放在service.ts文件里,由ts調用

    getWechatUserInfo(AccessToken,Openid){

      let  url="https://api.weixin.qq.com/sns/userinfo"

     url = url+"?access_token="+AccessToken+"&openid="+Openid;
    return this.http.get(url, {}).toPromise().then(response => {
    return response.json();
   }).catch(CommonService.handleError);
    }

分享:
  1、上面的1、2步需要操作一次
  2、代碼
//標題
title: string = "分享的標題";
//描述
description: string = "簡單描述!";
//分享鏈接
link: string = "分享后點擊查的url";
//分享圖片
image: string = "圖片鏈接";
//分享的目標://0:微信好友,1:朋友圈
scene: number=0;
wxShare() {
try {
Wechat.share({
// text: msg,
message: {
title: this.title,
description: this.description,
thumb: "",
media: {
type: Wechat.Type.WEBPAGE,
webpageUrl: url
}
},
scene: scene == 0 ? Wechat.Scene.SESSION : Wechat.Scene.Timeline // share to Timeline
}, function () {
console.log("分享成功");
}, function (reason) {
    console.log("分享失敗");
});
} catch (error) {
console.log(error);
}
}
//開發注意:APPID的一致性,需要做的功能在微信開發平台上相應的權限是否獲取,還有就是該微信的相關操作不能使用真機聯調,上面有看不明白的也可以查閱微信開發平台官方文檔。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM