目录

  • 一、创建小程序
  • 二、接入小程序
  • 三、调试小程序
  • 四、错误与解决

本篇主要记录支付宝小程序开发的整个步骤,从前端到后端,图文并茂,清晰易懂,从配置到开发,你想要的的都有。完整流程,后续追加过程问题的解决

最终效果是:获取支付宝登录用户的userId,用它完成相关的业务处理
主要对接技术包括:

获取授权码
证书配置
页面请求编程
获取userid


一、创建小程序

1、创建小程序
登录支付宝 https://www.alipay/ > 产品中心 > 支付宝预授权(没开通的开通)> 自行研发接入 > 创建小程序


2、记录下小程序的Id

3、开发设置
这步的目的是为了能接入开发
在小程序的控制台找到【开发设置】,完成 [设置加签和应用网关] 和 [设置域名白名单]

接口加签建议用证书的方式。配合【支付宝开发平台助手】生成证书,并在这个页面上传生成即可。
密钥接入文档
设置完成,把这三个证书下载下来备用,同时支付宝开发平台助手生成的公钥,私钥也保存好,开发时用到


二、接入小程序

1、前端接入-安装创建
下载安装开发者工具:https://render.alipay/p/f/fd-jwq8nu2a/pages/home/index.html
安装完后打开,新建小程序项目

完成后,首页是这样

2、前端接入-编程
目的:获取授权码,然后获取授权用户id,方便业务后续调用。
修改2个文件:

page/API/get-auth-code/get-auth-code.axml
page/API/get-auth-code/get-auth-code.js

get-auth-code.axml 新增myrequest节点

<view class="page">
  <view class="page-section">
    <view>请不要一进入小程序就弹框授权,建议先了解小程序的服务内容</view>
    <button type="primary" onTap="getAuthCode">
      获取授权码
    </button>
    <button type="primary" onTap="myrequest">
      我的请求
    </button>
  </view>
</view>

get-auth-code.js 加上响应请求

Page({
  onLoad() { },
  data: {},
  getAuthCode: () => {
    my.getAuthCode({
      scopes: 'auth_user',
      success: ({ authCode }) => {
        console.log(`authCode:`, authCode);
        my.alert({
           content: authCode,
        });
      },
    });
  },

  myrequest: () => {
    my.getAuthCode({
      scopes: 'auth_user',
      success: ({ authCode }) => {
        console.log(`authCode:`, authCode);
        my.request({
          url: 'http://192.168.3.2:8080/myapp/aliapi/login/login.do', //服务器接口地址
          method: 'Post',
          data: {
            code: authCode //上面getAuthCode 成功获取到的code, 传入后台接口
          },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            console.log(res)
             my.alert({
                content: res,
          });
          }
        })
      },
    });
  },
});

完成后编译,效果如下

接下来去完成 http://192.168.3.2:8080/myapp/aliapi/login/login.do 接口编码


3、后端接入


    @Override
    public String login(LoginDto loginDto, HttpServletResponse response) {
    
        String appid = "小程序id";	// 之前步骤提到的
        String appPrivateKey = "私钥";  // 之前步骤提到的
        
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay/gateway.do");
        certAlipayRequest.setAppId(appid);
        certAlipayRequest.setPrivateKey(appPrivateKey);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        certAlipayRequest.setCertPath(loader.getResource("").getPath() + "appCertPublicKey.crt");//应用公钥证书
        certAlipayRequest.setAlipayPublicCertPath(loader.getResource("").getPath() + "alipayCertPublicKey_RSA2.crt");//支付宝公钥证书
        certAlipayRequest.setRootCertPath(loader.getResource("").getPath() + "alipayRootCert.crt");//支付宝根证书

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType(grantType);
            request.setCode(loginDto.getCode());
            AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.certificateExecute(request);
            if (alipaySystemOauthTokenResponse.isSuccess()) {
                LogUtils.info("调用成功, Response result={}", alipaySystemOauthTokenResponse.getBody());
                // 生成UUID
                // String tokenId = UUID.randomUUID().toString().replaceAll("-", "");
                // 设置返回tokenid (用户id组成)
                // response.setHeader(TOKEN, JwtUtil.sign(alipaySystemOauthTokenResponse.getUserId(), tokenId));
                return alipaySystemOauthTokenResponse.getUserId();
            } else {
                LogUtils.info("调用失败, {}", alipaySystemOauthTokenResponse.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }

官方开发指南文档地址:https://opendocs.alipay/mini/developer

三、调试小程序

主要是看接口是否调通

1、在开发者工具上查看请求信息

2、查看前端日志打印

3、当然,出了问题,后端的调试更重要,这里就不举例了。

主要问题集中在密钥不正确,参数不全


四、错误与解决

移步这里

更多推荐

蚂蚁支付宝小程序开发从零开始[含demo]