这篇文章主要介绍了小程序中如何利用支付宝的SDK获取用户User ID,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
支付宝小程序前端
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”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。