官方文档:https://docs.alipay.com/mini/introduce/auth
一、首先获取authcode
官方文档:https://docs.alipay.com/mini/api/openapi-authorize
my.getAuthCode({scopes: 'auth_base',success: (res) => {// res.authCode//发送授权码到服务后台进行解析// 根据authcode,调用后台接口,获取用户ID}
});
二、根据authcode获取用户ID(user_id)
服务端SDK文档:https://docs.open.alipay.com/54/103419/
如果要获取用户昵称、头像,还需要先进行用户授权
解析授权码
///
/// 获取支付宝用户id
///
/// 小程序授权码
/// appid
/// 应用私钥,和应用公钥匹配 在密钥生产器中可见
/// 支付宝公钥(区别于应用公钥),开放平台中接口加签方式中可见
///
public static string GetUserID(string auth_code, string app_id, string merchant_private_key, string alipay_public_key)
{string result = "";try{IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", app_id, merchant_private_key, "json", "1.0", "RSA2", alipay_public_key, "GBK", false);AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();request.GrantType = "authorization_code";request.Code = auth_code;request.RefreshToken = "";AlipaySystemOauthTokenResponse response = client.Execute(request);JObject jobj = (JObject)JsonConvert.DeserializeObject(response.Body);JObject jk = (JObject)jobj["alipay_system_oauth_token_response"];if (jk.Property("code") == null){string user_id = jobj["alipay_system_oauth_token_response"]["user_id"].ToString();result = ReturnInfo.ListReturn("S", "", user_id);}else{string msg = jobj["alipay_system_oauth_token_response"]["msg"].ToString();result = ReturnInfo.ListReturn("E", msg, "");}}catch (Exception ex){result = ReturnInfo.ListReturn("E", ex.Message, "");}return result;
}
获取用户信息
my.getAuthUserInfo({success: (res) => {console.log("用户信息:" + JSON.stringify(res))var nickName = res.nickName;var avatar = res.avatar;});},fail: err => console.log(err)});