小程序支付 php

統(tǒng)一下單需要先拿到微信用戶openid

相關(guān)資源:小程序獲取openid php

小程序端

 wx.request({
     url: '統(tǒng)一下單地址',
     data: {
         openid: openid.data.openid,
         payAmount: '金額',
         orderName: '商品名稱',
     },
     success: function(results) {
         let tempArr = (results.data);
         wx.requestPayment({
             timeStamp: '' + tempArr.timeStamp,
             nonceStr: tempArr.nonceStr,
             package: tempArr.package,
             signType: tempArr.signType,
             paySign: tempArr.paySign,
             success(res) {
                 //   支付成功
             },
         })
     },
 });

PHP

<?php


header('Content-type: text/plain; charset=utf-8');

$mchid = '';          //微信支付商戶號 PartnerID 通過微信支付商戶資料審核后郵件發(fā)送
$appid = '';  //微信支付申請對應(yīng)的公眾號的APPID 
$apiKey = '';   //https://pay.weixin.qq.com 帳戶設(shè)置-安全設(shè)置-API安全-API密鑰-設(shè)置API密鑰 

//①、獲取用戶openid
$wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey);
$openId = $_REQUEST['openid'];     //獲取openid
if (!$openId) exit('獲取openid失敗');
//②环肘、統(tǒng)一下單
$outTradeNo = uniqid();     //你自己的商品訂單號
$payAmount = $_REQUEST['payAmount'];          //付款金額难述,單位:元
$orderName = $_REQUEST['orderName'];    //訂單標(biāo)題
$notifyUrl = 'https://baidu.com/notify.php';     //付款成功后的回調(diào)地址(不要有問號)
$payTime = time();      //付款時間
$jsApiParameters = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $orderName, $notifyUrl, $payTime);

echo (json_encode($jsApiParameters));

class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $appKey;
    protected $apiKey;
    public $data = null;
    public function __construct($mchid, $appid, $appKey, $key)
    {
        $this->mchid = $mchid; //https://pay.weixin.qq.com 產(chǎn)品中心-開發(fā)配置-商戶號
        $this->appid = $appid; //微信支付申請對應(yīng)的公眾號的APPID
        $this->appKey = $appKey; //微信支付申請對應(yīng)的公眾號的APP Key
        $this->apiKey = $key;   //https://pay.weixin.qq.com 帳戶設(shè)置-安全設(shè)置-API安全-API密鑰-設(shè)置API密鑰
    }

    /**
     * 構(gòu)造獲取code的url連接
     * @param string $redirectUrl 微信服務(wù)器回跳的url旷赖,需要url編碼
     * @return 返回構(gòu)造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE" . "#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
    }
    /**
     * 拼接簽名字符串
     * @param array $urlObj
     * @return 返回已經(jīng)拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * 統(tǒng)一下單
     * @param string $openid 調(diào)用【網(wǎng)頁授權(quán)獲取用戶信息】接口獲取到用戶在該公眾號下的Openid
     * @param float $totalFee 收款總費用 單位元
     * @param string $outTradeNo 唯一的訂單號
     * @param string $orderName 訂單名稱
     * @param string $notifyUrl 支付結(jié)果通知url 不要有問號
     * @param string $timestamp 支付時間
     * @return string
     */
    public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $nonce_str = self::createNonceStr();
        //$orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家數(shù)據(jù)包,原樣返回畦徘,如果填寫中文,請注意轉(zhuǎn)換為utf-8
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => $nonce_str,
            'notify_url' => $notifyUrl,
            'openid' => $openid,            //rade_type=JSAPI,此參數(shù)必傳
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => '127.0.0.1',
            'total_fee' => intval($totalFee * 100),       //單位 轉(zhuǎn)為分
            'trade_type' => 'JSAPI',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
        //禁止引用外部xml實體
        libxml_disable_entity_loader(true);
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }

        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",
            "nonceStr" =>  $nonce_str,
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
    }
    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https請求 不驗證證書和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //設(shè)置cURL允許執(zhí)行的最長秒數(shù)
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https請求 不驗證證書和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public static function arrayToXml($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;
    }
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);

        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末劫笙,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子星岗,更是在濱河造成了極大的恐慌填大,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俏橘,死亡現(xiàn)場離奇詭異允华,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進(jìn)店門靴寂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來磷蜀,“玉大人,你說我怎么就攤上這事百炬『致。” “怎么了?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵剖踊,是天一觀的道長妓灌。 經(jīng)常有香客問我,道長蜜宪,這世上最難降的妖魔是什么虫埂? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮圃验,結(jié)果婚禮上掉伏,老公的妹妹穿的比我還像新娘。我一直安慰自己澳窑,他們只是感情好纵诞,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著罚屋,像睡著了一般璧瞬。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上麻裁,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天箍镜,我揣著相機(jī)與錄音,去河邊找鬼煎源。 笑死色迂,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的手销。 我是一名探鬼主播歇僧,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼锋拖!你這毒婦竟也來了诈悍?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤兽埃,失蹤者是張志新(化名)和其女友劉穎侥钳,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體讲仰,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡慕趴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年痪蝇,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片冕房。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡躏啰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出耙册,到底是詐尸還是另有隱情给僵,我是刑警寧澤,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布详拙,位于F島的核電站帝际,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏饶辙。R本人自食惡果不足惜蹲诀,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望弃揽。 院中可真熱鬧脯爪,春花似錦、人聲如沸矿微。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽涌矢。三九已至掖举,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間娜庇,已是汗流浹背塔次。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留思灌,地道東北人俺叭。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像泰偿,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蜈垮,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容