Smartcontract that receive tokens and ether(native BNB) and swap it through pancakeSwap router?

Hi ,

i am creating a smartcontract on BSC which receive specific BSC tokens and transfer it to smartcontract.
and then using Pancakeswap router to swap that token to MyOwnToken.

but i am unable to integrate to receive native BNB . though it works for WBNB.

any minimal example to do this?

below is code i am using...

//receiving token from user to smartcontract

IBEP20(fromToken).safeTransferFrom(msg.sender, address(this), _amount);

//swapping token

function swap(
        address _tokenIn,
        address _tokenOut,
        uint256 _amountIn,
        uint256 _amountOutMin,
        address _to
    ) private {
        //next we need to allow the pancakeswap router to spend the token we just sent to this contract
        //by calling IBEP20 approve you allow the pancakeswap contract to spend the tokens in this contract
        IBEP20(_tokenIn).safeApprove(PANCAKESWAP_ROUTER, _amountIn);

        //path is an array of addresses.
        //this path array will have 3 addresses [tokenIn, WBNB, tokenOut]
        //the if statement below takes into account if token in or token out is WBNB.  then the path is only 2 addresses
        address[] memory path;
        if (_tokenIn == WBNB || _tokenOut == WBNB) {
            path = new address[](2);
            path[0] = _tokenIn;
            path[1] = _tokenOut;
        } else {
            path = new address[](3);
            path[0] = _tokenIn;
            path[1] = WBNB;
            path[2] = _tokenOut;
        }

        //then we will call swapExactTokensForTokens
        //for the deadline we will pass in block.timestamp
        //the deadline is the latest time the trade is valid for
        IPancakeRouter(PANCAKESWAP_ROUTER).swapExactTokensForTokens(
            _amountIn,
            _amountOutMin,
            path,
            _to,
            block.timestamp
        );
    }

You usage of Approve is wrong. IBEP20(_tokenIn).safeApprove(PANCAKESWAP_ROUTER, _amountIn); means you (the custom smart contract) wants to approve the router to spend tokens. A smart contract cannot approve a token on behalf of the users.

The users need to call Approve on the token contract to approve the custom smart contract instead.