在react页面内嵌“微信二维码”,实现PC端通过微信扫码进行登录。首先去
微信开放平台
注册一个账号,创建一个网站应用,提交网站备案审核,获取appid和appsecret;其他开发流程根据
微信文档
来进行操作。
react页面部分代码,引入内嵌二维码脚本,设置iframe标签支持跨域,自定义二维码样式:
componentWillMount(){
//引入“微信内嵌二维码”脚本
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = false;
script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
document.head.appendChild(script);
componentDidMount(){
* ... other code
//加载微信二维码
setTimeout(function() {
* 微信内嵌二维码自定义样式有两种方式实现
* 第一种是把自定义样式写在一个css文件里面,部署到一个https链接上
* 第二种是把自定义样式通过base64加密后设置在href上
var customeStyle = "data:text/css;base64,Lnd4X3FyY29kZSBpZnJhbWUgeyB3aWR0aDogMTYwcHg7IGhlaWdodDogMTYwcHg7IG1hcmdpbjogMDsgcGFkZGluZzogMDsgfQ0KLmxvZ2luUGFuZWwgeyBtYXJnaW46MDsgcGFkZGluZzogMDsgfQ0KLmxvZ2luUGFuZWwgLnRpdGxlLCAubG9naW5QYW5lbCAuaW5mbyB7IGRpc3BsYXk6IG5vbmU7IH0NCi5pbXBvd2VyQm94IC5xcmNvZGUgeyBtYXJnaW46IDA7IHdpZHRoOiAxNjBweDsgYm9yZGVyOiBub25lOyB9";
new WxLogin({
self_redirect: false,
id: "wx_login_container",
appid: "wx0*************", //微信开放平台网站应用appid
scope: "snsapi_login",
redirect_uri: encodeURI(location.origin), //设置扫码成功后回调页面
state: "" + (new Date()).getTime(),
style: "black",
href: customeStyle, //location.origin + "/css/wx_qrcode.css", //自定义微信二维码样式文件
//设置iframe标签可以进行跨域跳转
var qrcodeBox = document.getElementById("wx_login_container");
var iframes = qrcodeBox.getElementsByTagName("iframe");
if (iframes.length){
var ifr = iframe[0];
ifr.setAttribute("sandbox", "allow-scripts allow-top-navigation allow-same-origin");
}, 1000)