支付寶小程式在前端只能取得到使用者暱稱和頭像,但是這是遠遠不夠的,我們至少需要取得到使用者的支付寶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取得使用者User ID的詳細內容。更多資訊請關注PHP中文網其他相關文章!