欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  微信小程序

支付宝小程序开发-利用支付宝的SDK获取用户User ID

程序员文章站 2022-04-05 16:39:16
...
支付宝小程序在前端只能获取到用户昵称和头像,但是这是远远不够的,我们至少需要获取到用户的支付宝User ID,这个时候就必须在后端利用支付宝的SDK来获取了,当然前端要发出 httprequest 请求,下面结合前两篇的例子进行修改

支付宝小程序前端

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 来获取用户信息,并把取到的userid,username 存到全局变量 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 framwork 的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": ""
  }

然后在后端core还需要注入Service

Startup.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() });
            }
        }

相关文章:

支付宝SDK怎么用啊?

微信小程序和支付宝小程序对比区别介绍

以上就是支付宝小程序开发-利用支付宝的SDK获取用户User ID的详细内容,更多请关注其它相关文章!