【uniappAPPがAlipay認証ログインを実現】

同社が開発したプロジェクトはuni-appで開発されており、uni-ap公式サイトではAlipayのサードパーティログイン(統合QQ、Weibo、WeChat認証ログイン)を実現していないため、この機能にはAlipay認証ログインが必要となる。まさか、インターネット上でチュートリアルを探すしかありません。

まず第一に、Alipay ログインを実現したいので、次のように Alipay で接続された接続を開く必要があります。

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

実装手順:

1. クリックイベントで plus.runtime モジュールを使用して、Alipay を呼び出し、認証アドレスを開きます (認証アドレスはバックエンドで結合するか、フロントエンドでハードコーディングできます。個人的には、バックエンドの取得が必要であると感じています)比較的良いです)


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

//***********************
//***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'
  );
}
 

注: appId 20000067 は固定値であり、APPID に変更する必要はありません。

Alipayで通常にログインするには、この方法で電話します。

2. アプリの URL スキームを設定する

これは Android プラットフォームの UrlSchemes 設定です。サードパーティ アプリケーションが
HBuilder/HBuilderX の組み込み実機実行ベースの UrlSchemes を呼び出すのを容易にするために、開発者がデバッグするのに便利な「hbuilder://」になっています。

接続設定方法:https://uniapp.dcloud.io/tutorial/app-android-schemes.html
ここに画像の説明を挿入

3. パッケージ化 (urlscheme) 設定を送信した後、再パッケージ化する必要があります (ベースを再パッケージ化することも、クラウド アプリを直接パッケージ化することもできます。ベースを構築することをお勧めします (Alipay から戻った後にイベントを記述する必要があるため) ])

4. (redirect_uri) ページを作成し、書き込みが完了したら、それをバックエンドに取り込んでサーバーに配置すると、基本的には成功します。

APP へのジャンプがない場合は、URL スキームが正しく入力されていないか、APP がパッケージ化されていないことを意味します

<!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>

注意してください: alipayUrl のコールバック アドレス (redirect_uri) はパブリック ネットワークから直接アクセスできる必要があります。形式は http:// または https:// で始まります。イントラネット アドレス (http:/ など) を入力しないでください。 /localhost :8080/) および相対アドレス (/pages/aliPay) など。それ以外の場合、リダイレクトで 404 が表示されるか、アクセスできません。

5. ページ上の Alipay アプリによって送信された auth_code をリッスンし、auth_code を通じて userId を取得して、Alipay の認証を完了します (redirect_uri ページで userId を直接取得して、APP に戻ることもできます。または、アプリに戻り、auth_code Get userId を通じてバックエンドをリクエストできます [PS: 後者のスキームはより柔軟です])

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' });
					});
				}
			}
		},

その結果、機能はほぼ完成しました。最後に、ご指摘いただいた 2 人の偉い人に感謝しなければなりません。リンクは次のとおりです:
https://blog.csdn.net/z1783883121/article/details/116268402
https:// ask.dcloud.net.cn/article/36971

おすすめ

転載: blog.csdn.net/qq_39236283/article/details/125968384