微信小程序——搭建自己的服务器 c#
账号密码登录。
手机号验证码登录。
第三方账号登录
使用小程序的用户登录流程可以用这一句话简单概括:" 3个角色,4个步骤 ",3个角色是:
" 小程序(客户端) ,开发者的服务器 (中转服务器),微信接口服务(微信官方服务器) ",
4个步骤就是:
step 1.小程序获取code,- 临时登录凭证 code 只能使用一次
step 2.小程序将code发送到开发者服务器,
step 3.开发者服务器组合参数通过微信接口服务校验登录凭证 ,获取openid
step 4.开发者服务自定义登录的状态。
https://res.wx.qq.com/wxdoc/dist/assets/img/api-login.2fcc9f35.jpg
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
生产情况下微信小程序客户端获取临时 code 传给服务端;服务端调用微信服务后拿到 openid 返回给前端,因为调用微信服务需要用到 appid 和 appSecret,放在后端更安全。
微信小程序授权登录的具体实现步骤如下:
1. 首先在微信公众平台申请小程序并获得小程序的 AppID(得到 AppID和 AppSecret )。
2. 小程序客户端调用 `wx.login()` 方法,会返回 code,有效期5分钟;此步不需要和开发者的后端服务器发生关系。
step 3.发送 res.code 到后台服务器换取 openId, sessionKey, unionId
发送 res.code 到后台服务器,后台服务器和微信官方服务器换取 openId, sessionKey, unionId
3. 小程序客户端将 code 发送到后端服务器,后端服务器使用 AppID 和 AppSecret 、code组合后,调用微信服务器接口 `https://api.weixin.qq.com/sns/jscode2session` 并传入参数 `js_code`、`appid`、`secret`、`grant_type`,获得 session_key。
4. 后端服务器将 session_key 返回给前端小程序,小程序可以将其存储在本地。
5. 如果小程序需要获取用户信息,可以引导用户点击授权按钮获取用户信息,然后将加密后的数据和签名发送给后端服务器。
6. 后端服务器使用刚才获取到的 session_key 对加密数据进行解密,并使用 AppID 校验签名。
7. 后端服务器将解密后的数据返回给前端小程序,小程序端即可获得用户信息。
客户端代码 app.js
// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
console.log("code: " + res.code);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
globalData: {
userInfo: null
}
})
output
code: 0b1n1EGa1o4bNG0sBsFa1b3Tf83n1EGv VM76 app.js:15
服务端代码
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using WeiXinThirdserver_Miniprogrom_nocloud.Models;
namespace WeiXinThirdserver_Miniprogrom_nocloud.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
string appid = "wxae737f";
string secret = "c5c88552529";
string code = "0a1LIq0w3Dra923GWq1w3fWI1z2LIq0O";
//AppID(小程序ID) wxae AppSecret(小程序密钥) c5c88552529
string cod = code;
string html = string.Empty;
string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + cod + "&grant_type=authorization_code";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream ioStream = response.GetResponseStream();
StreamReader sr = new StreamReader(ioStream, Encoding.UTF8);
html = sr.ReadToEnd();
sr.Close();
ioStream.Close();
response.Close();
RepParamrep rep = JsonConvert.DeserializeObject<RepParamrep>(html);
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
public class RepParamrep
{
public string session_key { get; set; }
public string openid { get; set; }
}
}
Output
{"session_key":"d+KFPdO+vtDAOpp5pOFh0g==","openid":"ohWik5BeX2ssH5EhYn0rnSw3OfRg"}
Note
微信小程序报错 errcode: 40029, errmsg: “invalid code
解决方式。关闭这个项目,重新启动,获取新的 code
{"errcode":40163,"errmsg":"code been used, rid: 65b44ec2-1140c3ec-56792928"}
解决方式。关闭这个项目,重新启动,获取新的 code
Senparc.Weixin.WxOpen Sample
https://github.com/JeffreySu/WeiXinMPSDK/tree/master/Samples/WxOpen
Senparc.Weixin.Sample.WxOpen
微信小程序服务器代码端示例 + 说明文档
微信小程序登录c#
https://www.cnblogs.com/xingqiang/p/14045405.html
微信小程序实现微信和账号密码同时登录