使用开源项目Alipay.AopSdk.Core完成支付宝网页登录
核心方法:
public IActionResult UserInfoCallBackAli()
{
var alipayClient = new DefaultAopClient(ConfigAli.ServerUrl,
ConfigAli.AppId,
ConfigAli.PrivateKey,
"json",
null,
"RSA2",
ConfigAli.AlipayPublicKey,
"UTF-8",
false);
var alipayRequest = new AlipaySystemOauthTokenRequest();
alipayRequest.Code = Request.Query["auth_code"];
alipayRequest.GrantType = "authorization_code";
var aliUser = new UsersAli();
try
{
var alipayResponse = alipayClient.Execute(alipayRequest);
if (!alipayResponse.IsError)
{
var requestUser = new AlipayUserInfoShareRequest();
try
{
var userinfoShareResponse = alipayClient.Execute(requestUser, alipayResponse.AccessToken);
if (!userinfoShareResponse.IsError)
{
initUserInfo(aliUser, userinfoShareResponse);
var db = DB.GetInstance();
var flag = db.Queryable<UsersAli>().Where(m => m.user_id == aliUser.user_id).Any();
if (!flag)
{
db.Insertable<UsersAli>(aliUser).ExecuteCommand();
ViewData["json"] = "入库成功";
}
ViewData["json"] = "存在记录不用入库";
db.Dispose();
}
}
catch(AopException ex)
{
System.IO.File.AppendAllText("log", ex.ErrorMsg + "\r\n");
ViewData["ex"] = "出错"+ ex.ErrorMsg;
}
}
}
catch(AopException ex)
{
System.IO.File.AppendAllText("log", ex.ErrorMsg + "\r\n");
ViewData["ex"] = "出错"+ ex.ErrorMsg;
}
return View();
}
其中用到的一个工具方法
private void initUserInfo(UsersAli aliUser,AlipayUserInfoShareResponse response)
{
aliUser.user_id = response.UserId;
aliUser.avatar = response.Avatar;
aliUser.nick_name = response.NickName;
aliUser.city = response.City;
aliUser.province = response.Province;
aliUser.gender = response.Gender;
aliUser.user_type = response.UserType;
aliUser.is_certified = response.IsCertified;
aliUser.is_student_certified = response.IsStudentCertified;
//aliUser.is_balance_frozen = userinfoShareResponse.isBalanceFrozen
//aliUser.address = userinfoShareResponse.address
//aliUser.area = userinfoShareResponse.area
//aliUser.business_scope = userinfoShareResponse.businessScope
//aliUser.cert_no = userinfoShareResponse.certNo
//aliUser.email = userinfoShareResponse.email
//aliUser.license_no = userinfoShareResponse.licenseNo
//aliUser.mobile = userinfoShareResponse.mobile
//aliUser.person_birthday = userinfoShareResponse.personBirthday
}