# 小程序支付

## 1. 使用场景

商户已有微信小程序，用户通过好友分享或扫描二维码在微信内打开小程序时，可以调用微信支付完成下单购买的流程。

步骤（1）：如图7.1，用户通过分享或扫描二维码进入商户小程序，用户选择购买，完成选购流程。

![](/files/7Tt5Frp7AKFyxAw0aHIF)![](/files/zkedG7FKYsWSAfFqpUIc)

步骤（3）：如图7.3，调起微信支付控件，用户开始输入支付密码。

步骤（4）：如图7.4，密码验证通过，支付成功。商户后台得到支付成功的通知

![](/files/f846xwvbNMqX7LOAF8Eu)![](/files/CcGEhNuy29kbiLX2R9Li)

步骤（5）：如图7.5，返回商户小程序，显示购买成功。

步骤（6）：如图7.6，微信支付公众号下发支付凭证。

## 2. 开发步骤

1. 小程序内调用登录接口，获取到用户的openid,api&#x20;
2. 商户server调用支付下单接口，api参见【[Jsapi支付下单接口](/developer/reference/local-pay-ben-di-hua/ben-di-hua-jie-kou/dian-zi-qian-bao/wechat-hk/jsapi.md)】
3. 商户server接收支付通知，api参见公共api【[异步通知](/developer/reference/notify/notifyurl.md)】
4. 商户server查询支付结果，api参见公共api【[查询订单API](/developer/reference/api-reference-xin-yong-ka/order/order-detail.md)】

## 3. 如何获取用户的Openid

### 3.1 登录微信获取Code

参考[wx.login(Object object)](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html)

```
wx.login({
  success (res) {
    if (res.code) {
      //发起网络请求
      wx.request({
        url: 'https://example.com/onLogin',
        data: {
          code: res.code
        }
      })
    } else {
      console.log('登录失败！' + res.errMsg)
    }
  }
})
```

### 3.2 用Code换取openid

参考[auth.code2Session](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html)

登录凭证校验。通过 [wx.login](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html) 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见 [小程序登录](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html)。

#### 3.2.1 请求地址

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

## 4. 调用Jsapi接口

[Jsapi接口](/developer/reference/local-pay-ben-di-hua/ben-di-hua-jie-kou/dian-zi-qian-bao/wechat-hk/jsapi.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://useepay.gitbook.io/developer/reference/local-pay-ben-di-hua/ben-di-hua-jie-kou/dian-zi-qian-bao/wechat-hk/xiao-cheng-xu-zhi-fu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
