1. 程式人生 > >支付寶小程式開發練習-重構,在app.js獲取使用者資訊(三)

支付寶小程式開發練習-重構,在app.js獲取使用者資訊(三)

支付寶小程式在前端只能獲取到使用者暱稱和頭像,但是這是遠遠不夠的,我們至少需要獲取到使用者的支付寶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() });
            }
        }