小白开发微信小程序23--开放接口API

  1. 开放接口列表

wx.login 登录

wx.getUserInfo 获取用户信息

wx.chooseAddress 获取用户收货地址

wx.requestPayment 发起微信支付

wx.addCard 添加卡券

wx.openCard 打开卡券

.......................................................

  1. wx.getUserProfile

1、功能描述

获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。该接口用于替换 wx.getUserInfo,详见 用户信息接口调整说明。

2、示例代码

页面代码

js代码

运行效果

3.wx.login

功能描述

调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。

小程序登录wx.login()

小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系

说明

调用 wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。

调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key。

之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份

小程序登录code2Session

接口应在服务器端调用,详细说明参见服务端API。

功能描述

登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见小程序登录。

HTTPS 调用

GET https://api.weixin.qq.com/sns/jscode2session

请求数据示例

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

返回数据示例

{

"openid":"xxxxxx",

"session_key":"xxxxx",

"unionid":"xxxxx",

"errcode":0,

"errmsg":"xxxxx"

}

示例代码

1、页面添加登录按钮

2、js代码testLogin

可以看到这个code是变化的,不能作为登录的唯一凭证,需要用到下面的code2Session,即调用 auth.code2Session 接口,换取 用户唯一标识 OpenID

3、这个code不是唯一的,不能作为登录的凭证,需要进行下一步的验证

如图所示,用usercode换取openid

打开上次“小白开发微信小程序21--网络API(ASP.NET版”代码,首先添加包引用,newtonsoft.json

在model文件夹添加类HttpHelper

HttpHelper.cs完整代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace webapitest.Models
{
    /// <summary>
    /// http请求帮助类
    /// </summary>
    public  class HttpHelper
    {
        /// <summary>
        /// https get请求
        /// </summary>
        /// <param name="Url">请求地址</param> 
        /// <returns>System.String.</returns>
        public  string HttpsGet(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close(); 
            return retString;
        }
    }
}

在WebXinController中添加方法wxLogin,

完成代码:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapitest.Models;

namespace webapitest.Controllers
{
    /// <summary>
    /// 微信小程序控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WebXinController : ControllerBase
    {
        List<Book> booklist = null;

        private static List<Book> getBookList()
        {
            List<Book> books = new List<Book>();

            Book b1 = new Book();
            b1.id = 9032;
            b1.title = "java开发指南";
            b1.author = "杨强标";
            b1.publisher = "吉林出版公司";
            b1.image = "img01.jpg";
            books.Add(b1);

            Book b2 = new Book();
            b2.id = 7232;
            b2.title = "web项目指导";
            b2.author = "毛二平";
            b2.publisher = "山东出版公司";
            b2.image = "img02.jpg";
            books.Add(b2);

            Book b3 = new Book();
            b3.id = 6832;
            b3.title = "小程序教程";
            b3.author = "风间云";
            b3.publisher = "海南出版公司";
            b3.image = "img03.jpg";
            books.Add(b3);
            return books; 
        }

        /// <summary>
        /// 图书列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("findBookList")]
        public List<Book> findBookList()
        {
            booklist = getBookList();
            return booklist; 
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet("wxLogin")]
        public string  wxLogin(string userCode)
        {
            string appid = "wxd20d97e66580e91e";
            string secret = "5100c604bcb817cd0fa0cd801fccd239";
            string jscode = userCode;
            //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code 
            string requesturl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + jscode + "&grant_type=authorization_code";
            HttpHelper httpHelper = new HttpHelper();
            string jsonresult = httpHelper.HttpsGet(requesturl);
            JObject jsonobj = JsonConvert.DeserializeObject<JObject>(jsonresult);//序列化成json对象
            string useropenid = jsonobj.GetValue("openid").ToString();//获取指定属性的值
            string txt = useropenid; 
            return txt;
        }

    }
}

小程序页面js代码

完成代码

// pages/myapi/myapi.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},//用户信息
        useropenid: "",
        usercode:""
    },
    //登录
    testLogin() {
        let that=this;
        wx.login({
            success(res) {
                if (res.code) {
                    that.setData({
                        usercode:res.code
                    });
                    console.log(res.code);
                }
            }
        })
    },
    //微信登录
    doLogin() {
        let that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    const code = res.code;
                    that.setData({
                        usercode:res.code
                    });
                    wx.request({
                        url: 'https://localhost:5001/api/WebXin/wxLogin',
                        data: { "userCode": code },//传递参数
                        method: "GET",//当前请求的请求方式
                        header: {
                            'content-type': 'application/json' // 默认值
                        },
                        success(res) {
                            const tokendata = res.data;
                            if (tokendata != "error") {
                                wx.setStorageSync('token', tokendata);//存储用户token 
                                that.setData({ 
                                    useropenid: tokendata
                                });
                                wx.showToast({
                                    title: '登录成功',
                                    icon: 'success',
                                    duration: 2000
                                })
                            }
                        }
                    });
                }
            }
        })
    },




    getUserProfile() {
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: (res) => {
                this.setData({
                    userInfo: res.userInfo
                })
            }
        })
    },



    // 添加设备
    putdevice() {
        wx.showToast({
            title: '设备添加成功',
            icon: 'success',
            duration: 2000
        })
    },
    // 添加课程
    putcourse() {
        wx.showToast({
            title: '课程添加失败',
            icon: 'error',
            duration: 3000
        })
    },
    // 删除
    delbook() {
        wx.showModal({
            title: '提示',
            content: '您是否同意【最美乡村】评选结果?',
            confirmText: "赞成",
            cancelText: "反对",
            success(res) {
                if (res.confirm) {
                    wx.showToast({
                        title: '你投了赞成票',
                        icon: 'success',
                        duration: 2000
                    })
                } else if (res.cancel) {
                    wx.showToast({
                        title: '你投了反对票',
                        icon: 'error',
                        duration: 3000
                    })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})

点我登录

成功拉到了openid,这个openid才是小程序用户的唯一标识,这也是作为token。

帅是一个境界,相信自己的传说。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hqwest

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值