微信小程序支付业务处理

[微信小程序支付]
#登陆API https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html 
#可参考微信小程序登录逻辑整理 http://blog.csdn.net/hss01248/article/details/53405251
#获取登录凭证(code) @注意code 必须确认在小程序开发者绑定之后才能获取

app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var that = this;
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    //清除缓存
    //wx.removeStorageSync('user')
    var user = wx.getStorageSync('user') || {};
    var userInfo = wx.getStorageSync('userInfo') || {};
    if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)) && (!userInfo.nickName)) {   
      wx.login({
          success: function (res) {
          #获取code
          //console.log(res.code);

          var d = that.globalData;
          var url_ = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
          //我这里是通过请求自己的服务器,服务器模拟curl 请求获取返回的openid
          wx.request({
            url: url_,
            data: { code: res.code },
            method: 'GET',
           //header: { "Content-Type": "application/x-www-form-urlencoded" },//注意:post请求必须设置 设置请求的 
            success: function (sessionKey) {
              if (sessionKey!='') {
                  var obj = {};
                  obj.openid = sessionKey.data.openid;
                  obj.expires_in = Date.now() + sessionKey.data.expires_in;
                  wx.setStorageSync('user', obj);//存储openid 
                  //wx.removeStorageSync('user', obj)
                  console.log(obj);  
              }else{
                  console.log('请求服务器失败');
              }
              console.log(sessionKey);
            }
          });
        }
      })
    }else {  
        console.log('获取用户登录态失败!' + res.errMsg)  
     } 
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }
    // else{
    //   //调用登录接口
    //   wx.login({
    //     success: function () {

    //       wx.getUserInfo({
    //         success: function (res) {
    //           //console.log(res);
    //           that.globalData.userInfo = res.userInfo
    //           typeof cb == "function" && cb(that.globalData.userInfo)
    //         }
    //       })
    //     }
    //   })
    // }
  },
  #设置全局变量
  globalData:{
    appid: 'b01ddedddddddddd1ee1b',               //appid需自己提供,此处的appid我随机编写  
    secret: '0cc594acdfdsafsaddfdb56c5',//secret需自己提供,此处的secret我随机编
    userInfo:null,
    nav:{"channelList":[
      {"id":"1","name":"推荐","orderId":"1"},
      {"id":"2","name":"热点","orderId":"2"},
  }
})

//模拟订单提交
//index.js
//获取应用实例
var app = getApp()
Page({
  formSubmit: function (e) {
    var obj = wx.getStorageSync('user');
    console.log(obj.openid);
    var url_ = "https://xxxxxxxxxxx/index.php?controller=WxAppletPay&action=weChatPay";

    wx.request({
      url: url_,
      data: { goods_name: e.detail.value.goods_name, order_sn: e.detail.value.order_sn, order_amount: e.detail.value.order_amount, openid: obj.openid },
      method: 'GET',
      // header: {}, // 设置请求的 header    
      success: function (res) {
        console.log(res);
        if (res.data.error == 200){

          wx.requestPayment({
            'timeStamp': res.data.result.timeStamp,
            'nonceStr': res.data.result.nonceStr,
            'package': res.data.result.package,
            'signType': 'MD5',
            'paySign': res.data.result.sign,
            'success': function (success_) {

              console.log(success_);

            },
            'fail': function (fail_) {

              console.log(fail_) 

            },
            'complete': function (complete_) { 

              console.log(complete_)

            }
          })
        }
      }
    });
    //console.log(code);
    //console.log('form发生了submit事件,携带数据为:', e.detail.value)
  },
  formReset: function (e) {
    console.log('form发生了reset事件,携带数据为:', e.detail.value)
    this.setData({
      chosen: ''
    })
  }
})
//服务端处理
# https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3


require_once PROJECT_PATH."/WxApplet/wxPay/lib/WxPay.Config.php";
require_once PROJECT_PATH."/WxApplet/wxPay/lib/WxPay.Data.php";
require_once PROJECT_PATH."/WxApplet/wxPay/lib/WxPay.Api.php";
#/data/wwwroot/api.wap.miercn.com_new/shop/WxApplet/wxPay/lib/WxPay.Config.php

error_reporting(E_ALL);
ini_set('display_errors',true);

class WxAppletController extends Controller
{

  public function __construct($params)
  {
    parent::__construct($params);
  }

    //小程序支付
  public function weChatPay()
  {
        $goods_name = empty($this->goods_name) ? NULL : $this->goods_name;
        $order_sn  = empty($this->order_sn) ? NULL : $this->order_sn;
        $order_amount = empty($this->order_amount) ? NULL : $this->order_amount;
        $openid = empty($this->openid) ? NULL : $this->openid;

        if(!empty($goods_name) && !empty($order_sn) && !empty($order_amount)){
            $input = new WxPayUnifiedOrder();
            $input->SetAppid(WxPayConfig::APPID);# 这里要用小程序的APPID
            $input->SetMch_id(WxPayConfig::MCHID);
            $input->SetNonce_str(WxPayApi::getNonceStr());
            $input->SetBody($goods_name);
            $input->SetOut_trade_no($order_sn);
            $input->SetTotal_fee($order_amount);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetFee_type("CNY");
            $input->SetSpbill_create_ip(get_client_ip());
            $input->SetNotify_url(WxPayConfig::NOTIFY_URL);
            $input->SetTrade_type('JSAPI');
            $input->SetOpenid($openid);
            $results = WxPayApi::unifiedOrder($input);

      if (!empty($results['prepay_id'])) {//统一下单接口返回的 prepay_id 参数

                //用prepay_id 重新生成sign
                 $new_results= $this->sign($results['prepay_id']);
                 if (!empty($new_results)) {
                  $new_results['callback'] = WxPayConfig::CALLBACK;
          exit(json_response(0, "200200", "", "请求成功123", $new_results));
                 }
      }

        }

  }


  public function sign($prepay_id = '')
  { 
    $result = [];
    #加密格式串
    #appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111 区分大小写
    if (!empty($prepay_id)) {
      $input = new WxApplet();
      $input->SetAppid(WxPayConfig::APPID);          //应用ID
      $input->SetNonce_str(WxPayApi::getNonceStr()); //随机字符串
      $input->SetPrepayid('prepay_id='.$prepay_id);                //微信预支付ID
      $input->SetTimeStamp(time());
      $input->SetSign();
      $xml = $input->ToXml();
      $result = $input->FromXml($xml);
      return $result;
    }
        return $result;

  }

}


#异步处理和APP 支付一样
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值