微信JSAPI支付实现

时间:2022-09-24 17:43:34

1.获取到mch_id ,appid,appsecrect,api秘钥
2.下载安装证书
3.在商户中心配置jsapi目录,发起起调的页面。
4.公众号配置回调域名,业务,js域名。
5.加入安全白名单。

不多说了上代码前端

<script> function wxpay(){ var money = $('#paymoney').text(); var o_sonid=$('#o_sonid').attr('data-id'); var o_sonid=parseInt(o_sonid); var money =parseFloat(money); var id = $('.this').find('.index_id').val(); if(money){ $.ajax({ url:"{:U('Orders/wxpay')}", data:{ money:money, id:o_sonid, }, dataType:"json", type:"POST", success:function(data){ WeixinJSBridge.invoke('getBrandWCPayRequest',data,function(res){ if(res.err_msg == 'get_brand_wcpay_request:ok'){ window.location.reload(); } }); } }) }else{ alert('请确定金额!'); } } </script>

后端代码

  function wxpay(){
    $money=I('post.money');
    $id=I('post.id');   //对应订单子订单
    $order_goods=M('order_goods');
    $orderinfo=$order_goods->where('id='.$id)->find();
    $out_trade_no= $orderinfo['create_time'].mt_rand(0000,9999);
    $order_goods->where('id='.$id)->setField('out_trade_no',$out_trade_no);
    // $data= M('order')->where('order_id='.$_POST['id'])->find();
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $arr = array(
      'appid' => $this->appid,
      'mch_id' => $this->mch_id,
      'nonce_str' => $this->getNonceStr(),
      'body' =>$orderinfo['goods_name'],
      'out_trade_no' => $out_trade_no,
      'total_fee' => $money * 100,
      // 'total_fee' => 1,
      'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
      'notify_url' => 'http://xxxxx.com/index.php/Home/Orders/weixin/',
      'trade_type' => 'JSAPI',
      'openid' => $_SESSION['openid']
    );
    $arr['sign'] = $this->sign($arr);
    $data = $this->ToXml($arr);
    $result = $this->postData($url,$data);
    $options = array(
      'appId' => $this->appid,
      'timeStamp' => (string)time(),
      'nonceStr' => $this->getNonceStr(),
      'package' => 'prepay_id='.$result['prepay_id'],
      'signType' => 'MD5',
    );
    $options['paySign'] = $this->sign($options);
    die(json_encode($options));
  }
  //支付回调处理(不能继承基类验证页面之类的)
    public function weixin(){
        $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if($postObj->return_code == 'SUCCESS'){
      //获取交易金额 ,修改订单状态。
      $money = $postObj->total_fee;
            $money = (iconv("gbk", "UTF-8", $money))/100;
      $out_trade_no= $postObj->out_trade_no;
      $out_trade_no = (iconv("gbk", "UTF-8", $out_trade_no));
      $order_goods=M('order_goods');
      $order_goods->pay_money=$money;
      $order_goods->payment_notify_time=time();
      $order_goods->pay_status='2';
      $map['out_trade_no']=$out_trade_no;
            $order_goods->where($map)->save();
      //商品销售量+1
      $o_soninfo=M('order_goods')->where('out_trade_no='.$out_trade_no)->find();
      M('goods')->where('id='.$o_soninfo['goods_id'])->setInc('sale_num');
    }
    die('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
    }

  //微信授权(必须先获取用户openid)
    public function access_token(){
          // $tid = $_REQUEST['tid'];
        $code = $_REQUEST['code'];
        $res = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的appid&secret=你的app秘钥&code=".$code."&grant_type=authorization_code");
        $list = json_decode($res);
        $access_token = $list->access_token;
        $openid = $list->openid;
        $row = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN");
        $arr = json_decode($row);
        if ($arr->openid) {
            $data['openid'] = $arr->openid;
          $data['create_time'] =time();
          $data['status']='1';
          $data['img']=$arr->headimgurl;
            // $data['tid'] = $tid;
            $id = M('user')->where("openid='".$data['openid']."'")->getField('id');
            if(!$id){
                $id = M('user')->add($data);
            }
            $_SESSION['uid'] = $id;
          session('uid',$id);
              $_SESSION['openid'] = $data['openid'];
            if($_SESSION['uid']){
                $this->redirect('User/index');
            }
        }
    }
    //获取code码
        public function getOpenId(){
     $url = 'http://xxxxx.com/index.php/Home/Orders/access_token/';
     $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=?&redirect_uri='.urlencode($url).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
     header('location:'.$url);
    }

ps:再说一些开发中遇到的坑
1.如果拿不到openid 果断换个服务器试试吧,不多说了都是泪~。
2.支付过程中不能用session传递参数
3.别的没啥了