[uniappAPP realizes Alipay authorized login]

The project developed by the company is developed with uni-app, and the function requires Alipay authorized login, because the uni-ap official website does not realize the third-party login of Alipay (integrated QQ, Weibo, WeChat authorized login). No way, I can only search for tutorials all over the Internet.

First of all, because you want to realize Alipay login, you must open our spliced ​​connection in Alipay like this:

https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=商户的APPID&scope=auth_user&redirect_uri=ENCODED_URL&state=init 

Implementation steps:

1. Use the plus.runtime module on the click event to call Alipay to open the authorization address (the authorization address can be spliced ​​at the back end or hard-coded at the front end, personally feel that the back-end acquisition is relatively better)


//相关示例代码:(该代码会打开支付宝授权,授权之后会在支付宝中打开你所设置的【回调地址】网页)

//***********************
//***url授权地址由后端拼接也可以前端写死***
//***以下是一个拼接示例,仅需修改app_id的值和redirect_uri的值***
//***app_id是商户的APPID,redirect_uri是页面跳回地址(授权成功之后会在支付宝中打开这个地址)***
//***********************
let urls='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2021001183611007&scope=auth_userinfo&redirect_uri=https://shandianlaoshi.com/api/user/zfb_url';
urls=encodeURIComponent(urls);//将地址编码成浏览器访问的格式
// 判断平台
if (plus.os.name == 'Android') {
    
    
  plus.runtime.openURL(
    'alipays://platformapi/startapp?appId=20000067&url=' + urls,
    res => {
    
    
	//这里写打开URL地址失败后的处理
      console.log(res);
      uni.showModal({
    
    
        content: '本机未检测到对应客户端,是否打开浏览器访问页面?',
        success: function (res) {
    
    
          if (res.confirm) {
    
    
            //plus.runtime.openURL();
          }
        }
      });
    },
    'com.eg.android.AlipayGphone'
  );
} else if (plus.os.name == 'iOS') {
    
    
  plus.runtime.openURL(
    'alipay://platformapi/startapp?appId=20000067&url=' + urls,
    res => {
    
    
      console.log(res);
      uni.showModal({
    
    
        content: '本机未检测到对应客户端,是否打开浏览器访问页面?',
        success: function (res) {
    
    
          if (res.confirm) {
    
    
            //plus.runtime.openURL(url);
          }
        }
      });
    },
    'com.eg.android.AlipayGphone'
  );
}
 

Note: The appId of 20000067 is a fixed value and does not need to be changed to your APPID.

Call in this way to log in with Alipay normally.

2. Set a url scheme for your APP

This is the Android platform setting UrlSchemes. In order to facilitate the third-party application to call
the UrlSchemes of HBuilder/HBuilderX's built-in real machine running base, it is "hbuilder://", which is convenient for developers to debug.

Setting method connection: https://uniapp.dcloud.io/tutorial/app-android-schemes.html
insert image description here

3. After submitting the packaging (urlscheme) settings, it needs to be repackaged (you can re-package the base or directly package the cloud App, it is recommended to build the base [because you need to write the event after returning from Alipay])

4. Write the (redirect_uri) page, and after the writing is completed, take it to the backend and put it on the server, and it will be basically successful

If there is no jump to your APP, it means that your url scheme is not filled in correctly or your APP is not packaged

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XXXX登录</title>
    <style>
        body {
    
    
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            height: 90vh;
            font-size: .9375rem;
        }
        content{
    
    
            display: flex;
            flex-direction: column;
            justify-content: center ;
            align-items: center;
        }

        .logo_img {
    
    
            width: 6.875rem;
            height: 6.875rem;
            margin-bottom: .625rem;
        }

        #box {
    
    
            width: 80%;
            height: 2rem;
            text-align: center;
            line-height: 2rem;
            border-radius: 20px;
            background-color: rgb(23, 120, 194);
            color: white;
            margin: .9375rem auto;
        }

        .desc {
    
    
            font-size: .3125rem;
            color: gray;
        }
    </style>
	

</head>

<body>
    <content>
        <img src="./logo.png" class="logo_img">
        <div id="box" onclick="func()">返回XXXX</div>
        <div class="desc">您已授权登录,请点击返回XXXX</div>
    </content>
<script>
var code ;
function getQueryVariable(variable) {
    
      
	var query = window.location.search.substring(1);  
	var vars = query.split("&");  
	for (var i = 0; i < vars.length; i++) {
    
      
		var pair = vars[i].split("=");  
		if (pair[0] == variable) {
    
      
			return pair[1];  
		}  
	}  
	return (false);  
}  


function func(){
    
    
 
  code = getQueryVariable("auth_code");  
// 判断是那种设备
  let u = navigator.userAgent;
  console.log(u);
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;   // Android系统或者uc浏览器
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   // iOS系统

  // 如果为Android系统
  if (isAndroid) {
    
    
    window.location.href = "hbuilder://?auth_code="+code; // 注意*** 这里需要修改为刚刚设置的urlscheme,auth_code需要后端拼接。auth_code只有后端才能拿到
    window.setTimeout(function () {
    
    
      window.location.href = "http://www.baidu.com";   // 3s后如果不能跳转到 App,则跳转到 App 的下载地址,一般是应用宝的对应的下载地址
    }, 2000);
    return;
  }

  // ios设备:原理:判断是否认识这个协议,认识则直接跳转,不认识就在这里下载appios();
  if (isiOS) {
    
    
    let startIndex = u.indexOf('iPhone OS') + 9;
    let endIndex = u.indexOf('like Mac OS') - 1;
    let num = +u.slice(startIndex, endIndex).split('_')[0];  // 计算版本号的前面数值
    if (num < 9) {
    
    
      window.location.href = "hbuilder://?auth_code="+code;   //  注意*** 这里需要修改为刚刚设置的urlscheme,auth_code需要后端拼接。auth_code只有后端才能拿到
    } else {
    
    
      window.location.href = " ";   // universal link 链接
    }
    window.setTimeout(function () {
    
    
      window.location.href = " ";   // 3s后如果不能跳转到 App,则跳转到 AppStore 的下载地址
    }, 3000);
    return;
  };
}


</script>

</body>

</html>

Do pay attention: the callback address (redirect_uri) in alipayUrl must be directly accessible from the public network, the format starts with http:// or https://, please do not fill in the intranet address (such as: http://localhost :8080/) and relative address (/pages/aliPay), etc., otherwise the redirect will prompt 404 or inaccessible.

5. Listen to the auth_code sent by the Alipay App on the page, and then obtain the userId through the auth_code to complete the authorization of Alipay (you can directly obtain the userId on the redirect_uri page and then jump back to the APP, or you can return to the App and request the backend through the auth_code Get userId [PS: the latter scheme is more flexible])

onShow: function() {
    
    
			let args = plus.runtime.arguments;
			//console.log(args); //这里可以看到从后端拿过来的urlscheme
			if (args) {
    
    
				plus.runtime.arguments=null;//进入之后就把urlscheme清空要不然下一次oushow时还会执行
				// 处理args参数,如直达到某新页面等
				//通过code请求获取user_id
				var authCode = args.split("=")[1];
				if(authCode!=undefined&&authCode!=""&&authCode!=null){
    
    
					this.$busapi.restAuth.queryAlipayInfo("authCode="+authCode).then(res => {
    
    
						if (res.code == '0000') {
    
    
							if(res.data.userId){
    
    
								this.whetherBinding(res.data.userId,"alipay");
							}
							
						}else{
    
    
							this.$message({
    
     message: res.msg, type: 'error' });
						}
					})
					.catch(res => {
    
    
						this.$message({
    
     message: res.errmsg, type: 'error' });
					});
				}
			}
		},

As a result, the function is almost completed. Finally, I must thank the two big guys for their pointers. The link is as follows:
https://blog.csdn.net/z1783883121/article/details/116268402
https://ask.dcloud. net.cn/article/36971

Guess you like

Origin blog.csdn.net/qq_39236283/article/details/125968384