Vue+abp 위 챗 스 캔 로그 인 실현 코드 예제

최근 시스템 에 서 는 위 챗 스 캔 코드 로 로그 인 해 야 하 며 위 챗 공식 문서 와 인터넷 검색 관련 문헌 에 따라 이 루어 졌 다.필요 한 사람 에 게 나 누 어 주 는 것 도 자신의 노트 로 삼 는 다.백 엔 드 시스템 은 ABP 를 기반 으로 하기 때문에 일부 코드 는 abp 인 터 페 이 스 를 직접 사 용 했 고 코드 를 직접 복사 하여 컴 파일 할 수 없습니다.
위 챗 오픈 플랫폼 계 정 등록\#
위 챗 오픈 플랫폼 에 등록 하면 오픈 플랫폼 이 공공 플랫폼 이 아니 라 300 위안 이 필요 한 다음 에 사이트 응용 을 신청 해 야 합 니 다.심 사 를 통과 한 후 AppID 와 AppSecret 및 등 록 된 사이트 url 을 얻 을 수 있 습 니 다.이 url 아래 주소 인 위 챗 스 캔 후에 야 리 셋 할 수 있 습 니 다.

구체 적 인 신청 조건 은 공식 문 서 를 보십시오.
로그 인 QR 코드 생 성\#
vue 로그 인 페이지 에 로그 인 QR 코드 를 삽입 합 니 다.공식 문서 에 따라 페이지 에 div 요 소 를 넣 으 면 QR 코드 는 이 요소 에 있 습 니 다.var obj=new WxLogin 은 mounted 방법 에 넣 어야 합 니 다.이 때 vue 는 dom 요 소 를 dom 트 리 에 초기 화하 여 마 운 트 합 니 다.vue 공식 문서 의 생명주기 소 개 를 참조 할 수 있 습 니 다.

<template>
 <div id="login" class="login"></div>
</template>

<script>
export default {
 name: "WXLogin",
 data: function() {
  return {};
 },
 mounted() {
  this.wechatHandleClick();
  document.getElementsByTagName("iframe")[0].height="320";
  document.getElementsByTagName("iframe")[0].style.marginLeft="30px";
 },
 methods: {
  wechatHandleClick() {
   let ba64Css =
    "css  base64  ";//     https     ,         base64,      https,       https              css    
   const appid = "       Appid";
   const redirect_uri = encodeURIComponent("http://*/#/login");
   var obj = new WxLogin({
    id: "login", //div id
    appid: appid,
    scope: "snsapi_login",//    
    redirect_uri: redirect_uri, //    
    // href: "http://*/static/UserCss/WeChart.css" //       ,                。    
    href: "data:text/css;base64," + ba64Css
    // state: "", //  ,     
    // style: "", //     "black"、"white"  ,         
   });
  }
 }
};
</script>

리 셋 이벤트 등록\#
사용자 가 코드 를 스 캔 한 후 위 챗 은 이전 단계 에 제 공 된 redirect 를 되 돌려 줍 니 다.uri,위 챗 리 셋 을 모니터링 하고 위 챗 으로 되 돌아 오 는 code 로 백 엔 드 를 요청 합 니 다.백 엔 드 에서 위 챗 서버 를 방문 하여 token 및 사용자 openID 를 가 져 옵 니 다.
리 셋 페이지 에서 경로 변경 사건 을 감시 하여 위 챗 리 셋 을 감시 합 니 다(제 QR 코드 와 리 셋 이 같은 경로 페이지 에 있 기 때 문 입 니 다).다른 더 좋 은 방법 이 있 으 면 저 에 게 알려 주세요.

 @Watch("$route")
 async RouteChange(newVal, oldVal) {
  await this.weixinRedirect();
 }
 //       
 async weixinRedirect() {
  let code = this.$route.query.code;
  let state = this.$route.query.state;
  if (code) {
   let wxTo = {
    code,
    state
   };
   //    
   this.$http("*/WeixinRedirect",data:wxTo).then((token)=>{
     //    , token  cookie
     //     
      this.$router.replace({ path: "/", replace: true });
   }).catch(error => {
     //      
     this.$router.replace({ path: "/login", replace: true });
    });
  }
 }
}
백 엔 드 수신 코드 요청 token\#
apptsettings.json 에 AppId 와 AppSecret 설정

[HttpPost]
public async Task<AuthenticateResultModel> WeixinRedirect(string code, string state)
{
  if (code.IsNullOrEmpty())
  {
    throw new UserFriendlyException("      ,     ");
  }
  var appid = configuration["Authentication:Wechat:AppId"];
  var secret = configuration["Authentication:Wechat:AppSecret"];
  var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code=[code]&grant_type=authorization_code";
  var httpClient = httpClientFactory.CreateClient();
  httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  httpClient.Timeout = TimeSpan.FromMinutes(3);

  var resstr = await httpClient.GetStringAsync(url);
  try{
    //                  
   var res = JsonSerializationHelper.DeserializeWithType<WeiXinAccess_tokenResponse>(resstr);
  }catch (Exception e)
  {
    throw new UserFriendlyException("    access_token  ");
  }
  if (res == null || res.openid.IsNullOrEmpty())
  {
    throw new UserFriendlyException("    access_token  ");
  }
  var userId = //  openID    id,                    ,             openID      id;
  //        
  if (!userId.IsNullOrEmpty()&&long.TryParse(userId, out long id))
  {
    var user = await _userManager.GetUserByIdAsync(id);
    var loginResult = await _logInManager.LoginByUser(user);
    string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));

    return new AuthenticateResultModel
    {
      AccessToken = accessToken,
      EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
      ExpireInSeconds = (int)_tokenConfiguration.Expiration.TotalSeconds,
      UserId = loginResult.User.Id
    };
  }
  throw new UserFriendlyException("        ,            。");

}

WeiXinAccess_tokenResponse 형식

public class WeiXinAccess_tokenResponse
{
  public string access_token { get; set; }
  public int expires_in { get; set; }
  public string refresh_token { get; set; }
  public string openid { get; set; }
  public string scope { get; set; }
  public string unionid { get; set; }
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기