首先做小程序支付我们需要下面这些东西:
- appid:(小程序ID)
- app_secret:(小程序密钥)
- mch_id:(商户号)
- key:(api秘钥,商家后台自己设置)
小程序端:
做一个简单的支付页面,在index.wxml中添加一个输入框,一个button,绑定相关事件,输入框用于输入订单号,在正式使用中不需要输入框,button用于提交订单发起支付;
<input type="text" bindinput="getOrderCode" style="border:1px solid #ccc;margin: 10rpx;height: 80rpx;"></input>
<button bindtap='pay'>支付</button>
然后,在index.js中添加以下代码,主要处理上面的绑定事件和发起支付;
Page({
data:{
orderCode:""
},
pay: function(options) {
var orderCode = this.data.orderid;
wx.login({
success: function(res) {
if (res.code) {
wx.request({
url: 'http://192.168.0.32:9003/BingAnService/Pay.do',//服务端请求地址,使用时换上自己的地址
data: {
code: res.code, //要去换取openid的登录凭证
order_code: orderCode
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
success: function(res) {
console.log("支付接口返回信息:", res.data);
//拿到服务端返回数据,调用微信小程支付
wx.requestPayment({
timeStamp:res.data.timeStamp,
nonceStr:res.data.nonceStr,
package:res.data.package,
signType:res.data.signType,
paySign:res.data.paySign,
success: function(res) {//成功
console.log("支付成功:",res);
},
fail: function(res) {
console.log("支付失败:",res);
}
})
}
})
}
}
})
},
getOrderCode: function(options) {
this.setData({
orderid: options.detail.value
})
})
服务端:
我的服务端使用的是.net来做的,首先提供一个供小程序端调用的接口
public ListResultInfo Pay(JObject jObject)
{
ListResultInfo result = new ListResultInfo();
try
{
string code = jObject["code"].ToString();
string order_code = jObject["order_code"].ToString();
PayRequesEntity str = (PayRequesEntity)WXPay.Pay(code, order_code);
if (str!=null)
{
result.Error_code = 0;
result.Success = true;
result.Message = "支付结果!";
result.Total_count = 0;
result.Data = str;
}
else
{
}
}
catch (Exception e)
{
result.Error_code = 1;
result.Success = false;
result.Message = "发起支付失败!";
result.Error_desc = e.Message;
WebLog.WriteTextLog("运行", "发起支付失败:" + e.Message, DateTime.Now);
}
return result;
}
所有的支付相关的都写在WXPay这个类里面,先上代码:
public class WXPay
{
private static string APP_ID = "小程序ID";
private static string APP_SECRET = "密钥(小程序配置界面)";
private static string MCH_ID = "商户号";
private static string KEY = "api密钥(商家后台自己设置)";
private static string NOTIFY_URL = "支付回调地址";
private static string PAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static Object Pay(string code, string order_code)
{
Parameters para = new Parameters();
para.appid = APP_ID;//申请的appid
para.mchid = MCH_ID;//申请的商户号
para.nonce_str = GetNoncestr(); //随机字符串
para.notify_url = NOTIFY_URL;//支付结果回调接口
para.body = "testPay";//商品描述(商品简单描述,该字段请按照规范传递,具体请见参数规定)
para.out_trade_no = order_code;//商户订单号
para.total_fee = "0.01";//标价金额
para.spbill_create_ip = "IP地址";//终端IP
para.trade_type = "JSAPI";//交易类型
para.key = KEY;//