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