検索
ホームページWeChat アプレットミニプログラム開発Alipay ミニ プログラムの開発 - Alipay の SDK を使用してユーザー ID を取得する

Alipay アプレットはフロントエンドでユーザーのニックネームとアバターを取得することしかできませんが、これでは十分ではありません。現時点では、Alipay の SDK を使用してユーザー ID を取得する必要があります。もちろん、フロントエンドは httprequest リクエストを発行する必要があります。以下は、前の 2 つの記事の例に基づいて変更されています

Alipay アプレット フロントエンド

app.js

App({
  globalData:{
    studentid:'',
    username:'',
    apiurl: 'http://XXX'
  }, 
  getUserInfo(){
    var that = this
    return new Promise((resovle,reject)=>{
      if(this.userInfo) resovle(this.userInfo);
      
      //调用用户授权 api 获取用户信息
      my.getAuthCode({
        scopes: 'auth_user', 
        success:(res) =>{
           if (res.authCode) {    
             my.httpRequest({
               url: that.globalData.apiurl + '/api/AliPay/GetUserInfo',
               method: 'GET',
               data: {
                  auth_code: res.authCode
               },
               dataType: 'json',
               success: function(res) {
                  that.globalData.studentid = res.data.data.student_id;
                  that.globalData.username = res.data.data.user_name;
                  //获取用户信息,照片、昵称
                  my.getAuthUserInfo({
                    scopes: ['auth_user'],
                    success: (res) => {
                      that.userInfo = res;
                      resovle(that.userInfo);
                   },
                   fail:() =>{
                      reject({});
                   }
                  });
                  console.log('返回UserDetail', res.data.data);         
               },
               fail: function(res) {
                  my.alert({content: 'fail'});
               },
               complete: function(res) {
                  my.hideLoading();
               }
            });
          }
        },
        fail:() =>{
          reject({});
        }
      });
    });
  },

  onLaunch(options) {

  },
  onShow(options) {
    // 从后台被 scheme 重新打开
  },
});

バックエンド webapi http://XXX/api/AliPay/GetUserInfo ユーザー情報を取得し、取得したユーザー ID とユーザー名をグローバル変数 globalData に格納します

const app = getApp();

Page({
  data: {
    src: '',
    username: '',
    studentid: ''
  },
  imageError: function (e) {
    console.log('image 发生错误', e.detail.errMsg)
  },
  imageLoad: function (e) {
    console.log('image 加载成功', e);
  },
  onLoad(query) {
    // 页面加载
    app.getUserInfo().then(
      user => {
            console.info(user);
            //设置头像
            if (user.avatar.length > 0) {
               this.setData({src: user.avatar});
            }
            else{
               this.setData({src: '/images/tou.png'});
            } 
            //设置用户名    
            if (app.globalData.username)
            {
               this.setData({username: app.globalData.username});
            }
            else
            {
               this.setData({username: user.nickName});
            }

            if(app.globalData.studentid)
            {
               //设置UserId
               this.setData({studentid: app.globalData.studentid}); 
            }
        }
    );
  },
  onShow() {
    // 页面显示
       
  },
  onReady() {

     
  }
});

元々公式は .net フレームワーク用の SDK しか提供していませんでしたが、誰かがインターネットは .net core バージョンを移植し、Install-Package Alipay を実行して、AopSdk.Core をインストールし、appsettings.json で次の設定を実行し、ミニ プログラムの公開キー、秘密キー、appid およびその他のパラメーター uid を書き込みます。

  "Alipay": {
    //校园码支付宝小程序正式环境
    "AlipayPublicKey": "",
    "AppId": "",
    "CharSet": "UTF-8",
    "GatewayUrl": "https://openapi.alipay.com/gateway.do",
    "PrivateKey": "",
    "SignType": "RSA2",
    "Uid": ""
  }

を記述する必要はありません。その後、サービスをバックエンド コアに挿入する必要があります

。CS コードはすべてを補助し、関連するものだけを投稿します。このコードは、appsettings.json を読み取って挿入します。サービスに投入

        private void ConfigureAlipay(IServiceCollection services)
        {
            var alipayOptions = Configuration.GetSection("Alipay").Get<AlipayOptions>();
            //检查RSA私钥
            AlipayConfigChecker.Check(alipayOptions.SignType, alipayOptions.PrivateKey);
            services.AddAlipay(options => options.SetOption(alipayOptions)).AddAlipayF2F();
        }


        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //配置alipay服务
            ConfigureAlipay(services);
            ......

フロントエンドから認可コードを渡された後、その認可を利用してユーザー情報を取得します

        private AlipayUserInfoShareResponse GetShareResponse(string auth_code)
        {
            var alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest
            {
                Code = auth_code,
                GrantType = "authorization_code"
            };
            var oauthTokenResponse = _alipayService.Execute(alipaySystemOauthTokenRequest);
            AlipayUserInfoShareRequest requestUser = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userinfoShareResponse = _alipayService.Execute(requestUser, oauthTokenResponse.AccessToken);
            return userinfoShareResponse;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="auth_code"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserInfo")]
        public ActionResult GetUserInfo(string auth_code)
        {
            try
            {
                AlipayUserInfoShareResponse userinfoShareResponse = GetShareResponse(auth_code);
                return new JsonResult(new { data = userinfoShareResponse });
            }
            catch (Exception ex)
            {
                log.Error("错误:" + ex.ToString());
                return new JsonResult(new { data = ex.ToString() });
            }
        }

関連記事:

Alipay SDKの使い方は?

WeChatミニプログラムとAlipayミニプログラムの比較と違いの紹介

以上がAlipay ミニ プログラムの開発 - Alipay の SDK を使用してユーザー ID を取得するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター