微信小程序提现功能

1,开通微信支付账号,开通 企业付款到零钱

微信小程序提现功能_第1张图片

2,上代码

 /**
     * 提现功能
     */
    public function payOrder()
    {

				$openid = input('openid');//用户openid
				$userid = input('userid/d',0);//用户uid
				$amount = input('amount/s','');//提现金额
                $User = Db::name('user')->field('id,integral')->where(['id' => $userid])->find();
                if ($User['integral'] > 0 && !empty($User)) {
                    $trade_no = 'XJ1314520521' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商户订单号
					Db::startTrans();
					try {
						//添加支付信息 pay_trade
						$data = [
							'user_id' => $userid,
							'class_id' => 3,
							'order_no' => $trade_no,
                            'trade_no' => $trade_no,
							'subject' => '职豆提现',
							'trade_channel'=>'wxpay',
							'amount'  => $amount,//提现积分
							'status'=>0,
							'create_time' => time()
						];
						Db::name('pay_trade')->insert($data);


						$card_grade = Db::name('pay_trade')->where(['order_no' => $data['order_no']])->update(['status' =>1]);//修改状态-支付中

						$data['desc'] = '职豆提现';
						$data['appid'] = 'XXXXXXXXXXX';
                        $data['openid'] = 'XXXXXXXXXXXXX';
			
                   
						$result = $this->txFunc($data['openid'],$data['order_no'],$amount,$data['desc'],$data['appid']);
                        
					
			
                        // die;
						if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS' && $card_grade){
							$partner_trade_no = Db::name('pay_order')->where(['partner_trade_no' => $result['partner_trade_no']])->count();
							if ($partner_trade_no > 0) {
								$info = [
									'payment_no' => $result['payment_no'],
									'payment_time' => $result['payment_time'],
									'status' => 1
								];
								Db::name('pay_order')->where(['partner_trade_no' => $result['partner_trade_no']])->update($info);
								Db::name('user')->where(['openid' => $openid])->update(['amount' => 0]);
							}
							$msg = [
								'code' => 0,
								'msg'    => '提现成功',
								'data' => 0
							];
							// Db::commit();
							$code = $amount['user_name'] . ':' . $amount['amount'];
							$res = $this->sendMobileCaptcha('18735393892', $code);
						} else {
							$msg = [
								'code' => 1,
								'msg'    => '提现失败',
								'data' => 1
							];
						}
					} catch (\Exception $e) {
						// 回滚事务
						Db::rollback();
					}
                     
                } else {
                    $msg = [
                        'code' => 1,
                        'msg'    => '您的余额不够提现哦~',
                        'data' => 4
                    ];
                }
    }






   /**
     * 企业支付(向微信发起企业支付到零钱的请求)
     * @param string $openid 用户openID
     * @param string $trade_no 单号
     * @param string $money 金额(单位分)
     * @param string $desc 描述
     * @param string $appid 协会appid
     * @return string   XML 结构的字符串
     **/
    public function txFunc($openid,$trade_no,$money,$desc,$appid)
    {
	
        $data = array(
            'mch_appid' => $appid,//协会appid
            'mchid' => 'XXXXXXXX',//微信支付商户号
            'nonce_str' => $this->getNonceStr(), //随机字符串
            'partner_trade_no' => $trade_no, //商户订单号,需要唯一
            'openid' => $openid,
            'check_name' => 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK:强制 NO_CHECK:
            'amount' => $money * 100, //付款金额单位为分
            'desc' => $desc,//描述信息
            'spbill_create_ip' => request()->ip(),
        );
	
        //生成签名
        $data['sign'] = $this->makeSign($data);
        
        //构造XML数据(数据包要以xml格式进行发送)
        $xmldata = $this->arrToXml($data);
        //请求url
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        //发送post请求
        $res = $this->curl_post_ssl($url,$xmldata);
        return $res;
    }




 function share($url){
        $appID='XXXXX';//小程序appID
        $appSecret='XXXXXXXXXXXXX';//小程序appSecret
        $jssdk = new JSSDK($appID, $appSecret);  
        $signPackage = $jssdk->GetSignPackage(urldecode($url));
        if(!isset($signPackage)){
            return $this->apiNullJson(101);
        }
        $data=[
            'appId'=>$appID,
            'timestamp'=>$signPackage["timestamp"],
            'nonceStr'=>$signPackage["nonceStr"],
            'signature'=>$signPackage["signature"]
        ];

        $msg = [
            'code' => 0,
            'msg'    => 'OK',
            'data' => $data
        ];
        return json($msg);
    }






/**
     * 随机字符串
     * @param int $length
     * @return string
     */
    function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    function makeSign($data)
    {
        $key="XXXXXXXXXXXXXXX";//商户秘钥 微信支付平台-》 API安全-》设置APIv2密钥
        // 关联排序
        ksort($data);
        // 字典排序
        $str = http_build_query($data);
        // 添加商户密钥
        $str .= '&key=' . $key;
        // 清理空格
        $str = urldecode($str);
        $str = md5($str);
        // 转换大写
        $result = strtoupper($str);
        return $result;
    }



     /**
     * 数组转XML
     * @param $data
     * @return string
     */
    function arrToXml($data)
    {
        $xml = "";
        //  遍历组合
        foreach ($data as $k=>$v){
            $xml.='<'.$k.'>'.$v.'';
        }
        $xml .= '';
        return $xml;
    }

    /**
     * XML转数组
     * @param string
     * return $data
     * */
    function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    /**
     * [curl_post_ssl 发送curl_post数据]
     * @param  [type]  $url     [发送地址]
     * @param  [type]  $xmldata [发送文件格式]
     * @param  [type]  $second [设置执行最长秒数]
     * @param  [type]  $aHeader [设置头部]
     * @return [type]           [description]
     */
      function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
        $isdir = "../extend/Cert/";//证书位置;绝对路径
        
        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
        curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送


        $data = curl_exec($ch);//执行回话

        if ($data) {
            curl_close($ch);
            return $this->xmlToArray($data);
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    /*
    * 发送短信验证码
    */
    function sendMobileCaptcha($mobile,$code = ''){
        $content = "您好:".$code."元提现成功";
        $dataMsg["pwd"] ='XXXXXX';
        $dataMsg["username"]='XXXXX';
        $dataMsg["mobile"] = $mobile;
        $dataMsg["content"] = $content;
        $statusCode = $this->http_post("http://api.uoleem.com.cn/sms/uoleemApi",$dataMsg);
        $arr = explode(',',$statusCode);
        return $arr;
    }
    
    /*
    * 发送POST请求
    */
    function http_post($url,$data,$param = array()){

        $ch = curl_init();
        if(!empty($param)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $param);
        }
        if (substr($url, 0, 8) == 'https://') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);//获得返回数据
        curl_close($ch);
        return $result;

    }




你可能感兴趣的:(PHP,API,小程序)