Vue+abp 위 챗 스 캔 로그 인 실현 코드 예제
5920 단어 Vueabp위 챗 스 캔 로그 인
위 챗 오픈 플랫폼 계 정 등록\#
위 챗 오픈 플랫폼 에 등록 하면 오픈 플랫폼 이 공공 플랫폼 이 아니 라 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; }
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Vue Render 함수로 DOM 노드 코드 인스턴스 만들기render에서createElement 함수를 사용하여 DOM 노드를 만드는 것은 직관적이지 않지만 일부 독립 구성 요소의 디자인에서 특수한 수요를 충족시킬 수 있습니다.간단한 렌더링 예는 다음과 같습니다. 또한 v...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.