微信网页版唤起支付

墨尘| 阅读:140 发表时间:2023-05-17 10:54:10 科技智能

前端js请求参数调起支付

<script type="text/javascript" src="https://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

<script type="text/javascript">

 let obj = {"openid":oppenid,'user_id':userid,'total':2,'type':2};

                    $.post('https://www.lovexfang.com/api/wxpay/orderpay',obj,function(data){

                         let wxdata = data.msg;

                             wx.config({

                          debug: false,

                          appId: wxdata.appId,

                          timestamp: wxdata.timestamp,

                          nonceStr: wxdata.nonceStr,

                          signature: wxdata.signature,

                          jsApiList: [

                            "chooseWXPay"

                          ]

                         });

                            wx.ready(() => {

                              wx.chooseWXPay({

                                'appId': wxdata.appId,

                                'timestamp': wxdata.timeStamp,

                                'nonceStr': wxdata.nonceStr,

                                'package': wxdata.package,

                                'signType': wxdata.signType,

                                'paySign': wxdata.paySign,

                                success: function (res) {

                                   window.location.reload();

                                },

                                fail: function (res) {

                                  window.location.reload();

                                },

                                complete: function (res) {

                                  window.location.reload();

                                }

                              })

                            })

                    },'json');

</script>



后端php获取支付参数

    public function htmlpay(){

        $array = array(

            "app_id" => "wxf2edf0bf6fb553b0",//微信公众号appi;

            "app_secret" => "0b6aac517951c812a8a2b185592ee14a",//微信公众号密钥

            "mch_id" => "1630274740",//商户号;

            "key"  => "a66aac517951c812a8a2b185592ee14b",//商户号的密钥

            "notify" => "https://dnkj.jinhuoban.icu/web/mch.php?s=/api/index/paynotify"//支付后回调地址

        );

        return $array;

    }

    public function pay($money="0.01"){

            $openid = input('openid')?:'otAtt6SD3Ln3G1u7FD3zjJPsk-m8'; 

            $reannumb = $this->doCreateOrderNumber();  //生成唯一订单号

            $pays = $money;

            $conf = $this->payconfig($reannumb,$pays*100,'支付程序支付',$openid);

            if (!$conf || $conf['return_code'] == 'FAIL'){

              echo json_decode(['code'=>403,'msg'=>'支付参数有误']);

              die;  

            } 

            $array = $this->htmlpay();

            

            $this->orderid = $conf['prepay_id'];

            $jsApiObj["appId"] =$conf['appid'];

            $timeStamp = time();

            $jsApiObj["timeStamp"] = "$timeStamp";

            $jsApiObj["nonceStr"] = $this->createNoncestr();

            $jsApiObj["package"] = "prepay_id=".$conf['prepay_id'];

            $jsApiObj["signType"] = "MD5";

            $jsApiObj["paySign"] = $this->MakeSign($jsApiObj,$array['key']);

            echo json_encode(array('parameters'=>$jsApiObj));

            die();

    }

    

    

    public  function doCreateOrderNumber(){

        $code = array('AG', 'BI', 'CW', 'DA', 'EL', 'FW', 'GL', 'HO', 'IZ', 'JB');   

        $osn = $code[intval(rand(0,9))] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

        return $osn;

    }

    public function MakeSign($data, $key){

          $String = $this->formatParameters($data, false);

          //签名步骤二:在string后加入KEY

          $String = $String . "&key=" . $key;

          //签名步骤三:MD5加密

          $String = md5($String);

          //签名步骤四:所有字符转为大写

          $result = strtoupper($String);

          return $result;

    }

    public function formatParameters($paraMap, $urlencode)

    {

          $buff = "";

          ksort($paraMap);

          foreach ($paraMap as $k => $v) {

           if($k=="sign"){

            continue;

           }

           if ($urlencode) {

            $v = urlencode($v);

           }

           $buff .= $k . "=" . $v . "&";

          }

          $reqPar;

          if (strlen($buff) > 0) {

           $reqPar = substr($buff, 0, strlen($buff) - 1);

          }

          return $reqPar;

     }

    public function payconfig($no, $fee, $body,$openid)

    {           

        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        $array = $this->htmlpay();

        $data['appid'] = $array['app_id'];

        $data['mch_id'] = $array['mch_id'];

        $data['device_info'] ='WEB';

        $data['body'] = $body;

        $data['out_trade_no'] =$no;

        $data['total_fee'] = $fee;

        $data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];

        $data['notify_url'] =$array['notify'];

        $data['trade_type'] = 'JSAPI';

        $data['openid']= $openid; 

        $data['nonce_str'] = $this->createNoncestr();

        $data['sign'] = $this->MakeSign($data,$array['key']);

       

        $xml = $this->ToXml($data);

  

        $curl = curl_init(); // 启动一个CURL会话

        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        //设置header

        curl_setopt($curl, CURLOPT_HEADER, FALSE);

        //要求结果为字符串且输出到屏幕上

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

        curl_setopt($curl, CURLOPT_POST, TRUE);       //发送一个常规的Post请求

        curl_setopt($curl, CURLOPT_POSTFIELDS, $xml); // Post提交的数据包

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);      // 设置超时限制防止死循环

        $tmpInfo = curl_exec($curl); // 执行操作

        curl_close($curl); //关闭CURL会话

        $arr = $this->FromXml($tmpInfo);

       

        return $arr;

    }

    public function createNoncestr($length = 32)

    {

        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";

        $str = "";

        for ($i = 0; $i < $length; $i++) {

            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

        }

        return $str;

    }

    public function randomkeys($length)

    {

        $pattern = '1234567890123456789012345678905678901234';

        $key = null;

        for ($i = 0; $i < $length; $i++) {

            $key .= $pattern{mt_rand(0, 30)};    //生成php随机数

        }

        return $key;

    }

    public function FromXml($xml)

    {

        //将XML转为array

        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)),true);

    }

    public function ToXml($arr)

    {

       

          $xml = "<xml>";

          foreach ($arr as $key=>$val)

          {

            if (is_numeric($val))

            {

            $xml.="<".$key.">".$val."</".$key.">";

            }

            else

            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; 

          }

          $xml.="</xml>";

          return $xml;

    }

    /**

     * 首页diy数据

     * @return array

     * @throws \think\exception\DbException

     */

    public function page()

    {

        // 页面元素

        $wxappPage = WxappPage::detail();

        $items = $wxappPage['page_data']['array']['items'];

        // 新品推荐

        $model = new GoodsModel;

        $newest = $model->getNewList();

        // 猜您喜欢

        $best = $model->getBestList();

        return $this->renderSuccess(compact('items', 'newest', 'best'));

    }


*文章为投稿者独立观点,不代表本站站长的立场
本文由相遇青春-Yn发表并编辑,转载此文章须经作者同意,并请附上出处及本页链接。如有侵权,请联系本站删除。

热门推荐